Java
MCP Client
Java
MCP Client
了解如何使用模型上下文协议(MCP)客户端与MCP服务器交互
模型上下文协议客户端
MCP客户端是模型上下文协议(MCP)架构中的一个关键组件,负责建立和管理与MCP服务器的连接。它实现了协议的客户端部分,处理以下内容:
- 协议版本协商以确保与服务器的兼容性
- 能力协商以确定可用功能
- 消息传输和JSON-RPC通信
- 工具发现和执行
- 资源访问和管理
- 提示系统交互
- 可选功能,如根目录管理和采样支持
Spring-AI MCP Client 集成扩展了MCP Java SDK,为Spring Boot应用程序提供MCP客户端功能的自动配置,并与Spring AI的工具执行框架集成。
客户端同时提供同步和异步API,以适应不同的应用场景。
// Create a sync client with custom configuration
McpSyncClient client = McpClient.sync(transport)
.requestTimeout(Duration.ofSeconds(10))
.capabilities(ClientCapabilities.builder()
.roots(true) // Enable roots capability
.sampling() // Enable sampling capability
.build())
.sampling(request -> new CreateMessageResult(response))
.build();
// Initialize connection
client.initialize();
// List available tools
ListToolsResult tools = client.listTools();
// Call a tool
CallToolResult result = client.callTool(
new CallToolRequest("calculator",
Map.of("operation", "add", "a", 2, "b", 3))
);
// List and read resources
ListResourcesResult resources = client.listResources();
ReadResourceResult resource = client.readResource(
new ReadResourceRequest("resource://uri")
);
// List and use prompts
ListPromptsResult prompts = client.listPrompts();
GetPromptResult prompt = client.getPrompt(
new GetPromptRequest("greeting", Map.of("name", "Spring"))
);
// Add/remove roots
client.addRoot(new Root("file:///path", "description"));
client.removeRoot("file:///path");
// Close client
client.closeGracefully();
// Create a sync client with custom configuration
McpSyncClient client = McpClient.sync(transport)
.requestTimeout(Duration.ofSeconds(10))
.capabilities(ClientCapabilities.builder()
.roots(true) // Enable roots capability
.sampling() // Enable sampling capability
.build())
.sampling(request -> new CreateMessageResult(response))
.build();
// Initialize connection
client.initialize();
// List available tools
ListToolsResult tools = client.listTools();
// Call a tool
CallToolResult result = client.callTool(
new CallToolRequest("calculator",
Map.of("operation", "add", "a", 2, "b", 3))
);
// List and read resources
ListResourcesResult resources = client.listResources();
ReadResourceResult resource = client.readResource(
new ReadResourceRequest("resource://uri")
);
// List and use prompts
ListPromptsResult prompts = client.listPrompts();
GetPromptResult prompt = client.getPrompt(
new GetPromptRequest("greeting", Map.of("name", "Spring"))
);
// Add/remove roots
client.addRoot(new Root("file:///path", "description"));
client.removeRoot("file:///path");
// Close client
client.closeGracefully();
// Create an async client with custom configuration
McpAsyncClient client = McpClient.async(transport)
.requestTimeout(Duration.ofSeconds(10))
.capabilities(ClientCapabilities.builder()
.roots(true) // Enable roots capability
.sampling() // Enable sampling capability
.build())
.sampling(request -> Mono.just(new CreateMessageResult(response)))
.toolsChangeConsumer(tools -> Mono.fromRunnable(() -> {
logger.info("Tools updated: {}", tools);
}))
.resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> {
logger.info("Resources updated: {}", resources);
}))
.promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> {
logger.info("Prompts updated: {}", prompts);
}))
.build();
// Initialize connection and use features
client.initialize()
.flatMap(initResult -> client.listTools())
.flatMap(tools -> {
return client.callTool(new CallToolRequest(
"calculator",
Map.of("operation", "add", "a", 2, "b", 3)
));
})
.flatMap(result -> {
return client.listResources()
.flatMap(resources ->
client.readResource(new ReadResourceRequest("resource://uri"))
);
})
.flatMap(resource -> {
return client.listPrompts()
.flatMap(prompts ->
client.getPrompt(new GetPromptRequest(
"greeting",
Map.of("name", "Spring")
))
);
})
.flatMap(prompt -> {
return client.addRoot(new Root("file:///path", "description"))
.then(client.removeRoot("file:///path"));
})
.doFinally(signalType -> {
client.closeGracefully().subscribe();
})
.subscribe();
客户端传输
传输层处理MCP客户端和服务器之间的通信,为各种用例提供不同的实现。客户端传输管理消息序列化、连接建立和协议特定的通信模式。
为进程内通信创建传输
ServerParameters params = ServerParameters.builder("npx")
.args("-y", "@modelcontextprotocol/server-everything", "dir")
.build();
McpTransport transport = new StdioClientTransport(params);
为进程内通信创建传输
ServerParameters params = ServerParameters.builder("npx")
.args("-y", "@modelcontextprotocol/server-everything", "dir")
.build();
McpTransport transport = new StdioClientTransport(params);
创建框架无关(纯Java API)的SSE客户端传输。包含在核心mcp模块中。
McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server");
创建基于WebFlux的SSE客户端传输。需要mcp-webflux-sse-transport依赖。
WebClient.Builder webClientBuilder = WebClient.builder()
.baseUrl("http://your-mcp-server");
McpTransport transport = new WebFluxSseClientTransport(webClientBuilder);
客户端能力
客户端可以配置各种能力:
var capabilities = ClientCapabilities.builder()
.roots(true) // 启用文件系统根目录支持,包含列表更改通知
.sampling() // 启用LLM采样支持
.build();
根目录支持
根目录定义了服务器可以在文件系统中操作的边界:
// 动态添加根目录
client.addRoot(new Root("file:///path", "description"));
// 移除根目录
client.removeRoot("file:///path");
// 通知服务器根目录变更
client.rootsListChangedNotification();
根目录能力允许服务器:
- 请求可访问的文件系统根目录列表
- 接收根目录列表更改的通知
- 了解它们可以访问哪些目录和文件
采样支持
采样使服务器能够通过客户端请求LLM交互(“完成”或”生成”):
// 配置采样处理器
Function<CreateMessageRequest, CreateMessageResult> samplingHandler = request -> {
// 与LLM交互的采样实现
return new CreateMessageResult(response);
};
// 创建具有采样支持的客户端
var client = McpClient.sync(transport)
.capabilities(ClientCapabilities.builder()
.sampling()
.build())
.sampling(samplingHandler)
.build();
此能力允许:
- 服务器利用AI功能而无需API密钥
- 客户端维护对模型访问和权限的控制
- 支持文本和基于图像的交互
- 可选在提示中包含MCP服务器上下文
使用MCP客户端
工具执行
工具是客户端可以发现和执行的服务器端函数。MCP客户端提供方法来列出可用工具并使用特定参数执行它们。每个工具都有一个唯一的名称并接受参数映射。
// 列出可用工具及其名称
var tools = client.listTools();
tools.forEach(tool -> System.out.println(tool.getName()));
// 使用参数执行工具
var result = client.callTool("calculator", Map.of(
"operation", "add",
"a", 1,
"b", 2
));
// 列出可用工具及其名称
var tools = client.listTools();
tools.forEach(tool -> System.out.println(tool.getName()));
// 使用参数执行工具
var result = client.callTool("calculator", Map.of(
"operation", "add",
"a", 1,
"b", 2
));
// 异步列出可用工具
client.listTools()
.doOnNext(tools -> tools.forEach(tool ->
System.out.println(tool.getName())))
.subscribe();
// 异步执行工具
client.callTool("calculator", Map.of(
"operation", "add",
"a", 1,
"b", 2
))
.subscribe();
资源访问
资源代表客户端可以使用URI模板访问的服务器端数据源。MCP客户端提供方法来发现可用资源并通过标准化接口检索其内容。
// 列出可用资源及其名称
var resources = client.listResources();
resources.forEach(resource -> System.out.println(resource.getName()));
// 使用URI模板检索资源内容
var content = client.getResource("file", Map.of(
"path", "/path/to/file.txt"
));
// 列出可用资源及其名称
var resources = client.listResources();
resources.forEach(resource -> System.out.println(resource.getName()));
// 使用URI模板检索资源内容
var content = client.getResource("file", Map.of(
"path", "/path/to/file.txt"
));
// 异步列出可用资源
client.listResources()
.doOnNext(resources -> resources.forEach(resource ->
System.out.println(resource.getName())))
.subscribe();
// 异步检索资源内容
client.getResource("file", Map.of(
"path", "/path/to/file.txt"
))
.subscribe();
提示系统
提示系统支持与服务器端提示模板的交互。这些模板可以被发现并使用自定义参数执行,允许基于预定义模式生成动态文本。
// 列出可用提示模板
var prompts = client.listPrompts();
prompts.forEach(prompt -> System.out.println(prompt.getName()));
// 使用参数执行提示模板
var response = client.executePrompt("echo", Map.of(
"text", "Hello, World!"
));
// 列出可用提示模板
var prompts = client.listPrompts();
prompts.forEach(prompt -> System.out.println(prompt.getName()));
// 使用参数执行提示模板
var response = client.executePrompt("echo", Map.of(
"text", "Hello, World!"
));
// 异步列出可用提示模板
client.listPrompts()
.doOnNext(prompts -> prompts.forEach(prompt ->
System.out.println(prompt.getName())))
.subscribe();
// 异步执行提示模板
client.executePrompt("echo", Map.of(
"text", "Hello, World!"
))
.subscribe();