MCP Client Boot Starter
Spring AI MCP (Model Context Protocol) 客户端引导启动器为 Spring Boot 应用程序中的 MCP 客户端功能提供了自动配置。它支持同步和异步客户端实现以及各种传输选项。
The Spring AI MCP (Model Context Protocol) Client Boot Starter provides auto-configuration for MCP client functionality in Spring Boot applications. It supports both synchronous and asynchronous client implementations with various transport options.
MCP 客户端引导启动器提供:
The MCP Client Boot Starter provides:
-
多个客户端实例的管理
-
Management of multiple client instances
-
自动客户端初始化(如果启用)
-
Automatic client initialization (if enabled)
-
支持多个命名传输
-
Support for multiple named transports
-
与 Spring AI 的工具执行框架集成
-
Integration with Spring AI’s tool execution framework
-
适当的生命周期管理,在应用程序上下文关闭时自动清理资源
-
Proper lifecycle management with automatic cleanup of resources when the application context is closed
-
通过定制器实现可定制的客户端创建
-
Customizable client creation through customizers
Starters
Spring AI 自动配置、启动器模块的工件名称发生了重大变化。请参阅 upgrade notes 以获取更多信息。 There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the upgrade notes for more information. |
Standard MCP Client
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>
标准启动器通过 STDIO
(进程内)和/或 SSE
(远程)传输同时连接到一个或多个 MCP 服务器。SSE 连接使用基于 HttpClient 的传输实现。每次与 MCP 服务器的连接都会创建一个新的 MCP 客户端实例。您可以选择 SYNC
或 ASYNC
MCP 客户端(注意:不能混合使用同步和异步客户端)。对于生产部署,我们建议使用基于 WebFlux 的 SSE 连接和 spring-ai-starter-mcp-client-webflux
。
The standard starter connects simultaneously to one or more MCP servers over STDIO
(in-process) and/or SSE
(remote) transports.
The SSE connection uses the HttpClient-based transport implementation.
Each connection to an MCP server creates a new MCP client instance.
You can choose either SYNC
or ASYNC
MCP clients (note: you cannot mix sync and async clients).
For production deployment, we recommend using the WebFlux-based SSE connection with the spring-ai-starter-mcp-client-webflux
.
WebFlux Client
WebFlux 启动器提供与标准启动器类似的功能,但使用基于 WebFlux 的 SSE 传输实现。
The WebFlux starter provides similar functionality to the standard starter but uses a WebFlux-based SSE transport implementation.
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-client-webflux</artifactId>
</dependency>
Configuration Properties
Common Properties
通用属性以 spring.ai.mcp.client
为前缀:
The common properties are prefixed with spring.ai.mcp.client
:
Property | Description | Default Value |
---|---|---|
|
Enable/disable the MCP client |
|
|
Name of the MCP client instance (used for compatibility checks) |
|
|
Version of the MCP client instance |
|
|
Whether to initialize clients on creation |
|
|
Timeout duration for MCP client requests |
|
|
Client type (SYNC or ASYNC). All clients must be either sync or async; mixing is not supported |
|
|
Enable/disable root change notifications for all clients |
|
|
Enable/disable the MCP tool callback integration with Spring AI’s tool execution framework |
|
Stdio Transport Properties
标准 I/O 传输的属性以 spring.ai.mcp.client.stdio
为前缀:
Properties for Standard I/O transport are prefixed with spring.ai.mcp.client.stdio
:
Property | Description | Default Value |
---|---|---|
|
Resource containing the MCP servers configuration in JSON format |
- |
|
Map of named stdio connection configurations |
- |
|
The command to execute for the MCP server |
- |
|
List of command arguments |
- |
|
Map of environment variables for the server process |
- |
示例配置:
Example configuration:
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 format :
Alternatively, you can configure stdio connections using an external JSON file using the Claude Desktop format:
spring:
ai:
mcp:
client:
stdio:
servers-configuration: classpath:mcp-servers.json
Claude Desktop 格式如下所示:
The Claude Desktop format looks like this:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/username/Desktop",
"/Users/username/Downloads"
]
}
}
}
目前,Claude Desktop 格式仅支持 STDIO 连接类型。
Currently, the Claude Desktop format supports only STDIO connection types.
SSE Transport Properties
服务器发送事件 (SSE) 传输的属性以 spring.ai.mcp.client.sse
为前缀:
Properties for Server-Sent Events (SSE) transport are prefixed with spring.ai.mcp.client.sse
:
Property | Description | Default Value |
---|---|---|
|
Map of named SSE connection configurations |
- |
|
Base URL endpoint for SSE communication with the MCP server |
- |
|
the sse endpoint (as url suffix) to use for the connection |
|
示例配置:
Example configuration:
spring:
ai:
mcp:
client:
sse:
connections:
server1:
url: http://localhost:8080
server2:
url: http://otherserver:8081
sse-endpoint: /custom-sse
Features
Sync/Async Client Types
启动器支持两种类型的客户端:
The starter supports two types of clients:
-
同步 - 默认客户端类型,适用于具有阻塞操作的传统请求-响应模式
-
Synchronous - default client type, suitable for traditional request-response patterns with blocking operations
-
异步 - 适用于具有非阻塞操作的响应式应用程序,使用
spring.ai.mcp.client.type=ASYNC
进行配置 -
Asynchronous - suitable for reactive applications with non-blocking operations, configured using
spring.ai.mcp.client.type=ASYNC
Client Customization
自动配置通过回调接口提供了广泛的客户端规范定制功能。这些定制器允许您配置 MCP 客户端行为的各个方面,从请求超时到事件处理和消息处理。
The auto-configuration provides extensive client spec customization capabilities through callback interfaces. These customizers allow you to configure various aspects of the MCP client behavior, from request timeouts to event handling and message processing.
Customization Types
提供以下定制选项:
The following customization options are available:
-
Request Configuration - 设置自定义请求超时
-
Request Configuration - Set custom request timeouts
-
Custom Sampling Handlers - 服务器通过客户端向 LLM 请求 LLM 采样(
completions
或generations
)的标准化方式。此流程允许客户端保持对模型访问、选择和权限的控制,同时使服务器能够利用 AI 功能——无需服务器 API 密钥。 -
Custom Sampling Handlers - standardized way for servers to request LLM sampling (
completions
orgenerations
) from LLMs via clients. This flow allows clients to maintain control over model access, selection, and permissions while enabling servers to leverage AI capabilities — with no server API keys necessary. -
File system (Roots) Access - 客户端向服务器公开文件系统
roots
的标准化方式。根定义了服务器可以在文件系统内操作的边界,允许它们了解它们有权访问哪些目录和文件。服务器可以向支持客户端请求根列表,并在列表更改时接收通知。 -
File system (Roots) Access - standardized way for clients to expose filesystem
roots
to servers. Roots define the boundaries of where servers can operate within the filesystem, allowing them to understand which directories and files they have access to. Servers can request the list of roots from supporting clients and receive notifications when that list changes. -
Event Handlers - 当发生特定服务器事件时通知客户端的处理程序:
-
工具更改通知 - 当可用服务器工具列表更改时
-
Tools change notifications - when the list of available server tools changes
-
资源更改通知 - 当可用服务器资源列表更改时。
-
Resources change notifications - when the list of available server resources changes.
-
提示更改通知 - 当可用服务器提示列表更改时。
-
Prompts change notifications - when the list of available server prompts changes.
-
-
Event Handlers - client’s handler to be notified when a certain server event occurs:
-
工具更改通知 - 当可用服务器工具列表更改时
-
Tools change notifications - when the list of available server tools changes
-
资源更改通知 - 当可用服务器资源列表更改时。
-
Resources change notifications - when the list of available server resources changes.
-
提示更改通知 - 当可用服务器提示列表更改时。
-
Prompts change notifications - when the list of available server prompts changes.
-
-
Logging Handlers - 服务器向客户端发送结构化日志消息的标准化方式。客户端可以通过设置最低日志级别来控制日志的详细程度。
-
Logging Handlers - standardized way for servers to send structured log messages to clients. Clients can control logging verbosity by setting minimum log levels
你可以根据应用程序的需求,实现同步客户端的` McpSyncClientCustomizer
或异步客户端的
McpAsyncClientCustomizer
`。
You can implement either McpSyncClientCustomizer
for synchronous clients or McpAsyncClientCustomizer
for asynchronous clients, depending on your application’s needs.
-
Sync
-
Async
@Component
public class CustomMcpSyncClientCustomizer implements McpSyncClientCustomizer {
@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;
});
// 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
});
}
}
@Component
public class CustomMcpAsyncClientCustomizer implements McpAsyncClientCustomizer {
@Override
public void customize(String serverConfigurationName, McpClient.AsyncSpec spec) {
// Customize the async client configuration
spec.requestTimeout(Duration.ofSeconds(30));
}
}
` serverConfigurationName
`参数是正在应用自定义器并且为其创建MCP客户端的服务器配置的名称。
The serverConfigurationName
parameter is the name of the server configuration that the customizer is being applied to and the MCP Client is created for.
MCP客户端的自动配置会自动检测并应用在应用程序上下文中找到的任何自定义器。
The MCP client auto-configuration automatically detects and applies any customizers found in the application context.
Transport Support
自动配置支持多种传输类型:
The auto-configuration supports multiple transport types:
-
标准 I/O (Stdio) (通过
spring-ai-starter-mcp-client
激活) -
Standard I/O (Stdio) (activated by the
spring-ai-starter-mcp-client
) -
SSE HTTP (通过
spring-ai-starter-mcp-client
激活) -
SSE HTTP (activated by the
spring-ai-starter-mcp-client
) -
SSE WebFlux (通过
spring-ai-starter-mcp-client-webflux
激活) -
SSE WebFlux (activated by the
spring-ai-starter-mcp-client-webflux
)
Integration with Spring AI
启动器可以配置工具回调,使其与 Spring AI 的工具执行框架集成,从而允许 MCP 工具作为 AI 交互的一部分使用。此集成默认启用,可以通过设置 spring.ai.mcp.client.toolcallback.enabled=false
属性来禁用。
The starter can configure tool callbacks that integrate with Spring AI’s tool execution framework, allowing MCP tools to be used as part of AI interactions. This integration is enabled by default and can be disabled by setting the spring.ai.mcp.client.toolcallback.enabled=false
property.
Usage Example
将适当的启动器依赖项添加到您的项目中,并在 application.properties
或 application.yml
中配置客户端:
Add the appropriate starter dependency to your project and configure the client in application.properties
or 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
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 将自动配置并可用于注入:
The MCP client beans will be automatically configured and available for injection:
@Autowired
private List<McpSyncClient> mcpSyncClients; // For sync client
// OR
@Autowired
private List<McpAsyncClient> mcpAsyncClients; // For async client
当启用工具回调(默认行为)时,已注册的 MCP 工具将与所有 MCP 客户端一起作为 ToolCallbackProvider
实例提供:
When tool callbacks are enabled (the default behavior), the registered MCP Tools with all MCP clients are provided as a ToolCallbackProvider
instance:
@Autowired
private SyncMcpToolCallbackProvider toolCallbackProvider;
ToolCallback[] toolCallbacks = toolCallbackProvider.getToolCallbacks();
Example Applications
-
Brave Web Search Chatbot - 一个聊天机器人,使用模型上下文协议与网络搜索服务器交互。
-
Brave Web Search Chatbot - A chatbot that uses the Model Context Protocol to interact with a web search server.
-
Default MCP Client Starter - 使用默认
spring-ai-starter-mcp-client
MCP 客户端启动器的一个简单示例。 -
Default MCP Client Starter - A simple example of using the default
spring-ai-starter-mcp-client
MCP Client Boot Starter. -
WebFlux MCP Client Starter - 使用
spring-ai-starter-mcp-client-webflux
MCP 客户端启动器的一个简单示例。 -
WebFlux MCP Client Starter - A simple example of using the
spring-ai-starter-mcp-client-webflux
MCP Client Boot Starter.