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

MCP 服务Starters

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

MCP 服务器Starters提供:spring-doc.cadn.net.cn

Starters

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。spring-doc.cadn.net.cn

根据您的运输需求,选择以下其中一个启动选项:spring-doc.cadn.net.cn

标准MCP服务器

完整MCP服务器功能支持,且服务器传输为STDIOspring-doc.cadn.net.cn

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

启动程序会激活负责以下内容的McpServerAutoConfiguration自动配置:spring-doc.cadn.net.cn

WebMVC 服务器传输

完整支持MCP服务器功能,采用基于Spring MVC的SSE(服务器发送事件)服务器传输,并可选使用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(服务器发送事件)服务器传输,并可选使用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的默认行为,如果在类路径中同时存在0和1,Spring Boot将优先选择2。因此,如果您的项目使用3,建议使用4而不是5。spring-doc.cadn.net.cn

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

属性 描述 默认

enabledspring-doc.cadn.net.cn

启用或禁用Maven中心代理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

服务器类型 (同步/异步)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 表示客户端应访问 SSE 端点为 /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

同步/异步服务器类型

  • 同步服务器 - 使用 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 服务器Starters允许服务器向客户端公开工具、资源和提示。 它会根据服务器类型,自动将注册为 Spring Bean 的自定义能力处理器转换为同步/异步规范:spring-doc.cadn.net.cn

工具

允许服务器公开可由语言模型调用的工具。MCP 服务器Starters提供: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 bean * ToolCallback bean 列表 * ToolCallbackProvider beanspring-doc.cadn.net.cn

工具按名称去重,仅保留每个工具名称的首次出现。spring-doc.cadn.net.cn

工具上下文支持

<工具上下文>已支持,允许将上下文信息传递给工具调用。它在<代码>1键下包含一个<代码>0实例,可通过<代码>2访问。请参阅此<链接 t="C6">示例,演示<代码>3和<代码>4spring-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

示例应用程序