Spring Ai [1.1.2]版本 初始化MCP- client

37 阅读1分钟
  • 支持阿里百炼MCP [自定义header], 魔搭社区 等

1. 对接Streamable HTTP

McpSyncClient mcpSyncClient = null;
try {
    HttpClientStreamableHttpTransport transport = HttpClientStreamableHttpTransport
            .builder(url)
            .endpoint(endpoint)
            .customizeRequest(builder -> {
                // 使用 customizeRequest 方法添加自定义 headers
                if (headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        builder.header(entry.getKey(), entry.getValue());
                    }
                }
            })
            .build();
    mcpSyncClient = McpClient.sync(transport)
            .initializationTimeout(Duration.ofSeconds(10))
            .requestTimeout(Duration.ofSeconds(60)).build();

    mcpSyncClient.initialize();
} catch (Exception e) {
    log.error("初始化-StreamableHTTP-MCP链接出现异常, 工具/mcp名称:【{}】, URL:【{}】,endpoint:【{}】, Exception: {}", pluginName, url, endpoint, ExceptionUtils.getStackTrace(e));
    if (mcpSyncClient != null) {
        mcpSyncClient.close();
    }
    return null;
}
log.info("初始化-StreamableHTTP-MCP 链接成功, 工具/mcp名称:【{}】, URL:【{}】,endpoint:【{}】", pluginName, url, endpoint);
return mcpSyncClient;

2. 对接SSE

McpSyncClient mcpSyncClient = null;
try {
    HttpClientSseClientTransport transport = HttpClientSseClientTransport
            .builder(url)
            .sseEndpoint(endpoint)
            .customizeRequest(builder -> {
                if (headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        builder.header(entry.getKey(), entry.getValue());
                    }
                }
            })
            .build();
    mcpSyncClient = McpClient.sync(transport)
            .initializationTimeout(Duration.ofSeconds(10))
            .requestTimeout(Duration.ofSeconds(60)).build();
    mcpSyncClient.initialize();
} catch (Exception e) {
    log.error("初始化MCP链接出现异常, 工具/mcp名称:【{}】, URL:【{}】,sseEndpoint:【{}】, Exception: {}", pluginName, url, endpoint, ExceptionUtils.getStackTrace(e));
    if (mcpSyncClient != null) {
        mcpSyncClient.close();
    }
    return null;
}
log.info("初始化MCP链接成功, 工具/mcp名称:【{}】, URL:【{}】,sseEndpoint:【{}】", pluginName, url, endpoint);
return mcpSyncClient;