MCP客戶端啟動器

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

MCP 客戶端啟動器提供

  • 多個客戶端例項的管理

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

  • 支援多種命名傳輸(STDIO、Http/SSE 和 Streamable HTTP)

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

  • 用於選擇性工具包含/排除的工具過濾功能

  • 可定製的工具名稱字首生成,以避免命名衝突

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

  • 透過定製器進行可定製的客戶端建立

啟動器

標準 MCP 客戶端

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

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

WebFlux 客戶端

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

型別

客戶端型別(SYNC 或 ASYNC)。所有客戶端必須是同步或非同步;不支援混合

SYNC

root-change-notification

啟用/停用所有客戶端的根更改通知

true

toolcallback.enabled

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

true

MCP註解屬性

MCP 客戶端註解提供了一種使用 Java 註解實現 MCP 客戶端處理程式的宣告性方式。客戶端 mcp-annotations 屬性以 spring.ai.mcp.client.annotation-scanner 為字首

財產 描述 預設值

enabled

啟用/停用 MCP 客戶端註解自動掃描

true

Stdio 傳輸屬性

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

財產 描述 預設值

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"

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

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

Claude 桌面格式如下所示

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

Windows STDIO 配置

在 Windows 上,npxnpmnode 等命令是作為批處理檔案 (.cmd) 實現的,而不是原生可執行檔案。Java 的 ProcessBuilder 無法直接執行批處理檔案,需要 cmd.exe /c 包裝器。

為什麼 Windows 需要特殊處理

當 Java 的 ProcessBuilder(由 StdioClientTransport 內部使用)嘗試在 Windows 上生成程序時,它只能執行

  • 原生可執行檔案 (.exe 檔案)

  • cmd.exe 可用的系統命令

npx.cmdnpm.cmd 甚至 python.cmd(來自 Microsoft Store)等 Windows 批處理檔案需要 cmd.exe shell 來執行它們。

解決方案:cmd.exe 包裝器

使用 cmd.exe /c 包裝批處理檔案命令

Windows 配置

{
  "mcpServers": {
    "filesystem": {
      "command": "cmd.exe",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "C:\\Users\\username\\Desktop"
      ]
    }
  }
}

Linux/macOS 配置

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

跨平臺程式設計配置

對於需要跨平臺工作而無需單獨配置檔案的應用程式,請在 Spring Boot 應用程式中使用作業系統檢測

@Bean(destroyMethod = "close")
@ConditionalOnMissingBean(McpSyncClient.class)
public McpSyncClient mcpClient() {
    ServerParameters stdioParams;

    if (isWindows()) {
        // Windows: cmd.exe /c npx approach
        var winArgs = new ArrayList<>(Arrays.asList(
            "/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "target"));
        stdioParams = ServerParameters.builder("cmd.exe")
                .args(winArgs)
                .build();
    } else {
        // Linux/Mac: direct npx approach
        stdioParams = ServerParameters.builder("npx")
                .args("-y", "@modelcontextprotocol/server-filesystem", "target")
                .build();
    }

    return McpClient.sync(new StdioClientTransport(stdioParams, McpJsonMapper.createDefault()))
            .requestTimeout(Duration.ofSeconds(10))
            .build()
            .initialize();
}

private static boolean isWindows() {
    return System.getProperty("os.name").toLowerCase().contains("win");
}
使用 @Bean 進行程式設計配置時,新增 @ConditionalOnMissingBean(McpSyncClient.class) 以避免與 JSON 檔案中的自動配置衝突。

路徑注意事項

相對路徑(建議用於可移植性)

{
  "command": "cmd.exe",
  "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "target"]
}

MCP 伺服器根據應用程式的工作目錄解析相對路徑。

絕對路徑(Windows 需要反斜槓或轉義的正斜槓)

{
  "command": "cmd.exe",
  "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "C:\\Users\\username\\project\\target"]
}

需要 cmd.exe 的常見 Windows 批處理檔案

  • npx.cmd, npm.cmd - Node 包管理器

  • python.cmd - Python(Microsoft Store 安裝)

  • pip.cmd - Python 包管理器

  • mvn.cmd - Maven 包裝器

  • gradle.cmd - Gradle 包裝器

  • 自定義 .cmd.bat 指令碼

參考實現

請參閱 Spring AI 示例 - 檔案系統,瞭解一個完整的跨平臺 MCP 客戶端實現,它會自動檢測作業系統並相應地配置客戶端。

可流式 HTTP 傳輸屬性

用於連線到可流式 HTTP 和無狀態可流式 HTTP MCP 伺服器。

可流式 HTTP 傳輸的屬性以 spring.ai.mcp.client.streamable-http 為字首

財產 描述 預設值

connections

命名可流式 HTTP 連線配置的對映

-

connections.[name].url

與 MCP 伺服器進行可流式 HTTP 通訊的基 URL 端點

-

connections.[name].endpoint

用於連線的可流式 HTTP 端點(作為 URL 字尾)

/mcp

配置示例

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

SSE 傳輸屬性

伺服器傳送事件 (SSE) 傳輸的屬性以 spring.ai.mcp.client.sse 為字首

財產 描述 預設值

connections

命名 SSE 連線配置的對映

-

connections.[name].url

與 MCP 伺服器進行 SSE 通訊的基 URL 端點

-

connections.[name].sse-endpoint

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

/sse

示例配置

spring:
  ai:
    mcp:
      client:
        sse:
          connections:
            # Simple configuration using default /sse endpoint
            server1:
              url: https://:8080
            # Custom SSE endpoint
            server2:
              url: http://otherserver:8081
              sse-endpoint: /custom-sse
            # Complex URL with path and token (like MCP Hub)
            mcp-hub:
              url: https://:3000
              sse-endpoint: /mcp-hub/sse/cf9ec4527e3c4a2cbb149a85ea45ab01
            # SSE endpoint with query parameters
            api-server:
              url: https://api.example.com
              sse-endpoint: /v1/mcp/events?token=abc123&format=json

URL 分割指南

當您有一個完整的 SSE URL 時,將其拆分為基本 URL 和端點路徑

完整 URL 配置

https://:3000/mcp-hub/sse/token123

url: localhost:3000
sse-endpoint: /mcp-hub/sse/token123

https://api.service.com/v2/events?key=secret

url: api.service.com
sse-endpoint: /v2/events?key=secret

https://:8080/sse

url: localhost:8080
sse-endpoint: /sse(或省略使用預設值)

SSE 連線故障排除

404 未找到錯誤

  • 驗證 URL 分割:確保基 url 僅包含方案、主機和埠

  • 檢查 sse-endpoint 是否以 / 開頭,幷包含完整路徑和查詢引數

  • 直接在瀏覽器或 curl 中測試完整 URL,確認其可訪問

可流式 HTTP 傳輸屬性

可流式 HTTP 傳輸的屬性以 spring.ai.mcp.client.streamable-http 為字首

財產 描述 預設值

connections

命名可流式 HTTP 連線配置的對映

-

connections.[name].url

與 MCP 伺服器進行可流式 HTTP 通訊的基 URL 端點

-

connections.[name].endpoint

用於連線的可流式 HTTP 端點(作為 URL 字尾)

/mcp

配置示例

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

功能

同步/非同步客戶端型別

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

  • 同步 - 預設客戶端型別(spring.ai.mcp.client.type=SYNC),適用於具有阻塞操作的傳統請求-響應模式

注意: SYNC 客戶端將只註冊同步 MCP 註解方法。非同步方法將被忽略。

  • 非同步 - 適用於具有非阻塞操作的反應式應用程式,使用 spring.ai.mcp.client.type=ASYNC 進行配置

注意: ASYNC 客戶端將只註冊非同步 MCP 註解方法。同步方法將被忽略。

客戶端定製

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

定製型別

以下定製選項可用

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

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

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

  • 啟發式處理程式 - 伺服器在互動過程中透過客戶端向用戶請求額外資訊的標準化方式。

  • 事件處理程式 - 客戶端的處理程式,用於在發生特定伺服器事件時收到通知

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

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

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

    • 日誌處理程式 - 伺服器向客戶端傳送結構化日誌訊息的標準化方式。

    • 進度處理程式 - 伺服器向客戶端傳送結構化進度訊息的標準化方式。

客戶端可以透過設定最小日誌級別來控制日誌詳細程度

客戶端定製示例

您可以根據應用程式的需求,為同步客戶端實現 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;
        });

        // Sets a custom elicitation handler for processing elicitation requests.
        spec.elicitation((ElicitRequest request) -> {
          // handle elicitation
          return new ElicitResult(ElicitResult.Action.ACCEPT, Map.of("message", request.message()));
        });

        // Adds a consumer to be notified when progress notifications are received.
        spec.progressConsumer((ProgressNotification progress) -> {
         // Handle progress notifications
        });

        // 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-clientspring-ai-starter-mcp-client-webflux 啟用)

  • (HttpClient) HTTP/SSE 和可流式 HTTP(由 spring-ai-starter-mcp-client 啟用)

  • (WebFlux) HTTP/SSE 和可流式 HTTP(由 spring-ai-starter-mcp-client-webflux 啟用)

工具過濾

MCP 客戶端啟動器透過 McpToolFilter 介面支援對發現的工具進行過濾。這允許您根據 MCP 連線資訊或工具屬性等自定義條件選擇性地包含或排除工具。

要實現工具過濾,請建立一個實現 McpToolFilter 介面的 bean

@Component
public class CustomMcpToolFilter implements McpToolFilter {

    @Override
    public boolean test(McpConnectionInfo connectionInfo, McpSchema.Tool tool) {
        // Filter logic based on connection information and tool properties
        // Return true to include the tool, false to exclude it

        // Example: Exclude tools from a specific client
        if (connectionInfo.clientInfo().name().equals("restricted-client")) {
            return false;
        }

        // Example: Only include tools with specific names
        if (tool.name().startsWith("allowed_")) {
            return true;
        }

        // Example: Filter based on tool description or other properties
        if (tool.description() != null &&
            tool.description().contains("experimental")) {
            return false;
        }

        return true; // Include all other tools by default
    }
}

McpConnectionInfo 記錄提供對以下內容的訪問

  • clientCapabilities - MCP 客戶端的功能

  • clientInfo - 有關 MCP 客戶端的資訊(名稱和版本)

  • initializeResult - MCP 伺服器的初始化結果

過濾器會自動檢測並應用於同步和非同步 MCP 工具回撥提供程式。如果未提供自定義過濾器,則預設情況下包含所有發現的工具。

注意:應用程式上下文中只能定義一個 McpToolFilter bean。如果需要多個過濾器,請將它們組合成一個複合過濾器實現。

工具名稱字首生成

MCP 客戶端啟動器透過 McpToolNamePrefixGenerator 介面支援可定製的工具名稱字首生成。此功能透過為工具名稱新增唯一字首來幫助避免整合來自多個 MCP 伺服器的工具時的命名衝突。

預設情況下,如果未提供自定義 McpToolNamePrefixGenerator bean,啟動器將使用 DefaultMcpToolNamePrefixGenerator,它可確保所有 MCP 客戶端連線的工具名稱唯一。預設生成器

  • 跟蹤所有現有連線和工具名稱以確保唯一性

  • 透過將非字母數字字元替換為下劃線來格式化工具名稱(例如,my-tool 變為 my_tool

  • 當在不同連線中檢測到重複的工具名稱時,新增計數器字首(例如,alt_1_toolName, alt_2_toolName

  • 是執行緒安全的並保持冪等性 - 相同的(客戶端、伺服器、工具)組合總是獲得相同的唯一名稱

  • 確保最終名稱不超過 64 個字元(如有必要,從開頭截斷)

例如:* 工具 search 的首次出現 → search * 來自不同連線的工具 search 的第二次出現 → alt_1_search * 帶有特殊字元的工具 my-special-toolmy_special_tool

您可以透過提供自己的實現來定製此行為

@Component
public class CustomToolNamePrefixGenerator implements McpToolNamePrefixGenerator {

    @Override
    public String prefixedToolName(McpConnectionInfo connectionInfo, Tool tool) {
        // Custom logic to generate prefixed tool names

        // Example: Use server name and version as prefix
        String serverName = connectionInfo.initializeResult().serverInfo().name();
        String serverVersion = connectionInfo.initializeResult().serverInfo().version();
        return serverName + "_v" + serverVersion.replace(".", "_") + "_" + tool.name();
    }
}

McpConnectionInfo 記錄提供了有關 MCP 連線的全面資訊

  • clientCapabilities - MCP 客戶端的功能

  • clientInfo - 有關 MCP 客戶端的資訊(名稱、標題和版本)

  • initializeResult - MCP 伺服器的初始化結果,包括伺服器資訊

內建字首生成器

該框架提供了幾個內建字首生成器

  • DefaultMcpToolNamePrefixGenerator - 透過跟蹤重複項並在需要時新增計數器字首來確保唯一的工具名稱(如果未提供自定義 bean,則預設使用)

  • McpToolNamePrefixGenerator.noPrefix() - 返回不帶任何字首的工具名稱(如果多個伺服器提供同名工具,可能會導致衝突)

要完全停用字首並使用原始工具名稱(不建議在多個 MCP 伺服器中使用),請將無字首生成器註冊為 bean

@Configuration
public class McpConfiguration {

    @Bean
    public McpToolNamePrefixGenerator mcpToolNamePrefixGenerator() {
        return McpToolNamePrefixGenerator.noPrefix();
    }
}

字首生成器透過 Spring 的 ObjectProvider 機制自動檢測並應用於同步和非同步 MCP 工具回撥提供程式。如果未提供自定義生成器 bean,則自動使用 DefaultMcpToolNamePrefixGenerator

當使用 McpToolNamePrefixGenerator.noPrefix() 和多個 MCP 伺服器時,重複的工具名稱將導致 IllegalStateException。預設的 DefaultMcpToolNamePrefixGenerator 透過自動為重複工具名稱新增唯一字首來防止這種情況。

工具上下文到 MCP 元轉換器

MCP 客戶端啟動器支援將 Spring AI 的 ToolContext 可定製地轉換為 MCP 工具呼叫元資料,透過 ToolContextToMcpMetaConverter 介面。此功能允許您將附加上下文資訊(例如使用者 ID、金鑰令牌)作為元資料與 LLM 生成的呼叫引數一起傳遞。

例如,您可以在工具上下文中將 MCP progressToken 傳遞給 MCP 進度流,以跟蹤長時間執行操作的進度

ChatModel chatModel = ...

String response = ChatClient.create(chatModel)
        .prompt("Tell me more about the customer with ID 42")
        .toolContext(Map.of("progressToken", "my-progress-token"))
        .call()
        .content();

預設情況下,如果未提供自定義轉換器 bean,啟動器將使用 ToolContextToMcpMetaConverter.defaultConverter(),它

  • 過濾掉 MCP 交換金鑰(McpToolUtils.TOOL_CONTEXT_MCP_EXCHANGE_KEY

  • 過濾掉空值的條目

  • 將所有其他上下文條目作為元資料傳遞

您可以透過提供自己的實現來定製此行為

@Component
public class CustomToolContextToMcpMetaConverter implements ToolContextToMcpMetaConverter {

    @Override
    public Map<String, Object> convert(ToolContext toolContext) {
        if (toolContext == null || toolContext.getContext() == null) {
            return Map.of();
        }

        // Custom logic to convert tool context to MCP metadata
        Map<String, Object> metadata = new HashMap<>();

        // Example: Add custom prefix to all keys
        for (Map.Entry<String, Object> entry : toolContext.getContext().entrySet()) {
            if (entry.getValue() != null) {
                metadata.put("app_" + entry.getKey(), entry.getValue());
            }
        }

        // Example: Add additional metadata
        metadata.put("timestamp", System.currentTimeMillis());
        metadata.put("source", "spring-ai");

        return metadata;
    }
}

內建轉換器

該框架提供了內建轉換器

  • ToolContextToMcpMetaConverter.defaultConverter() - 過濾掉 MCP 交換金鑰和空值(如果未提供自定義 bean,則預設使用)

  • ToolContextToMcpMetaConverter.noOp() - 返回一個空對映,有效地停用上下文到元資料的轉換

要完全停用上下文到元資料的轉換

@Configuration
public class McpConfiguration {

    @Bean
    public ToolContextToMcpMetaConverter toolContextToMcpMetaConverter() {
        return ToolContextToMcpMetaConverter.noOp();
    }
}

轉換器透過 Spring 的 ObjectProvider 機制自動檢測並應用於同步和非同步 MCP 工具回撥。如果未提供自定義轉換器 bean,則自動使用預設轉換器。

停用 MCP ToolCallback 自動配置

MCP ToolCallback 自動配置預設啟用,但可以使用 spring.ai.mcp.client.toolcallback.enabled=false 屬性停用。

停用時,不會從可用的 MCP 工具建立 ToolCallbackProvider bean。

MCP 客戶端註解

MCP 客戶端啟動器會自動檢測並註冊註解方法,用於處理各種 MCP 客戶端操作

  • @McpLogging - 處理來自 MCP 伺服器的日誌訊息通知

  • @McpSampling - 處理來自 MCP 伺服器的 LLM 完成取樣請求

  • @McpElicitation - 處理啟發式請求以從使用者那裡收集附加資訊

  • @McpProgress - 處理長時間執行操作的進度通知

  • @McpToolListChanged - 處理伺服器工具列表更改時的通知

  • @McpResourceListChanged - 處理伺服器資源列表更改時的通知

  • @McpPromptListChanged - 處理伺服器提示列表更改時的通知

示例用法

@Component
public class McpClientHandlers {

    @McpLogging(clients = "server1")
    public void handleLoggingMessage(LoggingMessageNotification notification) {
        System.out.println("Received log: " + notification.level() +
                          " - " + notification.data());
    }

    @McpSampling(clients = "server1")
    public CreateMessageResult handleSamplingRequest(CreateMessageRequest request) {
        // Process the request and generate a response
        String response = generateLLMResponse(request);

        return CreateMessageResult.builder()
            .role(Role.ASSISTANT)
            .content(new TextContent(response))
            .model("gpt-4")
            .build();
    }

    @McpProgress(clients = "server1")
    public void handleProgressNotification(ProgressNotification notification) {
        double percentage = notification.progress() * 100;
        System.out.println(String.format("Progress: %.2f%% - %s",
            percentage, notification.message()));
    }

    @McpToolListChanged(clients = "server1")
    public void handleToolListChanged(List<McpSchema.Tool> updatedTools) {
        System.out.println("Tool list updated: " + updatedTools.size() + " tools available");
        // Update local tool registry
        toolRegistry.updateTools(updatedTools);
    }
}

這些註解支援同步和非同步實現,並且可以使用 clients 引數為特定客戶端配置

@McpLogging(clients = "server1")
public void handleServer1Logs(LoggingMessageNotification notification) {
    // Handle logs from specific server
    logToFile("server1.log", notification);
}

@McpSampling(clients = "server1")
public Mono<CreateMessageResult> handleAsyncSampling(CreateMessageRequest request) {
    return Mono.fromCallable(() -> {
        String response = generateLLMResponse(request);
        return CreateMessageResult.builder()
            .role(Role.ASSISTANT)
            .content(new TextContent(response))
            .model("gpt-4")
            .build();
    }).subscribeOn(Schedulers.boundedElastic());
}

有關所有可用註解及其用法模式的詳細資訊,請參閱 MCP 客戶端註解 文件。

使用示例

將適當的啟動器依賴項新增到您的專案並在 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
        streamable-http:
          connections:
            server3:
              url: https://:8083
              endpoint: /mcp
        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();

示例應用程式

© . This site is unofficial and not affiliated with VMware.