MCP 客户端 Starter(Spring Boot)

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

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

MCP 客户端 Boot Starter 提供以下功能:

  • 多客户端实例管理

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

  • 多命名传输协议支持

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

  • Application Context(应用程序上下文)关闭时自动清理资源的生命周期管理

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

Starter

Spring AI 自动配置及 Starter 模块的 artifact 名称已发生重大变更。更多信息请参阅 升级说明

标准 MCP Client

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

标准 Starter 支持通过 STDIO(进程内)和/或 SSE(远程)传输协议同时连接一个或多个 MCP 服务器。SSE 连接基于 HttpClient 传输实现。每个 MCP 服务器连接会创建一个新的 MCP 客户端实例。可选择 SYNCASYNC 模式的 MCP 客户端(注意:不可混用同步与异步客户端)。生产环境部署建议使用基于 WebFlux 的 SSE 连接(搭配 spring-ai-starter-mcp-client-webflux)。

WebFlux 客户端

WebFlux Starter 提供与标准 Starter 类似的功能,但采用基于 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

启用/禁用所有客户端的 root 变更通知

true

toolcallback.enabled

启用/禁用 MCP 工具回调与 Spring AI 工具执行框架的集成

true

Stdio 传输属性

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

属性 说明 默认值

servers-configuration

包含 MCP 服务器配置(JSON 格式)的资源文件

-

connections

命名的 stdio 连接配置 Map

-

connections.[name].command

MCP 服务器的执行命令

-

connections.[name].args

命令参数列表

-

connections.[name].env

服务器进程的环境变量 Map

-

示例配置:

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"

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

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"
      ]
    }
  }
}

当前,Claude Desktop 格式仅支持 STDIO 连接类型。

SSE 传输配置

Server-Sent Events(SSE)传输协议的属性以 spring.ai.mcp.client.sse: 为前缀。

属性 说明 默认值

connections

命名的 SSE 连接配置 Map

-

connections.[name].url

与 MCP 服务器进行 SSE 通信的 Base URL 端点

-

connections.[name].sse-endpoint

用于连接的 SSE 端点(作为 URL 后缀)

/sse

示例配置:

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

特性

Sync/Async 客户端类型

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

  • 同步模式(默认)— 适用于传统阻塞式请求-响应场景。

  • 异步模式 — 适用于非阻塞式响应式应用,需配置 spring.ai.mcp.client.type=ASYNC

自定义客户端

自动配置通过回调接口提供全面的客户端规范定制能力。这些定制器(Customizer)允许你配置 MCP 客户端行为的各个方面,包括请求超时、事件处理和消息处理等。

可自定义的类型

可用的自定义选项包括:

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

  • 自定义采样 Hanlder — 通过标准化方式使服务器能经客户端向 LLM 请求采样(补全或生成)。该流程让客户端保有模型访问、选择及权限的控制权,同时使服务器无需配置 API 密钥即可调用 AI 能力。

  • 文件系统(根目录)访问 — 客户端向服务器公开文件系统根目录的标准化方式。根目录定义了服务器在文件系统中的操作边界,使其明确可访问的目录和文件范围。支持该功能的客户端可应服务器请求提供根目录列表,并在列表变更时发送通知。

  • 事件 Handler - 当服务器发生特定事件时,客户端的处理程序会收到通知:

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

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

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

  • 日志 Handler — 服务器向客户端发送结构化日志消息的标准化方式。客户端可通过设置最低日志级别控制日志详细程度。

可根据应用需求选择实现 McpSyncClientCustomizer(同步客户端)或 McpAsyncClientCustomizer(异步客户端)。

  • 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 参数表示当前定制器(Customizer)所应用的服务器配置名称,该配置将用于创建对应的 MCP 客户端。

MCP 客户端自动配置会检测并 Application Context 中所有已定义的定制器(Customizer)。

传输协议支持

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

  • 标准输入/输出(Stdio)(通过 spring-ai-starter-mcp-client 激活)

  • SSE HTTP(通过 spring-ai-starter-mcp-client 激活)

  • SSE WebFlux(通过 spring-ai-starter-mcp-client-webflux 激活)

整合 Spring AI

该 Starter 可配置与 Spring AI 工具执行框架集成的工具回调,使 MCP 工具能作为 AI 交互的一部分使用。此集成默认启用,可通过设置属性 spring.ai.mcp.client.toolcallback.enabled=false 禁用。

用例

将对应的 Starter 依赖添加到项目中,并在 application.propertiesapplication.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 将自动配置并可供注入:

@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();

示例应用