此版本仍在开发中,尚未被视为稳定版本。最新的快照版本请使用 Spring AI 1.0.0!spring-doc.cadn.net.cn

MCP 服务器启动Starters

Spring AI MCP(模型上下文协议)服务器Starters提供了在 Spring Boot 应用程序中设置 MCP 服务器的自动配置。它支持将 MCP 服务器功能与 Spring Boot 的自动配置系统无缝集成。spring-doc.cadn.net.cn

MCP Server Boot Starter 提供:spring-doc.cadn.net.cn

首先

Spring AI 自动配置、启动模块的 artifact 名称发生了重大变化。 有关更多信息,请参阅升级说明spring-doc.cadn.net.cn

根据您的运输要求选择以下Starters之一:spring-doc.cadn.net.cn

标准 MCP 服务器

完整的 MCP 服务器功能支持STDIO服务器传输。spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-server</artifactId>
</dependency>

Starters会激活McpServerAutoConfigurationauto-configuration 负责:spring-doc.cadn.net.cn

WebMVC 服务器传输

完整的 MCP 服务器功能支持SSE(Server-Sent Events) 基于 Spring MVC 的服务器传输和可选的STDIO运输。spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>

Starters会激活McpWebMvcServerAutoConfigurationMcpServerAutoConfigurationauto-configurations 提供:spring-doc.cadn.net.cn

WebFlux 服务器传输

完整的 MCP 服务器功能支持SSE(Server-Sent Events) 基于 Spring WebFlux 的服务器传输和可选的STDIO运输。spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-server-webflux</artifactId>
</dependency>

Starters会激活McpWebFluxServerAutoConfigurationMcpServerAutoConfigurationauto-configurations 提供:spring-doc.cadn.net.cn

配置属性

所有属性都以spring.ai.mcp.server:spring-doc.cadn.net.cn

属性 描述 默认值

enabledspring-doc.cadn.net.cn

启用/禁用 MCP 服务器spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

stdiospring-doc.cadn.net.cn

启用/禁用 stdio 传输spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

namespring-doc.cadn.net.cn

用于标识的服务器名称spring-doc.cadn.net.cn

mcp-serverspring-doc.cadn.net.cn

versionspring-doc.cadn.net.cn

服务器版本spring-doc.cadn.net.cn

1.0.0spring-doc.cadn.net.cn

instructionsspring-doc.cadn.net.cn

可选说明,用于向客户端提供有关如何与此服务器交互的指导spring-doc.cadn.net.cn

nullspring-doc.cadn.net.cn

typespring-doc.cadn.net.cn

服务器类型 (SYNC/ASYNC)spring-doc.cadn.net.cn

SYNCspring-doc.cadn.net.cn

capabilities.resourcespring-doc.cadn.net.cn

启用/禁用资源功能spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

capabilities.toolspring-doc.cadn.net.cn

启用/禁用工具功能spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

capabilities.promptspring-doc.cadn.net.cn

启用/禁用提示功能spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

capabilities.completionspring-doc.cadn.net.cn

启用/禁用完成功能spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

resource-change-notificationspring-doc.cadn.net.cn

启用资源更改通知spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

prompt-change-notificationspring-doc.cadn.net.cn

启用提示更改通知spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

tool-change-notificationspring-doc.cadn.net.cn

启用工具更改通知spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

tool-response-mime-typespring-doc.cadn.net.cn

(可选)每个工具名称的响应 MIME 类型。例如spring.ai.mcp.server.tool-response-mime-type.generateImage=image/png会将image/pngMIME 类型与generateImage()工具名称spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

sse-message-endpointspring-doc.cadn.net.cn

客户端用于发送消息的 Web 传输的自定义 SSE 消息终端节点路径spring-doc.cadn.net.cn

/mcp/messagespring-doc.cadn.net.cn

sse-endpointspring-doc.cadn.net.cn

用于 Web 传输的自定义 SSE 终端节点路径spring-doc.cadn.net.cn

/ssespring-doc.cadn.net.cn

base-urlspring-doc.cadn.net.cn

可选 URL 前缀。例如base-url=/api/v1表示客户端应通过/api/v1 + sse-endpoint消息端点为/api/v1 + sse-message-endpointspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

request-timeoutspring-doc.cadn.net.cn

在请求超时之前等待服务器响应的持续时间。适用于通过客户端发出的所有请求,包括工具调用、资源访问和提示作。spring-doc.cadn.net.cn

20spring-doc.cadn.net.cn

Sync/Async 服务器类型

  • 同步服务器 - 使用McpSyncServer. 它专为应用程序中的简单请求-响应模式而设计。 要启用此服务器类型,请将spring.ai.mcp.server.type=SYNC在您的配置中。 激活后,它会自动处理同步工具规格的配置。spring-doc.cadn.net.cn

  • 异步服务器 - 异步服务器实现使用McpAsyncServer并针对非阻塞作进行了优化。 要启用此服务器类型,请使用spring.ai.mcp.server.type=ASYNC. 此服务器类型会自动设置具有内置 Project Reactor 支持的异步工具规范。spring-doc.cadn.net.cn

服务器功能

MCP 服务器支持四种主要功能类型,可以单独启用或禁用:spring-doc.cadn.net.cn

默认情况下,所有功能均处于启用状态。禁用功能将阻止服务器注册和向客户端公开相应的功能。spring-doc.cadn.net.cn

交通方式

MCP 服务器支持三种传输机制,每种机制都有其专用的Starters:spring-doc.cadn.net.cn

特性和功能

MCP Server Boot Starter 允许服务器向客户端公开工具、资源和提示。 它根据服务器类型自动将注册为 Spring bean 的自定义功能处理程序转换为同步/异步规范:spring-doc.cadn.net.cn

工具

允许服务器公开可由语言模型调用的工具。MCP Server Boot Starter 提供:spring-doc.cadn.net.cn

@Bean
public ToolCallbackProvider myTools(...) {
    List<ToolCallback> tools = ...
    return ToolCallbackProvider.from(tools);
}

或使用低级 API:spring-doc.cadn.net.cn

@Bean
public List<McpServerFeatures.SyncToolSpecification> myTools(...) {
    List<McpServerFeatures.SyncToolSpecification> tools = ...
    return tools;
}

自动配置将自动检测并注册来自以下来源的所有工具回调: *个人ToolCallback豆 * 列表ToolCallback豆 *ToolCallbackProviderspring-doc.cadn.net.cn

按名称对工具进行重复数据删除,并使用每个工具名称的第一个匹配项。spring-doc.cadn.net.cn

工具上下文支持

支持 ToolContext,允许将上下文信息传递给工具调用。它包含一个McpSyncServerExchange实例exchange键,可通过McpToolUtils.getMcpExchange(toolContext).请参阅此示例演示exchange.loggingNotification(…​)exchange.createMessage(…​).spring-doc.cadn.net.cn

资源管理

为服务器提供一种标准化的方法,以便向客户端公开资源。spring-doc.cadn.net.cn

@Bean
public List<McpServerFeatures.SyncResourceSpecification> myResources(...) {
    var systemInfoResource = new McpSchema.Resource(...);
    var resourceSpecification = new McpServerFeatures.SyncResourceSpecification(systemInfoResource, (exchange, request) -> {
        try {
            var systemInfo = Map.of(...);
            String jsonContent = new ObjectMapper().writeValueAsString(systemInfo);
            return new McpSchema.ReadResourceResult(
                    List.of(new McpSchema.TextResourceContents(request.uri(), "application/json", jsonContent)));
        }
        catch (Exception e) {
            throw new RuntimeException("Failed to generate system info", e);
        }
    });

    return List.of(resourceSpecification);
}

及时管理

为服务器提供一种标准化的方法,以便向客户端公开提示模板。spring-doc.cadn.net.cn

@Bean
public List<McpServerFeatures.SyncPromptSpecification> myPrompts() {
    var prompt = new McpSchema.Prompt("greeting", "A friendly greeting prompt",
        List.of(new McpSchema.PromptArgument("name", "The name to greet", true)));

    var promptSpecification = new McpServerFeatures.SyncPromptSpecification(prompt, (exchange, getPromptRequest) -> {
        String nameArgument = (String) getPromptRequest.arguments().get("name");
        if (nameArgument == null) { nameArgument = "friend"; }
        var userMessage = new PromptMessage(Role.USER, new TextContent("Hello " + nameArgument + "! How can I assist you today?"));
        return new GetPromptResult("A personalized greeting message", List.of(userMessage));
    });

    return List.of(promptSpecification);
}

完成管理

为服务器提供一种标准化的方法,以便向客户端公开完成功能。spring-doc.cadn.net.cn

@Bean
public List<McpServerFeatures.SyncCompletionSpecification> myCompletions() {
    var completion = new McpServerFeatures.SyncCompletionSpecification(
        "code-completion",
        "Provides code completion suggestions",
        (exchange, request) -> {
            // Implementation that returns completion suggestions
            return new McpSchema.CompletionResult(List.of(
                new McpSchema.Completion("suggestion1", "First suggestion"),
                new McpSchema.Completion("suggestion2", "Second suggestion")
            ));
        }
    );

    return List.of(completion);
}

根更改使用者

当根发生变化时,支持listChanged发送 Root Change 通知。spring-doc.cadn.net.cn

@Bean
public BiConsumer<McpSyncServerExchange, List<McpSchema.Root>> rootsChangeHandler() {
    return (exchange, roots) -> {
        logger.info("Registering root resources: {}", roots);
    };
}

使用示例

标准 STDIO 服务器配置

# Using spring-ai-starter-mcp-server
spring:
  ai:
    mcp:
      server:
        name: stdio-mcp-server
        version: 1.0.0
        type: SYNC

WebMVC 服务器配置

# Using spring-ai-starter-mcp-server-webmvc
spring:
  ai:
    mcp:
      server:
        name: webmvc-mcp-server
        version: 1.0.0
        type: SYNC
        instructions: "This server provides weather information tools and resources"
        sse-message-endpoint: /mcp/messages
        capabilities:
          tool: true
          resource: true
          prompt: true
          completion: true

WebFlux 服务器配置

# Using spring-ai-starter-mcp-server-webflux
spring:
  ai:
    mcp:
      server:
        name: webflux-mcp-server
        version: 1.0.0
        type: ASYNC  # Recommended for reactive applications
        instructions: "This reactive server provides weather information tools and resources"
        sse-message-endpoint: /mcp/messages
        capabilities:
          tool: true
          resource: true
          prompt: true
          completion: true

使用 MCP 服务器创建 Spring Boot 应用程序

@Service
public class WeatherService {

    @Tool(description = "Get weather information by city name")
    public String getWeather(String cityName) {
        // Implementation
    }
}

@SpringBootApplication
public class McpServerApplication {

    private static final Logger logger = LoggerFactory.getLogger(McpServerApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(McpServerApplication.class, args);
    }

	@Bean
	public ToolCallbackProvider weatherTools(WeatherService weatherService) {
		return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
	}
}

自动配置会自动将工具回调注册为 MCP 工具。 你可以让多个 bean 生成 ToolCallbacks。自动配置将合并它们。spring-doc.cadn.net.cn

示例应用