跳到主要内容
版本:2.0.1

MCP 客户端启动器

QWen 3.8 中英对照 MCP Client Boot Starters MCP Client Boot Starter

Spring AI MCP(Model Context Protocol)客户端 Boot Starter 为 Spring Boot 应用提供 MCP 客户端功能的自动配置。它支持多种传输选项,同时提供同步和异步客户端实现。

MCP Client Boot Starter 提供了:

  • 管理多个客户端实例

  • 自动初始化客户端(如果已启用)

  • 支持多种命名传输方式(STDIO、Http/SSE 和 Streamable HTTP)

  • 与 Spring AI 工具执行框架集成

  • 支持工具过滤功能,以便选择性包含或排除工具

  • 可定制的工具名称前缀生成机制,以避免命名冲突

  • 完善的生命周期管理,在应用上下文关闭时自动清理资源

  • 通过自定义器(customizers)实现可定制的客户端创建

快速开始​

标准 MCP 客户端​

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

标准启动器同时通过 STDIO(进程内)、SSE、Streamable-HTTP 和 Stateless Streamable-HTTP 传输方式连接一个或多个 MCP 服务器。SSE 和 Streamable-Http 传输方式使用基于 JDK HttpClient 的传输实现。每次连接 MCP 服务器都会创建一个新的 MCP 客户端实例。您可以选择 SYNC 或 ASYNC MCP 客户端(注意:不能混用同步和异步客户端)。对于生产环境部署,我们推荐使用基于 WebFlux 的 SSE & StreamableHttp 连接,并配合 spring-ai-starter-mcp-client-webflux 使用。

WebFlux 客户端​

WebFlux starter 提供了与标准 starter 类似的功能,但使用基于 WebFlux 的 Streamable-Http、无状态 Streamable-Http 和 SSE 传输实现。

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

配置属性​

常见属性​

通用属性以 spring.ai.mcp.client 为前缀:

属性描述默认值
enabled启用/禁用 MCP 客户端true
nameMCP 客户端实例名称spring-ai-mcp-client
versionMCP 客户端实例版本1.0.0
initialized创建时是否初始化客户端true
request-timeoutMCP 客户端请求的超时时长20s
type客户端类型(SYNC 或 ASYNC)。所有客户端必须为同步或异步,不支持混用SYNC
root-change-notification启用/禁用所有客户端的根路径变更通知true
toolcallback.enabled启用/禁用与 Spring AI 工具执行框架集成的 MCP 工具回调true

MCP 注释属性​

MCP 客户端注解(MCP Client Annotations)提供了一种声明式的方法,使用 Java 注解实现 MCP 客户端处理器。客户端 mcp-annotations 属性的前缀为 spring.ai.mcp.client.annotation-scanner:

属性描述默认值
enabled启用/禁用 MCP client 注解的自动扫描功能true

Stdio 传输属性​

标准 I/O 传输的属性以 spring.ai.mcp.client.stdio 为前缀:

PropertyDescriptionDefault Value
servers-configuration包含 JSON 格式 MCP 服务器配置的资源-
connections命名 stdio 连接配置的映射-
connections.[name].command用于执行 MCP 服务器的命令-
connections.[name].args命令参数列表-
connections.[name].env用于服务器进程的环境变量映射-

示例配置:

spring:
ai:
mcp:
client:
stdio:
root-change-notification: true
connections:
server1:
command: /path/to/server
args:
- --port=8080
- --mode=production
env:
API_KEY: your-api-key
DEBUG: "true"

或者,您可以使用外部 JSON 文件来配置 stdio 连接,采用 Claude Desktop 格式:

spring:
ai:
mcp:
client:
stdio:
servers-configuration: classpath:mcp-servers.json

Claude Desktop 格式如下所示:

{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/username/Desktop",
"/Users/username/Downloads"
]
}
}
}

Windows 标准输入输出(STDIO)配置​

important

在 Windows 上,诸如 npx、npm 和 node 等命令是通过批处理文件(.cmd)实现的,而非原生可执行文件。Java 的 ProcessBuilder 无法直接执行批处理文件,需要借助 cmd.exe /c 包装器。

为什么 Windows 需要特殊处理​

当 Java 的 ProcessBuilder(由 StdioClientTransport 内部使用)在 Windows 上尝试启动进程时,它只能执行:

  • 原生可执行文件(.exe 文件)
  • 可供 cmd.exe 使用的系统命令

像 npx.cmd、npm.cmd,甚至 python.cmd(来自 Microsoft Store)这样的 Windows 批处理文件,都需要 cmd.exe shell 来执行。

解决方案:cmd.exe 包装器​

使用 cmd.exe /c 包装批处理文件命令:

Windows 配置:

{
"mcpServers": {
"filesystem": {
"command": "cmd.exe",
"args": [
"/c",
"npx",
"-y",
"@modelcontextprotocol/server-filesystem",
"C:\\Users\\username\\Desktop"
]
}
}
}

Linux/macOS 配置:

{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/username/Desktop"
]
}
}
}

跨平台编程配置​

对于需要在不同平台上运行且无需单独配置文件的程序,请在您的 Spring Boot 应用中实现操作系统检测:

@Bean(destroyMethod = "close")
@ConditionalOnMissingBean(McpSyncClient.class)
public McpSyncClient mcpClient() {
ServerParameters stdioParams;

if (isWindows()) {
// Windows: cmd.exe /c npx approach
var winArgs = new ArrayList<>(Arrays.asList(
"/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "target"));
stdioParams = ServerParameters.builder("cmd.exe")
.args(winArgs)
.build();
} else {
// Linux/Mac: direct npx approach
stdioParams = ServerParameters.builder("npx")
.args("-y", "@modelcontextprotocol/server-filesystem", "target")
.build();
}

return McpClient.sync(new StdioClientTransport(stdioParams, McpJsonDefaults.getMapper()))
.requestTimeout(Duration.ofSeconds(10))
.build()
.initialize();
}

private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("win");
}
备注

在使用通过 @Bean 进行的编程式配置时,请添加 @ConditionalOnMissingBean(McpSyncClient.class),以避免与来自 JSON 文件的自动配置发生冲突。

路径注意事项​

相对路径(推荐,以提升可移植性):

{
"command": "cmd.exe",
"args": ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "target"]
}

MCP 服务器基于应用程序的工作目录解析相对路径。

绝对路径(Windows 需要反斜杠或转义的正斜杠):

{
"command": "cmd.exe",
"args": ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "C:\\Users\\username\\project\\target"]
}

依赖 cmd.exe 的常见 Windows 批处理文件​

  • npx.cmd,npm.cmd - Node 包管理器

  • python.cmd - Python(Microsoft Store 安装)

  • pip.cmd - Python 包管理器

  • mvn.cmd - Maven 包装器

  • gradle.cmd - Gradle 包装器

  • 自定义的 .cmd 或 .bat 脚本

参考实现​

参见 Spring AI 示例 - Filesystem 中完整的跨平台 MCP 客户端实现,该实现会自动检测操作系统并相应地配置客户端。

流式 HTTP 传输属性​

用于连接 Streamable-HTTP 和 Stateless Streamable-HTTP MCP 服务器。

Streamable-HTTP 传输的属性以 spring.ai.mcp.client.streamable-http 为前缀:

属性描述默认值
connections具名 Streamable-HTTP 连接配置的映射-
connections.[name].url与 MCP 服务器进行 Streamable-Http 通信的基础 URL 端点-
connections.[name].endpoint用于该连接的 streamable-http 端点(作为 URL 后缀)/mcp

示例配置:

spring:
ai:
mcp:
client:
streamable-http:
connections:
server1:
url: http://localhost:8080
server2:
url: http://otherserver:8081
endpoint: /custom-sse

SSE 传输属性​

服务器发送事件 (SSE) 传输的属性以 spring.ai.mcp.client.sse 为前缀:

属性描述默认值
connections具名 SSE 连接配置的映射-
connections.[name].url用于与 MCP 服务器进行 SSE 通信的基础 URL 端点-
connections.[name].sse-endpoint用于该连接的 sse 端点(作为 URL 后缀)/sse

示例配置:

spring:
ai:
mcp:
client:
sse:
connections:
# Simple configuration using default /sse endpoint
server1:
url: http://localhost:8080
# Custom SSE endpoint
server2:
url: http://otherserver:8081
sse-endpoint: /custom-sse
# Complex URL with path and token (like MCP Hub)
mcp-hub:
url: http://localhost:3000
sse-endpoint: /mcp-hub/sse/cf9ec4527e3c4a2cbb149a85ea45ab01
# SSE endpoint with query parameters
api-server:
url: https://api.example.com
sse-endpoint: /v1/mcp/events?token=abc123&format=json

URL 拆分指南​

当您拥有完整的 SSE URL 时,请将其拆分为基础 URL 和端点路径:

完整 URL配置
http://localhost:3000/mcp-hub/sse/token123url: [localhost:3000](http://localhost:3000)
sse-endpoint: /mcp-hub/sse/token123
https://api.service.com/v2/events?key=secreturl: [api.service.com](https://api.service.com)
sse-endpoint: /v2/events?key=secret
http://localhost:8080/sseurl: [localhost:8080](http://localhost:8080)
sse-endpoint: /sse(或省略以使用默认值)

排查 SSE 连接​

404 Not Found 错误:

  • 验证 URL 拆分:确保基础 url 仅包含协议、主机和端口
  • 检查 sse-endpoint 是否以 / 开头,且包含完整的路径和查询参数
  • 直接在浏览器或 curl 中测试完整 URL,以确认其可访问性

Streamable HTTP 传输属性​

Streamable Http 传输方式的属性以 spring.ai.mcp.client.streamable-http 为前缀:

属性描述默认值
connections具名 Streamable Http 连接配置映射表-
connections.[name].url用于与 MCP 服务器进行 Streamable-Http 通信的 Base URL 端点-
connections.[name].endpoint用于该连接的 streamable-http 端点(作为 URL 后缀)/mcp

示例配置:

spring:
ai:
mcp:
client:
streamable-http:
connections:
server1:
url: http://localhost:8080
server2:
url: http://otherserver:8081
endpoint: /custom-sse

功能​

同步/异步客户端类型​

Starter 支持两种类型的客户端:

  • 同步 - 默认客户端类型(spring.ai.mcp.client.type=SYNC),适用于基于阻塞操作的传统请求-响应模式

注意: SYNC 客户端仅注册同步的 MCP 注解方法。异步方法将被忽略。

  • 异步——适用于具有非阻塞操作的响应式应用,使用 spring.ai.mcp.client.type=ASYNC 进行配置

NOTE: ASYNC 客户端仅会注册带有异步 MCP 注解的方法。同步方法将被忽略。

客户端定制​

自动配置通过回调接口提供了广泛的客户端规范定制能力。这些定制器允许您配置 MCP 客户端行为的各个方面,从请求超时到事件处理和消息处理。

自定义类型​

提供以下自定义选项:

  • 请求配置 - 设置自定义请求超时

  • 自定义采样处理器 - 一种标准化的方式,允许服务器通过客户端向 LLM 请求采样(completions 或 generations)。此流程允许客户端保持对模型访问、选择和权限的控制,同时让服务器能够利用 AI 能力——且无需服务器 API 密钥。

  • 文件系统(根目录)访问 - 一种标准化的方式,允许客户端向服务器暴露文件系统的 roots。根目录定义了服务器在文件系统中可操作的边界,使其能够了解拥有访问权限的目录和文件。服务器可以从支持的客户端处请求根目录列表,并在该列表发生变化时接收通知。

  • 信息征询处理器 - 一种标准化的方式,允许服务器在交互过程中通过客户端向用户请求额外信息。

  • 事件处理器 - 客户端的处理器,用于在特定服务器事件发生时收到通知:

    • 工具变更通知 - 当可用服务器工具列表发生变化时

    • 资源变更通知 - 当可用服务器资源列表发生变化时。

    • 提示词变更通知 - 当可用服务器提示词列表发生变化时。

    • 日志处理器 - 一种标准化的方式,允许服务器向客户端发送结构化日志消息。

    • 进度处理器 - 一种标准化的方式,允许服务器向客户端发送结构化进度消息。

客户端可以通过设置最低日志级别来控制日志详细程度

客户端定制示例​

根据应用程序的需求,您可以为同步客户端实现 McpCustomizer<McpClient.SyncSpec>,或为异步客户端实现 McpCustomizer<McpClient.AsyncSpec>。

@Component
public class CustomMcpSyncClientCustomizer implements McpClientCustomizer<McpClient.SyncSpec> {
@Override
public void customize(String serverConfigurationName, McpClient.SyncSpec spec) {

// Customize the request timeout configuration
spec.requestTimeout(Duration.ofSeconds(30));

// Sets the root URIs that this client can access.
spec.roots(roots);

// Sets a custom sampling handler for processing message creation requests.
spec.sampling((CreateMessageRequest messageRequest) -> {
// Handle sampling
CreateMessageResult result = ...
return result;
});

// Sets a custom elicitation handler for processing elicitation requests.
spec.elicitation((ElicitRequest request) -> {
// handle elicitation
return new ElicitResult(ElicitResult.Action.ACCEPT, Map.of("message", request.message()));
});

// Adds a consumer to be notified when progress notifications are received.
spec.progressConsumer((ProgressNotification progress) -> {
// Handle progress notifications
});

// Adds a consumer to be notified when the available tools change, such as tools
// being added or removed.
spec.toolsChangeConsumer((List<McpSchema.Tool> tools) -> {
// Handle tools change
});

// Adds a consumer to be notified when the available resources change, such as resources
// being added or removed.
spec.resourcesChangeConsumer((List<McpSchema.Resource> resources) -> {
// Handle resources change
});

// Adds a consumer to be notified when the available prompts change, such as prompts
// being added or removed.
spec.promptsChangeConsumer((List<McpSchema.Prompt> prompts) -> {
// Handle prompts change
});

// Adds a consumer to be notified when logging messages are received from the server.
spec.loggingConsumer((McpSchema.LoggingMessageNotification log) -> {
// Handle log messages
});
}
}

serverConfigurationName 参数是自定义器所应用的服务器配置的名称,同时也是为其创建 MCP 客户端的服务器配置名称。

MCP 客户端的自动配置会检测并应用应用程序上下文中发现的所有自定义器(customizers)。

传输支持​

自动配置支持多种传输类型:

  • 标准 I/O(Stdio)(由 spring-ai-starter-mcp-client 和 spring-ai-starter-mcp-client-webflux 激活)
  • (HttpClient) HTTP/SSE 和 Streamable-HTTP(由 spring-ai-starter-mcp-client 激活)
  • (WebFlux) HTTP/SSE 和 Streamable-HTTP(由 spring-ai-starter-mcp-client-webflux 激活)

工具过滤​

MCP Client Boot Starter 支持通过 McpToolFilter 接口对发现的工具进行过滤。这允许您基于自定义条件(如 MCP 连接信息或工具属性)选择性包含或排除工具。

要实现工具过滤,请创建一个实现了 McpToolFilter 接口的 Bean:

@Component
public class CustomMcpToolFilter implements McpToolFilter {

@Override
public boolean test(McpConnectionInfo connectionInfo, McpSchema.Tool tool) {
// Filter logic based on connection information and tool properties
// Return true to include the tool, false to exclude it

// Example: Exclude tools from a specific client
if (connectionInfo.clientInfo().name().equals("restricted-client")) {
return false;
}

// Example: Only include tools with specific names
if (tool.name().startsWith("allowed_")) {
return true;
}

// Example: Filter based on tool description or other properties
if (tool.description() != null &&
tool.description().contains("experimental")) {
return false;
}

return true; // Include all other tools by default
}
}

McpConnectionInfo 记录提供对以下内容的访问:

  • clientCapabilities - MCP 客户端的能力
  • clientInfo - MCP 客户端的相关信息(名称和版本)
  • initializeResult - 来自 MCP 服务器的初始化结果

过滤器会被自动检测并应用于同步和异步的 MCP 工具回调提供者。如果未提供自定义过滤器,则默认包含所有已发现的工具。

注意:在应用程序上下文中应只定义一个 McpToolFilter Bean。如果需要多个过滤器,请将它们组合成一个单一的复合过滤器实现。

工具名称前缀生成​

MCP Client Boot Starter 支持通过 McpToolNamePrefixGenerator 接口自定义工具名称前缀的生成。此功能通过在工具名称中添加唯一的前缀,有助于在集成来自多个 MCP 服务器的工具时避免命名冲突。

默认情况下,如果未提供自定义的 McpToolNamePrefixGenerator Bean,starter 将使用 DefaultMcpToolNamePrefixGenerator,以确保在所有 MCP 客户端连接中工具名称的唯一性。默认生成器:

  • 跟踪所有现有连接和工具名称,以确保唯一性
  • 通过将非字母数字字符替换为下划线来格式化工具名称(例如,my-tool 变为 my_tool)
  • 当在不同连接中检测到重复的工具名称时,添加计数器前缀(例如,alt_1_toolName、alt_2_toolName)
  • 保证线程安全且保持幂等性 - 相同的 (client, server, tool) 组合始终获得相同的唯一名称
  • 确保最终名称不超过 64 个字符(如有必要,从开头进行截断)

例如:* 工具 search 的第一次出现 → search * 来自不同连接的第二次工具 search 出现 → alt_1_search * 包含特殊字符的工具 my-special-tool → my_special_tool

您可以通过提供自己的实现来自定义此行为:

@Component
public class CustomToolNamePrefixGenerator implements McpToolNamePrefixGenerator {

@Override
public String prefixedToolName(McpConnectionInfo connectionInfo, Tool tool) {
// Custom logic to generate prefixed tool names

// Example: Use server name and version as prefix
String serverName = connectionInfo.initializeResult().serverInfo().name();
String serverVersion = connectionInfo.initializeResult().serverInfo().version();
return serverName + "_v" + serverVersion.replace(".", "_") + "_" + tool.name();
}
}

McpConnectionInfo 记录提供了关于 MCP 连接的全面信息:

  • clientCapabilities - MCP 客户端的能力
  • clientInfo - MCP 客户端的信息(名称、标题和版本)
  • initializeResult - MCP 服务器的初始化结果,包括服务器信息

内置前缀生成器​

该框架提供了一些内置的前缀生成器:

  • DefaultMcpToolNamePrefixGenerator - 通过跟踪重复项并在必要时添加计数器前缀来确保工具名称唯一(如果未提供自定义 bean,则默认使用)

  • McpToolNamePrefixGenerator.noPrefix() - 返回不带任何前缀的工具名称(如果多个服务器提供同名的工具,可能会导致冲突)

要完全禁用前缀并使用原始工具名称(如果在多个 MCP 服务器中使用时,不建议这样做),请将 no-prefix 生成器注册为 Bean:

@Configuration
public class McpConfiguration {

@Bean
public McpToolNamePrefixGenerator mcpToolNamePrefixGenerator() {
return McpToolNamePrefixGenerator.noPrefix();
}
}

前缀生成器会通过 Spring 的 ObjectProvider 机制,自动检测并应用于同步和异步 MCP 工具回调提供者。如果未提供自定义的生成器 Bean,系统将自动使用 DefaultMcpToolNamePrefixGenerator。

注意

当配合多个 MCP 服务器使用 McpToolNamePrefixGenerator.noPrefix() 时,重复的工具名称会导致 IllegalStateException。默认的 DefaultMcpToolNamePrefixGenerator 通过自动为重复的工具名称添加唯一前缀来防止此问题。

Tool Context 到 MCP Meta 转换器​

MCP Client Boot Starter 支持通过 ToolContextToMcpMetaConverter 接口,对 Spring AI 的 ToolContext 进行可自定义的转换,以映射为 MCP 工具调用元数据。此功能允许你将额外的上下文信息(例如用户 ID、密钥令牌)作为元数据,与 LLM 生成的调用参数一同传递。

例如,你可以将 MCP progressToken 传递到工具上下文中的 MCP Progress Flow,以跟踪长时运行操作的进度:

ChatModel chatModel = ...

String response = ChatClient.create(chatModel)
.prompt("Tell me more about the customer with ID 42")
.toolContext(Map.of("progressToken", "my-progress-token"))
.call()
.content();

默认情况下,如果未提供自定义转换器 Bean,starter 将使用 ToolContextToMcpMetaConverter.defaultConverter(),其功能如下:

  • 过滤掉 MCP 交换密钥(McpToolUtils.TOOL_CONTEXT_MCP_EXCHANGE_KEY)

  • 过滤掉值为 null 的条目

  • 将所有其他上下文条目作为元数据传递

您可以通过提供自己的实现来自定义此行为:

@Component
public class CustomToolContextToMcpMetaConverter implements ToolContextToMcpMetaConverter {

@Override
public Map<String, Object> convert(ToolContext toolContext) {
if (toolContext == null || toolContext.getContext() == null) {
return Map.of();
}

// Custom logic to convert tool context to MCP metadata
Map<String, Object> metadata = new HashMap<>();

// Example: Add custom prefix to all keys
for (Map.Entry<String, Object> entry : toolContext.getContext().entrySet()) {
if (entry.getValue() != null) {
metadata.put("app_" + entry.getKey(), entry.getValue());
}
}

// Example: Add additional metadata
metadata.put("timestamp", System.currentTimeMillis());
metadata.put("source", "spring-ai");

return metadata;
}
}

内置转换器​

该框架提供了内置的转换器:

  • ToolContextToMcpMetaConverter.defaultConverter() - 过滤掉 MCP 交换键和 null 值(如果在未提供自定义 bean 的情况下默认使用此方法)

  • ToolContextToMcpMetaConverter.noOp() - 返回一个空 map,从而有效地禁用上下文到元数据的转换

若要完全禁用上下文到元数据的转换:

@Configuration
public class McpConfiguration {

@Bean
public ToolContextToMcpMetaConverter toolContextToMcpMetaConverter() {
return ToolContextToMcpMetaConverter.noOp();
}
}

转换器会通过 Spring 的 ObjectProvider 机制自动检测并应用于同步和异步的 MCP 工具回调。如果未提供自定义的转换器 bean,系统将自动使用默认转换器。

禁用 MCP ToolCallback 自动配置​

MCP ToolCallback 自动配置默认启用,但可以通过设置 spring.ai.mcp.client.toolcallback.enabled=false 属性来禁用。

禁用时,不会从可用的 MCP 工具中创建 ToolCallbackProvider bean。

MCP 客户端注释​

MCP 客户端启动器会自动检测并注册带有注解的方法,以处理各种 MCP 客户端操作:

  • @McpLogging - 处理来自 MCP 服务器的日志消息通知

  • @McpSampling - 处理来自 MCP 服务器用于 LLM 补全的采样请求

  • @McpElicitation - 处理提示请求以从用户处收集额外信息

  • @McpProgress - 处理长时运行操作的进度通知

  • @McpToolListChanged - 处理服务器工具列表变更的通知

  • @McpResourceListChanged - 处理服务器资源列表变更的通知

  • @McpPromptListChanged - 处理服务器提示词列表变更的通知

用法示例:

@Component
public class McpClientHandlers {

@McpLogging(clients = "server1")
public void handleLoggingMessage(LoggingMessageNotification notification) {
System.out.println("Received log: " + notification.level() +
" - " + notification.data());
}

@McpSampling(clients = "server1")
public CreateMessageResult handleSamplingRequest(CreateMessageRequest request) {
// Process the request and generate a response
String response = generateLLMResponse(request);

return CreateMessageResult.builder(Role.ASSISTANT, response, "gpt-4")
.build();
}

@McpProgress(clients = "server1")
public void handleProgressNotification(ProgressNotification notification) {
double percentage = notification.progress() * 100;
System.out.println(String.format("Progress: %.2f%% - %s",
percentage, notification.message()));
}

@McpToolListChanged(clients = "server1")
public void handleToolListChanged(List<McpSchema.Tool> updatedTools) {
System.out.println("Tool list updated: " + updatedTools.size() + " tools available");
// Update local tool registry
toolRegistry.updateTools(updatedTools);
}
}

注解支持同步和异步实现,并可通过 clients 参数为特定客户端进行配置:

@McpLogging(clients = "server1")
public void handleServer1Logs(LoggingMessageNotification notification) {
// Handle logs from specific server
logToFile("server1.log", notification);
}

@McpSampling(clients = "server1")
public Mono<CreateMessageResult> handleAsyncSampling(CreateMessageRequest request) {
return Mono.fromCallable(() -> {
String response = generateLLMResponse(request);
return CreateMessageResult.builder(Role.ASSISTANT, response, "gpt-4")
.build();
}).subscribeOn(Schedulers.boundedElastic());
}

有关所有可用注释及其使用模式的详细信息,请参阅 MCP Client Annotations 文档。

使用示例​

将合适的 starter 依赖项添加到项目中,并在 application.properties 或 application.yml 中配置客户端:

spring:
ai:
mcp:
client:
enabled: true
name: my-mcp-client
version: 1.0.0
request-timeout: 30s
type: SYNC # or ASYNC for reactive applications
sse:
connections:
server1:
url: http://localhost:8080
server2:
url: http://otherserver:8081
streamable-http:
connections:
server3:
url: http://localhost:8083
endpoint: /mcp
stdio:
root-change-notification: false
connections:
server1:
command: /path/to/server
args:
- --port=8080
- --mode=production
env:
API_KEY: your-api-key
DEBUG: "true"

MCP 客户端 Bean 将自动配置并可注入使用:

@Autowired
private List<McpSyncClient> mcpSyncClients; // For sync client

// OR

@Autowired
private List<McpAsyncClient> mcpAsyncClients; // For async client

启用工具回调时(默认行为),与所有 MCP 客户端关联的已注册 MCP Tools 会作为 ToolCallbackProvider 实例提供:

@Autowired
private SyncMcpToolCallbackProvider toolCallbackProvider;
ToolCallback[] toolCallbacks = toolCallbackProvider.getToolCallbacks();

应用示例​

更多资源​