STDIO 和 SSE MCP 服务器

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

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

STDIO MCP 服务器

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

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

SSE WebMVC 服务器

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

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

SSE WebFlux 服务器

完整的MCP服务器功能支持SSE(服务器发送事件)基于 Spring WebFlux 的服务器传输,并可选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 将优先处理调度器服务.因此,如果你的项目使用Spring Boot启动网,建议使用Spring-AI-starter-MCP-Server-webmvc而不是Spring-AI-starter-mcp-server-webflux.spring-doc.cadn.net.cn

配置属性

常见性质

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

属性 描述 默认值

启用spring-doc.cadn.net.cn

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

truespring-doc.cadn.net.cn

工具回调转换器spring-doc.cadn.net.cn

启用/禁用将 Spring AI ToolCallback 转换为 MCP 工具规范spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

标准spring-doc.cadn.net.cn

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

falsespring-doc.cadn.net.cn

名称spring-doc.cadn.net.cn

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

MCP-服务器spring-doc.cadn.net.cn

版本spring-doc.cadn.net.cn

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

1.0.0spring-doc.cadn.net.cn

指示spring-doc.cadn.net.cn

可选指令,指导客户端如何与该服务器交互spring-doc.cadn.net.cn

spring-doc.cadn.net.cn

类型spring-doc.cadn.net.cn

服务器类型(同步/非同步)spring-doc.cadn.net.cn

同步spring-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

能力。完成spring-doc.cadn.net.cn

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

truespring-doc.cadn.net.cn

资源变更通知spring-doc.cadn.net.cn

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

truespring-doc.cadn.net.cn

提示-变更-通知spring-doc.cadn.net.cn

启用即时变更通知spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

工具更换通知spring-doc.cadn.net.cn

启用刀具更换通知spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

工具-反应-哑剧型spring-doc.cadn.net.cn

可选响应 MIME 类型,按工具名称。例如spring.ai.mcp.server.tool-response-mime-type.generateImage=image/png将关联图片/PNGMIME类型具有生成图像()工具名称spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

请求超时spring-doc.cadn.net.cn

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

20秒spring-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

属性 描述 默认值

启用spring-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-消息-端点spring-doc.cadn.net.cn

客户端用于发送消息的定制SSE消息端点路径,用于网页传输spring-doc.cadn.net.cn

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

SSE-端点spring-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-端点消息端点为/api/v1 + SSE-消息-端点spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

保持生命间隔spring-doc.cadn.net.cn

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

(残疾)spring-doc.cadn.net.cn

出于向后兼容性考虑,SSE 属性没有额外的后缀(例如.sse).

功能与功能

MCP 服务器启动Starters允许服务器向客户端暴露工具、资源和提示符。它自动将注册为 Spring Beans 的自定义能力处理程序转换为基于服务器类型的同步/异步规范: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

你可以通过设置工具回调转换器false.

工具上下文支持

支持ToolContext,允许将上下文信息传递给工具调用。它包含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(
        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);
}

Logging

为服务器向客户端发送结构化日志消息提供了标准化方式。在工具、资源、提示符或完成调用处理器中,可以使用提供的McpSyncServerExchange/McpAsyncServerExchange 交换发送日志消息的对象: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客户端上,你可以注册日志消费者以处理以下消息:spring-doc.cadn.net.cn

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

进展

为服务器提供向客户端发送进度更新的标准化方式。在工具、资源、提示符或完成调用处理器内部,可以使用提供的McpSyncServerExchange/McpAsyncServerExchange 交换发送进度通知的对象: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客户端可以接收进度通知并相应更新其UI。为此,它需要注册一个进度消费者。spring-doc.cadn.net.cn

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

根列表变更

当根源改变时,支持的客户端列表已更改发送根更更通知。spring-doc.cadn.net.cn

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

服务器验证客户端仍然存活的ping机制。在工具、资源、提示符或完成调用处理器内,使用提供的McpSyncServerExchange/McpAsyncServerExchange 交换发送ping消息的对象:spring-doc.cadn.net.cn

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

保持生命

服务器可以选择性地定期向连接的客户端发送ping以验证连接健康。spring-doc.cadn.net.cn

默认情况下,保持生命功能被禁用。要启用保持生命功能,请设置保持生命间隔你的配置中的属性: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工具。你可以有多个豆子生成ToolCallback,自动配置会将它们合并。spring-doc.cadn.net.cn

应用示例