此版本仍在开发中,尚未被视为稳定版本。最新的快照版本请使用 Spring AI 1.0.0-SNAPSHOT!spring-doc.cadn.net.cn

MCP 客户端启动Starters

Spring AI MCP(模型上下文协议)客户端引导Starters为 Spring Boot 应用程序中的 MCP 客户端功能提供自动配置。它支持具有各种传输选项的同步和异步客户端实现。spring-doc.cadn.net.cn

MCP Client Boot Starter 提供:spring-doc.cadn.net.cn

首先

标准 MCP 客户端

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

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

WebFlux 客户端

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

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

配置属性

通用属性

通用属性以spring.ai.mcp.client:spring-doc.cadn.net.cn

财产 描述 默认值

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

客户端类型(SYNC 或 ASYNC)。所有客户端都必须是 sync 或 async;不支持混合spring-doc.cadn.net.cn

SYNCspring-doc.cadn.net.cn

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

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

truespring-doc.cadn.net.cn

标准传输属性

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

财产 描述 默认值

servers-configurationspring-doc.cadn.net.cn

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

-spring-doc.cadn.net.cn

connectionsspring-doc.cadn.net.cn

命名 stdio 连接配置的映射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"

或者,您也可以使用 Claude Desktop 格式的外部 JSON 文件配置 stdio 连接: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

财产 描述

connectionsspring-doc.cadn.net.cn

命名 SSE 连接配置的映射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

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

特征

同步/异步客户端类型

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

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

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

客户端定制

自动配置通过回调接口提供广泛的客户端规范自定义功能。这些定制器允许您配置 MCP 客户端行为的各个方面,从请求超时到事件处理和消息处理。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 serverConfiurationName, McpClient.SyncSpec spec) {

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

        // Sets the root URIs that the server connecto 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 serverConfiurationName, McpClient.AsyncSpec spec) {
        // Customize the async client configuration
        spec.requestTimeout(Duration.ofSeconds(30));
    }
}

serverConfiurationNameparameter 是定制器所应用到的服务器配置的名称,以及为其创建 MCP 客户端的服务器配置的名称。spring-doc.cadn.net.cn

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

运输支持

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

与 Spring AI 集成

Starter 会自动配置与 Spring AI 的工具执行框架集成的工具回调,从而允许将 MCP 工具用作 AI 交互的一部分。spring-doc.cadn.net.cn

使用示例

将适当的 starter 依赖项添加到您的项目中,并在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 工具都作为 ToolCallback 列表提供 通过 ToolCallbackProvider 实例:spring-doc.cadn.net.cn

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

示例应用