侧边栏壁纸
博主头像
AI中文站

write sth

  • 累计撰写 39 篇文章
  • 累计创建 3 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Spring AI-MCP Client Boot Starter

Spring AI MCP(模型上下文协议)客户端启动器 (Spring AI MCP Client Boot Starter) 为 Spring Boot 应用程序中的 MCP 客户端功能提供自动配置。
它支持具有多种传输选项的同步和异步客户端实现。

MCP 客户端启动器提供:

  • 管理多个客户端实例

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

  • 支持多个命名传输

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

  • 正确的生命周期管理,在应用程序上下文关闭时自动清理资源

  • 通过定制器 (customizers) 进行可定制的客户端创建

启动器 (Starters)

Spring AI 的自动配置、启动器模块的工件名称发生了重大变化。请参阅升级说明以获取更多信息。

标准 MCP 客户端 (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

WebFlux 客户端 (WebFlux Client)

WebFlux 启动器提供与标准启动器类似的功能,但使用基于 WebFlux 的 SSE 传输实现。

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

配置属性 (Configuration Properties)

通用属性 (Common Properties)

通用属性以 spring.ai.mcp.client 为前缀:

属性 (Property)

描述 (Description)

默认值 (Default Value)

enabled

启用/禁用 MCP 客户端

true

name

MCP 客户端实例的名称(用于兼容性检查)

spring-ai-mcp-client

version

MCP 客户端实例的版本

1.0.0

initialized

是否在创建时初始化客户端

true

request-timeout

MCP 客户端请求的超时时长

20s

type

客户端类型 (SYNCASYNC)。所有客户端必须都是同步或异步;不支持混合。

SYNC

root-change-notification

为所有客户端启用/禁用根变更通知

true

toolcallback.enabled

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

true

标准输入输出传输属性 (Stdio Transport Properties)

标准输入输出传输的属性以 spring.ai.mcp.client.stdio 为前缀:

属性 (Property)

描述 (Description)

默认值 (Default Value)

servers-configuration

包含 JSON 格式 MCP 服务器配置的资源

-

connections

命名 stdio 连接配置的映射

-

connections.[name].command

用于执行 MCP 服务器的命令

-

connections.[name].args

命令参数列表

-

connections.[name].env

服务器进程的环境变量映射

-

配置示例:

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 文件(采用 Claude Desktop 格式)配置 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 传输属性 (SSE Transport Properties)

服务器发送事件 (SSE) 传输的属性以 spring.ai.mcp.client.sse 为前缀:

属性 (Property)

描述 (Description)

默认值 (Default Value)

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:8080
            server2:
              url: http://otherserver:8081
              sse-endpoint: /custom-sse

特性 (Features)

同步/异步客户端类型 (Sync/Async Client Types)
启动器支持两种类型的客户端:

  • 同步 (Synchronous) - 默认客户端类型,适用于具有阻塞操作的传统请求-响应模式

  • 异步 (Asynchronous) - 适用于具有非阻塞操作的反应式应用程序,使用 spring.ai.mcp.client.type=ASYNC 配置

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

定制类型 (Customization Types)
提供以下定制选项:

  • 请求配置 (Request Configuration) - 设置自定义请求超时

  • 自定义采样处理器 (Custom Sampling Handlers) - 服务器通过客户端从 LLM 请求 LLM 采样(补全或生成)的标准化方式。此流程允许客户端在无需服务器 API 密钥的情况下,保持对模型访问、选择和权限的控制,同时使服务器能够利用 AI 功能。

  • 文件系统(根)访问 (File system (Roots) Access) - 客户端向服务器公开文件系统根的标准化方式。根定义了服务器可以在文件系统中操作的边界,使它们能够了解可以访问哪些目录和文件。服务器可以从支持它们的客户端请求根列表,并在该列表更改时接收通知。

  • 事件处理器 (Event Handlers) - 当特定服务器事件发生时通知客户端的处理程序:

-工具变更通知 (Tools change notifications) - 当可用服务器工具列表发生变化时
-资源变更通知 (Resources change notifications) - 当可用服务器资源列表发生变化时
-提示变更通知 (Prompts change notifications) - 当可用服务器提示列表发生变化时

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

您可以根据应用程序的需求实现 McpSyncClientCustomizer(用于同步客户端)或 McpAsyncClientCustomizer(用于异步客户端)。

同步 (Sync)

@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 客户端的服务器配置的名称。

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

传输支持 (Transport Support)

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

  • 标准输入输出 (Standard 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 集成 (Integration with Spring AI)

启动器可以配置工具回调,这些回调与 Spring AI 的工具执行框架集成,允许将 MCP 工具用作 AI 交互的一部分。此集成默认启用,可以通过设置属性 spring.ai.mcp.client.toolcallback.enabled=false 来禁用。

使用示例 (Usage Example)

将适当的启动器依赖项添加到您的项目中,并在 application.propertiesapplication.yml 中配置客户端:

spring:
  ai:
    mcp:
      client:
        enabled: true
        name: my-mcp-client
        version: 1.0.0
        request-timeout: 30s
        type: SYNC  # 对于反应式应用程序使用 ASYNC
        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;  // 用于同步客户端

// 或者

@Autowired
private List<McpAsyncClient> mcpAsyncClients;  // 用于异步客户端

当工具回调启用时(默认行为),所有 MCP 客户端注册的 MCP 工具都作为一个 ToolCallbackProvider 实例提供:

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

示例应用程序 (Example Applications)

Brave 网络搜索聊天机器人 (Brave Web Search Chatbot) - 一个使用模型上下文协议与网络搜索服务器交互的聊天机器人。

默认 MCP 客户端启动器 (Default MCP Client Starter) - 使用默认 spring-ai-starter-mcp-client MCP 客户端启动器的简单示例。

WebFlux MCP 客户端启动器 (WebFlux MCP Client Starter) - 使用 spring-ai-starter-mcp-client-webflux MCP 客户端启动器的简单示例。

其他资源 (Additional Resources)

[Spring AI 文档](Spring AI Documentation)

[模型上下文协议规范](Model Context Protocol Specification)

[Spring Boot 自动配置](Spring Boot Auto-configuration)

0

评论区