Solon v3.8.0

mcp - 服务端的反向通讯(比如采样)

</> markdown
2025年12月22日 下午7:58:37

v3.8.0 后支持:MCP 反向通讯,即服务器发起的请求 (Server-initiated requests)。主要有两种:

  • 变更通知,比如:tool 变更(框架内自动处理)
  • 反向请求,比如:sampling、roots 请求

提醒:当 server 使用 STREAMABLE_STATELESS 方式时。不支持反向通讯。

1、反向请求 (Server-initiated requests)

反向请求这个需求场景较少。Solon MCP 直接采用 SDK 接口的体验方式,只支持响应式接口(projectreactor)。

Sampling (采样)

  • 当 MCP Server 正在执行某项任务,发现需要 LLM(大语言模型)提供进一步的推理、解释或决策时,它可以向 Client 发起一个采样请求。

Roots (根目录访问)

  • 除了 Sampling,MCP 还支持 Roots List 的反向获取。 Server 可以请求 Client 提供当前用户授权访问的目录列表(Roots)。这同样属于 Server 向 Client 主动获取信息的一种“反向”行为。

2、Sampling 示例

  • 客户端
public class SamplingClientDemo {
    public void test() {
        McpClientProvider clientProvider = McpClientProvider.builder()
                .url("http://localhost:8080/mcp")
                .customize(spec -> {
                    spec.capabilities(McpSchema.ClientCapabilities.builder().sampling().build());
                    spec.sampling(req -> Mono.just(McpSchema.CreateMessageResult.builder()
                            .content(new McpSchema.TextContent("test"))
                            .build()));
                })
                .build();


        clientProvider.callToolAsText("demo", Utils.asMap("a", 1))
                .getContent();
    }
}
  • 服务端(只是示意下)
@McpServerEndpoint(channel = McpChannel.STREAMABLE, mcpEndpoint = "/mcp")
public class SamplingServerDemo {
    @ToolMapping(description = "demo")
    public Mono<McpSchema.CreateMessageResult> demo(McpAsyncServerExchange exchange) {
        return exchange.createMessage(McpSchema.CreateMessageRequest.builder().build());
    }
}