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

可流式传输的 HTTP MCP 服务器

可流式传输的 HTTP 传输允许 MCP 服务器作为独立进程运行,通过 HTTP POST 和 GET 请求处理多个客户端连接,并支持可选的服务器发送事件(SSE)流式传输以发送多条服务器消息。它取代了 SSE 传输。spring-doc.cadn.net.cn

这些服务器随规范版本 2025-03-26 引入,非常适合需要通知客户端有关工具、资源或提示动态变化的应用程序。spring-doc.cadn.net.cn

设置 spring.ai.mcp.server.protocol=STREAMABLE 属性
使用 Streamable-HTTP 客户端 连接到 Streamable-HTTP 服务器。

可流式传输的 HTTP WebMVC 服务器

使用 spring-ai-starter-mcp-server-webmvc 依赖:spring-doc.cadn.net.cn

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

并将 spring.ai.mcp.server.protocol 属性设置为 STREAMABLEspring-doc.cadn.net.cn

可流式传输的 HTTP WebFlux 服务器

使用 spring-ai-starter-mcp-server-webflux 依赖:spring-doc.cadn.net.cn

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

并将 spring.ai.mcp.server.protocol 属性设置为 STREAMABLEspring-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

protocolspring-doc.cadn.net.cn

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

必须设置为 STREAMABLE 以启用可流式传输的服务器spring-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

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-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 Server Annotations 提供了一种使用 Java 注解以声明式方式实现 MCP 服务器处理程序的方法。spring-doc.cadn.net.cn

服务器 mcp-annotations 的属性以 spring.ai.mcp.server.annotation-scanner 为前缀: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

可流式 HTTP 属性

所有可流式 HTTP 属性均以 spring.ai.mcp.server.streamable-http 为前缀:spring-doc.cadn.net.cn

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

mcp-endpointspring-doc.cadn.net.cn

自定义 MCP 端点路径spring-doc.cadn.net.cn

/mcpspring-doc.cadn.net.cn

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

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

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

disallow-deletespring-doc.cadn.net.cn

禁止删除操作spring-doc.cadn.net.cn

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

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

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

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

工具上下文支持

支持 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 JsonMapper().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);
}

日志记录

为服务器向客户端发送结构化日志消息提供了一种标准化方式。 在工具、资源、提示或完成调用处理程序中,使用提供的 McpSyncServerExchange/McpAsyncServerExchange exchange 对象来发送日志消息: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 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

服务器用于验证其客户端是否仍然存活的机制。 在工具、资源、提示或完成调用处理程序中,使用提供的 McpSyncServerExchange/McpAsyncServerExchange exchange 对象来发送心跳消息:spring-doc.cadn.net.cn

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

保持活跃

服务器可以选择性地定期向已连接的客户端发送心跳检测,以验证连接的健康状态。spring-doc.cadn.net.cn

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

spring:
  ai:
    mcp:
      server:
        streamable-http:
          keep-alive-interval: 30s
目前,对于可流式传输的 HTTP 服务器,保持存活机制仅适用于 监听来自服务器的消息(SSE) 连接。

使用示例

可流式 HTTP 服务器配置

# Using spring-ai-starter-mcp-server-streamable-webmvc
spring:
  ai:
    mcp:
      server:
        protocol: STREAMABLE
        name: streamable-mcp-server
        version: 1.0.0
        type: SYNC
        instructions: "This streamable server provides real-time notifications"
        resource-change-notification: true
        tool-change-notification: true
        prompt-change-notification: true
        streamable-http:
          mcp-endpoint: /api/mcp
          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