如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

MCP Server Boot Starters

The Spring AI MCP (Model Context Protocol) Server Boot Starter 为在 Spring Boot 应用程序中设置 MCP 服务器提供自动配置。它实现了 MCP 服务器功能与 Spring Boot 自动配置系统的无缝集成。spring-doc.cadn.net.cn

The MCP Server Boot Starter 提供以下功能:spring-doc.cadn.net.cn

Starters

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

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

标准 MCP 服务器

完全支持 MCP Server 功能,使用 STDIO 服务器传输。spring-doc.cadn.net.cn

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

Starters激活了负责以下内容的 McpServerAutoConfiguration 自动配置:spring-doc.cadn.net.cn

WebMVC 服务器传输

基于 Spring MVC 的 SSE(服务器发送事件)服务器传输提供完整的 MCP 服务器功能支持,以及可选的 STDIO 传输。spring-doc.cadn.net.cn

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

该Starters激活 McpWebMvcServerAutoConfigurationMcpServerAutoConfiguration 自动配置,以提供:spring-doc.cadn.net.cn

WebFlux 服务器传输

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

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

该Starters激活 McpWebFluxServerAutoConfigurationMcpServerAutoConfiguration 自动配置,以提供:spring-doc.cadn.net.cn

由于 Spring Boot 的默认行为,当类路径中同时存在 org.springframework.web.servlet.DispatcherServletorg.springframework.web.reactive.DispatcherHandler 时,Spring Boot 将优先使用 DispatcherServlet。因此,如果您的项目使用了 spring-boot-starter-web,建议改用 spring-ai-starter-mcp-server-webmvc 而不是 spring-ai-starter-mcp-server-webfluxspring-doc.cadn.net.cn

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

<property> </property> <description> </description> 默认

enabledspring-doc.cadn.net.cn

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

truespring-doc.cadn.net.cn

stdiospring-doc.cadn.net.cn

启用/禁用标准输入输出传输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

服务器类型(同步/异步)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/png MIME 类型与 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 的 sse 端点,而消息端点是 /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

同步/异步服务器类型

  • 同步服务器 - 使用 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.ai.mcp.server.capabilities.tool=true|false 启用/禁用工具功能spring-doc.cadn.net.cn

  • 资源 - 使用 spring.ai.mcp.server.capabilities.resource=true|false 启用/禁用资源功能spring-doc.cadn.net.cn

  • 提示词 - 使用 spring.ai.mcp.server.capabilities.prompt=true|false 启用/禁用提示词功能spring-doc.cadn.net.cn

  • 补全 - 使用 spring.ai.mcp.server.capabilities.completion=true|false 启用/禁用补全功能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 beans * ToolCallback beans 的列表 * ToolCallbackProvider beansspring-doc.cadn.net.cn

工具按名称去重,使用每个工具名称首次出现的实例。spring-doc.cadn.net.cn

工具上下文支持

支持 ToolContext,允许将上下文信息传递给工具调用。它在 exchange 键下包含一个 McpSyncServerExchange 实例,可通过 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 的客户端会发送根节点变更通知。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 工具。 您可以有多个生成 ToolCallbacks 的 Bean。自动配置会将它们合并。spring-doc.cadn.net.cn

示例应用