如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

MCP 客户端Starters

The Spring AI MCP (Model Context Protocol) Client Boot Starter 为 Spring Boot 应用程序中的 MCP 客户端功能提供自动配置。它支持同步和异步客户端实现,并包含多种传输选项。spring-doc.cadn.net.cn

MCP 客户端Starters提供:spring-doc.cadn.net.cn

Starters

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

标准 MCP 客户端

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

标准Starters通过 STDIO(进程内)和/或 SSE(远程)传输同时连接到一个或多个 MCP 服务器。 SSE 连接使用基于 HttpClient 的传输实现。 每个与 MCP 服务器的连接都会创建一个新的 MCP 客户端实例。 您可以选择 SYNCASYNC MCP 客户端(注意:您不能混合使用同步和异步客户端)。 对于生产部署,我们建议使用基于 WebFlux 的 SSE 连接与 spring-ai-starter-mcp-client-webfluxspring-doc.cadn.net.cn

WebFlux 客户端

WebFlux Starters提供了与标准Starters类似的功能,但使用基于 WebFlux 的 SSE 传输实现。spring-doc.cadn.net.cn

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

配置属性

常用属性

公共属性以前缀 spring.ai.mcp.client 开头: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

namespring-doc.cadn.net.cn

MCP 客户端实例名称spring-doc.cadn.net.cn

spring-ai-mcp-clientspring-doc.cadn.net.cn

versionspring-doc.cadn.net.cn

MCP 客户端实例的版本spring-doc.cadn.net.cn

1.0.0spring-doc.cadn.net.cn

initializedspring-doc.cadn.net.cn

是否在创建时初始化客户端spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

request-timeoutspring-doc.cadn.net.cn

MCP 客户端请求的超时持续时间spring-doc.cadn.net.cn

20sspring-doc.cadn.net.cn

typespring-doc.cadn.net.cn

客户端类型(同步或异步)。所有客户端必须同为同步或异步;不支持混合使用。spring-doc.cadn.net.cn

SYNCspring-doc.cadn.net.cn

root-change-notificationspring-doc.cadn.net.cn

为所有客户端启用/禁用根变更通知spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

toolcallback.enabledspring-doc.cadn.net.cn

启用/禁用 MCP 工具回调与 Spring AI 工具执行框架的集成spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

标准输入输出传输属性

标准 I/O 传输的属性以前缀 spring.ai.mcp.client.stdio 开头:spring-doc.cadn.net.cn

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

servers-configurationspring-doc.cadn.net.cn

包含 JSON 格式的 MCP 服务器配置的资源spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

connectionsspring-doc.cadn.net.cn

命名标准输入输出连接配置的映射spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

connections.[name].commandspring-doc.cadn.net.cn

执行 MCP 服务器的命令spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

connections.[name].argsspring-doc.cadn.net.cn

命令参数列表spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

connections.[name].envspring-doc.cadn.net.cn

服务器进程的环境变量映射spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

示例配置:spring-doc.cadn.net.cn

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-doc.cadn.net.cn

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

Claude Desktop 格式如下所示:spring-doc.cadn.net.cn

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

目前,Claude Desktop 格式仅支持 STDIO 连接类型。spring-doc.cadn.net.cn

SSE 传输属性

服务器发送事件 (SSE) 传输的属性以前缀 spring.ai.mcp.client.sse 开头:spring-doc.cadn.net.cn

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

connectionsspring-doc.cadn.net.cn

命名 SSE 连接配置的映射spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

connections.[name].urlspring-doc.cadn.net.cn

用于与 MCP 服务器进行 SSE 通信的基础 URL 端点spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

connections.[name].sse-endpointspring-doc.cadn.net.cn

用于连接的 SSE 端点(作为 URL 后缀)spring-doc.cadn.net.cn

/ssespring-doc.cadn.net.cn

示例配置:spring-doc.cadn.net.cn

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

功能

同步/异步客户端类型

该Starters支持两种类型的客户端:spring-doc.cadn.net.cn

  • 同步 - 默认的客户端类型,适用于具有阻塞操作的传统请求-响应模式spring-doc.cadn.net.cn

  • 异步 - 适用于具有非阻塞操作的响应式应用程序,使用 spring.ai.mcp.client.type=ASYNC 进行配置spring-doc.cadn.net.cn

客户端自定义

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

自定义类型

以下自定义选项可用:spring-doc.cadn.net.cn

  • 请求配置 - 设置自定义请求超时时间spring-doc.cadn.net.cn

  • 自定义采样处理器 - 为服务器通过客户端向大语言模型请求采样(completionsgenerations)提供的标准化方式。此流程允许客户端保持对模型访问、选择和权限的控制,同时使服务器能够利用人工智能能力——无需服务器 API 密钥。spring-doc.cadn.net.cn

  • 文件系统(根目录)访问 - 为客户端向服务器暴露文件系统 roots 提供的标准化方式。 根目录定义了服务器在文件系统中可操作的边界,使其能够了解可以访问哪些目录和文件。 服务器可以从支持的客户端请求根目录列表,并在该列表发生变化时接收通知。spring-doc.cadn.net.cn

  • 事件处理器 - 当特定服务器事件发生时,用于通知客户端的处理器:spring-doc.cadn.net.cn

  • 日志处理器 - 服务器向客户端发送结构化日志消息的标准化方式。 客户端可以通过设置最低日志级别来控制日志详细程度spring-doc.cadn.net.cn

您可以根据应用程序的需求,实现 McpSyncClientCustomizer 用于同步客户端,或实现 McpAsyncClientCustomizer 用于异步客户端。spring-doc.cadn.net.cn

@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 客户端的服务器配置名称。spring-doc.cadn.net.cn

MCP 客户端自动配置会自动检测并应用应用程序上下文中的任何自定义器。spring-doc.cadn.net.cn

传输支持

自动配置支持多种传输类型:spring-doc.cadn.net.cn

与 Spring AI 集成

Starters可以配置与 Spring AI 的工具执行框架集成的工具回调,从而允许 MCP 工具作为 AI 交互的一部分使用。此集成默认启用,可以通过设置 spring.ai.mcp.client.toolcallback.enabled=false 属性来禁用。spring-doc.cadn.net.cn

使用示例

将适当的Starters依赖项添加到您的项目中,并在 application.propertiesapplication.yml 中配置客户端:spring-doc.cadn.net.cn

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 将自动配置并可用于注入:spring-doc.cadn.net.cn

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

// OR

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

当工具回调启用时(默认行为),所有已注册的 MCP 客户端的 MCP 工具将作为 ToolCallbackProvider 实例提供:spring-doc.cadn.net.cn

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

示例应用