Spring AI MCP 客户端
文章目录
- 简述
- maven 配置
- 标准 MCP 客户端
- WebFlux 客户端
- 配置属性
- 共同属性
- Stdio 传输属性
- 示例
- 配置文件
- 启动类
- SSE 传输属性
- 同步/异步客户端类型
- 启动器支持两种类型的客户端:
- 客户端定制
- 自定义类型
- 运输支持
- 与 Spring AI 集成
- 配置文件案例
- 示例

简述
Spring AI MCP(模型上下文协议)客户端启动启动器为 Spring Boot 应用程序中的 MCP 客户端功能提供自动配置。它支持具有各种传输选项的同步和异步客户端实现。
MCP 客户端启动器提供:
- 管理多个客户端实例
- 自动客户端初始化(如果启用)
- 支持多个命名传输
- 与 Spring AI 的工具执行框架集成
- 适当的生命周期管理,在应用程序上下文关闭时自动清理资源
- 通过定制器创建可定制的客户端
maven 配置
标准 MCP 客户端
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>
标准启动器通过(进程内)和/或(远程)传输同时连接到一个或多个 MCP 服务器。 SSE 连接使用基于 HttpClient 的传输实现。 与 MCP 服务器的每次连接都会创建一个新的 MCP 客户端实例。 您可以选择 MCP 客户端(注意:不能混合使用同步和异步客户端)。 对于生产部署,我们建议将基于 WebFlux 的 SSE 连接与 .STDIOSSESYNCASYNCspring-ai-starter-mcp-client-webflux
WebFlux 客户端
WebFlux 启动器提供与标准启动器类似的功能,但使用基于 WebFlux 的 SSE 传输实现。
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-mcp-client-webflux</artifactId>
</dependency>
配置属性
共同属性
公共属性前缀为 :spring.ai.mcp.client
财产 | 描述 | 默认值 |
---|---|---|
enabled | 启用/禁用 MCP 客户端 | true |
name | MCP 客户端实例的名称(用于兼容性检查) | spring-ai-mcp-client |
version | MCP 客户端实例的版本 | 1.0.0 |
initialized | 是否在创建时初始化客户端 | true |
request-timeout | MCP 客户端请求的超时持续时间 | 20s |
type | 客户端类型(SYNC 或 ASYNC)。所有客户端必须是同步或异步的;不支持混合 | SYNC |
root-change-notification | 为所有客户端启用/禁用根更改通知 | true |
toolcallback.enabled | 启用/禁用 MCP 工具回调与 Spring AI 的工具执行框架的集成 | true |
Stdio 传输属性
标准 I/O 传输的属性以 : 为前缀:spring.ai.mcp.client.stdio
财产 | 描述 | 默认值 |
---|---|---|
servers-configuration | 包含 JSON 格式的 MCP 服务器配置的资源 | - |
connections | 命名 stdio 连接配置的映射 | - |
connections.[name].command | 要为 MCP 服务器执行的命令 | - |
connections.[name].args | 命令参数列表 | - |
connections.[name].env | 服务器进程的环境变量映射 | - |
spring:ai:mcp:client:stdio:root-change-notification: trueconnections:server1:command: /path/to/serverargs:- --port=8080- --mode=productionenv:API_KEY: your-api-keyDEBUG: "true"
或者,您可以使用 Claude Desktop 格式的外部 JSON 文件配置 stdio 连接:
spring:ai:mcp:client:stdio:servers-configuration: classpath:mcp-servers.json
Claude 桌面格式如下所示:
{"mcpServers": {"filesystem": {"command": "npx","args": ["-y","@modelcontextprotocol/server-filesystem","/Users/username/Desktop","/Users/username/Downloads"]}}
}
示例
配置文件
mcp-servers-config.json
{"mcpServers": { //连接的多个 MCP 服务"brave-search": { // MCP 服务的名称"command": "C:\\Program Files\\nodejs\\npx.cmd", // 执行命令"args": ["@modelcontextprotocol/server-brave-search" //MCP 服务包名],"env": {"BRAVE_API_KEY":"BSA_test" // 额外参数}}}
}
application.yaml
spring:ai:zhipuai:api-key: "test"embedding:options:model: "embedding-2"chat:options:model: "glm-4-air"mcp:client:stdio:servers-configuration: 'classpath:mcp-servers-config.json'
maven 配置
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-zhipuai</artifactId>
</dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>
启动类
Spring boot 启动 时 作为 bean 注入 使用 同步 mcp
ChatClient.Builder chatClientBuilder
- 根据yaml 文件配置model 进行自动装配
List<McpSyncClient> mcpSyncClients
- 根据配置mcp信息进行自动装配
MessageWindowChatMemory
- 短时间记忆默认应该在10条信息左右
@SpringBootApplication
public class AiApplication {public static void main(String[] args) {SpringApplication.run(AiApplication.class, args);}@Beanpublic CommandLineRunner chatbot(ChatClient.Builder chatClientBuilder, List<McpSyncClient> mcpSyncClients) {return args -> {var chatClient = chatClientBuilder.defaultSystem("You are useful assistant and can perform web searches Brave's search API to reply to your questions.").defaultToolCallbacks(new SyncMcpToolCallbackProvider(mcpSyncClients)) // 完成工具注入.defaultAdvisors(MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build()).build();// Start the chat loopSystem.out.println("\nI am your AI assistant.\n");try (Scanner scanner = new Scanner(System.in)) {while (true) {System.out.print("\nUSER: ");System.out.println("\nASSISTANT: " +chatClient.prompt(scanner.nextLine()) // Get the user input.call().content());}}};}
}
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:server1:url: http://localhost:8080server2:url: http://otherserver:8081sse-endpoint: /custom-sse
同步/异步客户端类型
启动器支持两种类型的客户端:
同步 - 默认客户端类型,适用于具有阻塞作的传统请求-响应模式
异步 - 适用于具有非阻塞作的响应式应用程序,使用spring.ai.mcp.client.type=ASYNC
客户端定制
自动配置通过回调接口提供广泛的客户端规范自定义功能。这些定制器允许您配置 MCP 客户端行为的各个方面,从请求超时到事件处理和消息处理。
自定义类型
以下自定义选项可用:
- 请求配置 - 设置自定义请求超时
- 自定义采样处理程序 - 服务器通过客户端向 LLM 请求 LLM 采样(或)的标准化方式。此流程允许客户端保持对模型访问、选择和权限的控制,同时使服务器能够利用 AI 功能,而无需服务器 API 密钥。completionsgenerations
- 文件系统(根)访问 - 客户端向服务器公开文件系统的标准化方式。 根定义了服务器可以在文件系统中运行的位置的边界,使它们能够了解它们可以访问哪些目录和文件。 服务器可以向支持客户端请求根列表,并在该列表更改时接收通知。roots
- 事件处理程序 - 当发生某个服务器事件时要通知的客户端处理程序:
- 工具更改通知 - 当可用服务器工具列表更改时
- 资源更改通知 - 当可用服务器资源列表发生更改时。
- 提示更改通知 - 当可用服务器列表提示更改时。
- 日志记录处理程序 - 服务器向客户端发送结构化日志消息的标准化方式。 客户端可以通过设置最低日志级别来控制日志详细程度
您可以为同步客户端或异步客户端实现,具体取决于应用程序的需求。McpSyncClientCustomizerMcpAsyncClientCustomizer
同步
/*** 这是一个 Spring 的 @Component 类,用于自定义 MCP(Model Control Protocol)同步客户端的配置。* 它实现了 McpSyncClientCustomizer 接口,并重写了 customize 方法。*/
@Component
public class CustomMcpSyncClientCustomizer implements McpSyncClientCustomizer {/*** 重写 customize 方法,用于对 MCP 客户端进行自定义配置。** @param serverConfigurationName 服务器配置的名称* @param spec 用于配置 MCP 客户端的 SyncSpec 对象*/@Overridepublic void customize(String serverConfigurationName, McpClient.SyncSpec spec) {// 设置请求的超时时间为 30 秒spec.requestTimeout(Duration.ofSeconds(30));// 设置该客户端可以访问的根 URI(roots 是一个外部定义的变量)spec.roots(roots);// 设置一个自定义的采样处理器,用于处理创建消息的请求spec.sampling((CreateMessageRequest messageRequest) -> {// 在这里处理采样逻辑,例如生成或修改消息CreateMessageResult result = ... // 实际的处理结果return result;});// 添加一个消费者,当可用的工具发生变化时(如新增或删除工具)会被通知spec.toolsChangeConsumer((List<McpSchema.Tool> tools) -> {// 在这里处理工具变化的逻辑});// 添加一个消费者,当可用的资源发生变化时(如新增或删除资源)会被通知spec.resourcesChangeConsumer((List<McpSchema.Resource> resources) -> {// 在这里处理资源变化的逻辑});// 添加一个消费者,当可用的提示词(Prompt)发生变化时(如新增或删除提示词)会被通知spec.promptsChangeConsumer((List<McpSchema.Prompt> prompts) -> {// 在这里处理提示词变化的逻辑});// 添加一个消费者,当从服务器接收到日志消息时会被调用spec.loggingConsumer((McpSchema.LoggingMessageNotification log) -> {// 在这里处理接收到的日志消息});}
}
异步
/*** 这是一个 Spring 的 @Component 组件,用于自定义 MCP 异步客户端的配置。* 它实现了 McpAsyncClientCustomizer 接口,并重写了 customize 方法。*/
@Component
public class CustomMcpAsyncClientCustomizer implements McpAsyncClientCustomizer {/*** 重写 customize 方法,用于对 MCP 异步客户端进行自定义配置。** @param serverConfigurationName 服务器配置的名称* @param spec 用于配置异步 MCP 客户端的 AsyncSpec 对象*/@Overridepublic void customize(String serverConfigurationName, McpClient.AsyncSpec spec) {// 设置异步请求的超时时间为 30 秒spec.requestTimeout(Duration.ofSeconds(30));}
}
运输支持
自动配置支持多种传输类型:
- 标准 I/O (Stdio)(由spring-ai-starter-mcp-client)
- SSE HTTP(由spring-ai-starter-mcp-client)
- SSE WebFlux(由spring-ai-starter-mcp-client-webflux)
与 Spring AI 集成
入门者可以配置与 Spring AI 的工具执行框架集成的工具回调,从而允许将 MCP 工具用作 AI 交互的一部分。默认情况下,此集成处于启用状态,可以通过设置属性来禁用。spring.ai.mcp.client.toolcallback.enabled=false
配置文件案例
spring:ai:mcp:client:enabled: truename: my-mcp-clientversion: 1.0.0request-timeout: 30stype: SYNC # or ASYNC for reactive applicationssse:connections:server1:url: http://localhost:8080server2:url: http://otherserver:8081stdio:root-change-notification: falseconnections:server1:command: /path/to/serverargs:- --port=8080- --mode=productionenv:API_KEY: your-api-keyDEBUG: "true"
MCP 客户端 bean 将自动配置并可用于注入:
@Autowired
private List<McpSyncClient> mcpSyncClients; // For sync client// OR@Autowired
private List<McpAsyncClient> mcpAsyncClients; // For async client
启用工具回调(默认行为)时,所有 MCP 客户端的注册 MCP 工具将作为实例提供:ToolCallbackProvider
@Autowired
private SyncMcpToolCallbackProvider toolCallbackProvider;
ToolCallback[] toolCallbacks = toolCallbackProvider.getToolCallbacks();
示例
application.yaml
server:port: 8087
spring:ai:zhipuai:api-key: "test"embedding:options:model: "embedding-2"chat:options:model: "glm-4-air"mcp:client:sse:connections:server1:url: http://localhost:8080
配置 ai 启动类
@SpringBootApplication
public class AiApplication {public static void main(String[] args) {SpringApplication.run(AiApplication.class, args);}@Beanpublic CommandLineRunner predefinedQuestions(ChatClient.Builder chatClientBuilder, ToolCallbackProvider tools, ConfigurableApplicationContext context) {return (args) -> {ChatClient chatClient = chatClientBuilder.defaultToolCallbacks(new ToolCallbackProvider[]{tools}).build();System.out.println("\n>>> QUESTION: 当前时间");System.out.println("\n>>> ASSISTANT: " + chatClient.prompt("当前时间").call().content());context.close();};}
}
对应mcp 服务器
public class McpToolClient {@Tool(description = "Testing method, used to test whether the tool is called")public String helloworld(){return "hello, world";}@Tool(description = "获取当前时间")public String nowTime(){// 定义日期格式SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 获取当前时间Date now = new Date();// 转换为字符串String nowStr = sdf.format(now);return "当前时间: " + nowStr;}
}
sse mcp服务器配置案例
https://blog.csdn.net/ling_zhi_xin/article/details/149298267