MCP 客戶端啟動器

Spring AI MCP(模型上下文協議)客戶端啟動器為 Spring Boot 應用中的 MCP 客戶端功能提供了自動配置。它支援同步和非同步客戶端實現以及多種傳輸選項。

MCP 客戶端啟動器提供以下功能

  • 多客戶端例項管理

  • 自動客戶端初始化(如果啟用)

  • 支援多種命名傳輸

  • 與 Spring AI 的工具執行框架整合

  • 適當的生命週期管理,並在應用上下文關閉時自動清理資源

  • 透過定製器實現可定製的客戶端建立

啟動器

Spring AI 自動配置和啟動器模組的 artifact 名稱發生了重大變化。請參考升級注意事項瞭解更多資訊。

標準 MCP 客戶端

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

標準啟動器可以透過 STDIO(程序內)和/或 SSE(遠端)傳輸同時連線到一個或多個 MCP 伺服器。SSE 連線使用基於 HttpClient 的傳輸實現。每個與 MCP 伺服器的連線都會建立一個新的 MCP 客戶端例項。您可以選擇 SYNCASYNC MCP 客戶端(注意:不能混用同步和非同步客戶端)。對於生產環境部署,我們建議使用基於 WebFlux 的 SSE 連線以及 spring-ai-starter-mcp-client-webflux

WebFlux 客戶端

WebFlux 啟動器提供與標準啟動器類似的功能,但使用基於 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

客戶端型別(SYNCASYNC)。所有客戶端必須是同步或非同步中的一種;不支援混合使用

SYNC

root-change-notification

對所有客戶端啟用/停用根目錄更改通知

true

toolcallback.enabled

啟用/停用 MCP 工具回撥與 Spring AI 工具執行框架的整合

false

Stdio 傳輸屬性

標準 I/O 傳輸的屬性以 spring.ai.mcp.client.stdio 為字首

屬性 描述 預設值

servers-configuration

包含 JSON 格式的 MCP 伺服器配置的資源

-

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"

或者,您可以使用外部 JSON 檔案配置 stdio 連線,使用Claude Desktop 格式

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 通訊的基本 URL 端點

-

connections.[name].sse-endpoint

用於該連線的 SSE 端點(作為 URL 字尾)

/sse

配置示例

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

功能特性

同步/非同步客戶端型別

啟動器支援兩種型別的客戶端

  • 同步 - 預設客戶端型別,適用於傳統的請求-響應模式和阻塞操作

  • 非同步 - 適用於響應式應用和非阻塞操作,使用 spring.ai.mcp.client.type=ASYNC 配置

客戶端定製

自動配置透過回撥介面提供了廣泛的客戶端規範定製能力。這些定製器允許您配置 MCP 客戶端行為的各個方面,從請求超時到事件處理和訊息處理。

定製型別

以下定製選項可用

  • 請求配置 - 設定自定義請求超時

  • 自定義取樣處理器 - 伺服器透過客戶端從 LLM 請求 LLM 取樣(completionsgenerations)的標準方式。此流程允許客戶端保持對模型訪問、選擇和許可權的控制,同時使伺服器能夠利用 AI 能力 — 無需伺服器 API 金鑰。

  • 檔案系統(根目錄)訪問 - 客戶端向伺服器公開檔案系統 roots 的標準方式。Roots 定義了伺服器在檔案系統中操作的邊界,允許它們瞭解自己有權訪問哪些目錄和檔案。伺服器可以從支援的客戶端請求 roots 列表,並在列表更改時接收通知。

  • 事件處理器 - 當發生特定伺服器事件時通知客戶端的處理器

    • 工具更改通知 - 當可用伺服器工具列表更改時

    • 資源更改通知 - 當可用伺服器資源列表更改時。

    • Prompts 更改通知 - 當可用伺服器 prompts 列表更改時。

  • 日誌處理器 - 伺服器向客戶端傳送結構化日誌訊息的標準方式。客戶端可以透過設定最低日誌級別來控制日誌詳細程度

根據您的應用需求,您可以為同步客戶端實現 McpSyncClientCustomizer,或為非同步客戶端實現 McpAsyncClientCustomizer

  • 同步

  • 非同步

@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 客戶端自動配置會自動檢測並應用在應用上下文中找到的任何定製器。

傳輸支援

自動配置支援多種傳輸型別

  • 標準 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 整合

啟動器可以配置與 Spring AI 工具執行框架整合的工具回撥,允許將 MCP 工具用作 AI 互動的一部分。此整合是可選加入的 (opt-in),並且必須透過設定屬性 spring.ai.mcp.client.toolcallback.enabled=true 來顯式啟用。

使用示例

將適當的啟動器依賴新增到您的專案中,並在 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: https://: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();

請注意,工具回撥功能預設是停用的,必須透過以下方式顯式啟用

spring:
  ai:
    mcp:
      client:
        toolcallback:
          enabled: true

示例應用