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

STDI和SSE MCP服务器

STDIO 和 SSE MCP 服务器支持多种传输机制,每种机制都有专门的Starters。spring-doc.cadn.net.cn

使用 STIO客户端SSE客户端 连接到 STDIO 和 SSE 服务器。

STDIO MCP 服务器STDIO MCP Server

全MCP服务器功能支持,STDIO传输代码块。spring-doc.cadn.net.cn

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

Spring MVC Servlets

全MCP服务器功能支持,基于Spring MVC的Server-Sent Events服务器传输,以及可选的`STDIO`传输方式。spring-doc.cadn.net.cn

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

SSE 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

配置属性

常见属性

所有公共属性都以0前缀spring-doc.cadn.net.cn

属性 描述 默认

enabledspring-doc.cadn.net.cn

启用或禁用Maven中心代理spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

tool-callback-converterspring-doc.cadn.net.cn

启用或禁用将Spring AI ToolCallbacks转换为MCP Tool规格的操作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

request-timeoutspring-doc.cadn.net.cn

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

20 secondsspring-doc.cadn.net.cn

MCP注解属性

MCP 服务器注解提供了一种声明式方法,用于通过 Java 注解实现 MCP 服务器处理器。spring-doc.cadn.net.cn

服务器 mcp-annotations 的属性以 spring.ai.mcp.server.annotation-scanner 为前缀:spring-doc.cadn.net.cn

属性 描述 默认值

enabledspring-doc.cadn.net.cn

启用/禁用 MCP 服务器注解的自动扫描spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

SSE 属性

所有SSE属性都以 spring.ai.mcp.server 为前缀: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

keep-alive-intervalspring-doc.cadn.net.cn

连接保活间隔spring-doc.cadn.net.cn

null (已禁用)spring-doc.cadn.net.cn

出于向后兼容性的原因,SSE 属性没有额外的后缀(如 .sse)。

功能与特性

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;
}

自动配置将自动检测并注册来自以下的所有工具回调:spring-doc.cadn.net.cn

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

您可以将tool-callback-converter设置为false,以禁用所有工具回调的自动检测和注册。

工具上下文支持

<工具上下文>已支持,允许将上下文信息传递给工具调用。它在<代码>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(
        new McpSchema.PromptReference(
					"ref/prompt", "code-completion", "Provides code completion suggestions"),
        (exchange, request) -> {
            // Implementation that returns completion suggestions
            return new McpSchema.CompleteResult(List.of("python", "pytorch", "pyside"), 10, true);
        }
    );

    return List.of(completion);
}

日志记录

提供了一种标准的方法,以便服务器将结构化的日志消息发送给客户端。 在工具中,资源、提示或完成处理人使用提供的 McpSyncServerExchangeMcpAsyncServerExchangeexchange 对象来发送日志消息:spring-doc.cadn.net.cn

(exchange, request) -> {
        exchange.loggingNotification(LoggingMessageNotification.builder()
            .level(LoggingLevel.INFO)
            .logger("test-logger")
            .data("This is a test log message")
            .build());
}

在MCP客户端上,你可以注册 logging消费者来处理这些消息:spring-doc.cadn.net.cn

mcpClientSpec.loggingConsumer((McpSchema.LoggingMessageNotification log) -> {
    // Handle log messages
});

进展

提供了一种标准方法,供服务器向客户端发送进度更新。 从工具中,资源、提示或完成处理程序使用提供的 McpSyncServerExchange/McpAsyncServerExchange exchange 对象发送进度通知:spring-doc.cadn.net.cn

(exchange, request) -> {
        exchange.progressNotification(ProgressNotification.builder()
            .progressToken("test-progress-token")
            .progress(0.25)
            .total(1.0)
            .message("tool call in progress")
            .build());
}

Mcp客户端可以接收进度通知并相应地更新其用户界面。 要实现这一功能,它需要注册一个进度消费者。spring-doc.cadn.net.cn

mcpClientSpec.progressConsumer((McpSchema.ProgressNotification progress) -> {
    // Handle progress notifications
});

根目录变更记录

当根发生变化时,支持listChanged的客户端会发送根变化通知。spring-doc.cadn.net.cn

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

击打

ping机制,用于服务器验证其客户端是否仍然存活。在工具或框架中,当处理资源、提示或完成调用时,会使用提供的McpSyncServerExchangeMcpAsyncServerExchangeexchange对象来发送ping消息:spring-doc.cadn.net.cn

(exchange, request) -> {
        exchange.ping();
}

保持连接

服务器可以(可选地)定期向已连接的客户端发送 ping 请求,以验证连接健康状况。spring-doc.cadn.net.cn

默认情况下,keep-alive 是禁用的。 要启用 keep-alive,请在配置中设置 keep-alive-interval 属性:spring-doc.cadn.net.cn

spring:
  ai:
    mcp:
      server:
        keep-alive-interval: 30s

使用示例

标准 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"
        capabilities:
          tool: true
          resource: true
          prompt: true
          completion: true
        # sse properties
        sse-message-endpoint: /mcp/messages
        keep-alive-interval: 30s

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"
        capabilities:
          tool: true
          resource: true
          prompt: true
          completion: true
        # sse properties
        sse-message-endpoint: /mcp/messages
        keep-alive-interval: 30s

使用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

示例应用程序