了解如何使用 Model Context Protocol (MCP) 客户端与 MCP 服务器进行交互
io.modelcontextprotocol.sdk:mcp
io.modelcontextprotocol.sdk:mcp-spring-webflux
// 使用自定义配置创建同步客户端 McpSyncClient client = McpClient.sync(transport) .requestTimeout(Duration.ofSeconds(10)) .capabilities(ClientCapabilities.builder() .roots(true) // 启用根目录功能 .sampling() // 启用采样功能 .build()) .sampling(request -> new CreateMessageResult(response)) .build(); // 初始化连接 client.initialize(); // 列出可用工具 ListToolsResult tools = client.listTools(); // 调用工具 CallToolResult result = client.callTool( new CallToolRequest("calculator", Map.of("operation", "add", "a", 2, "b", 3)) ); // 列出和读取资源 ListResourcesResult resources = client.listResources(); ReadResourceResult resource = client.readResource( new ReadResourceRequest("resource://uri") ); // 列出和使用提示 ListPromptsResult prompts = client.listPrompts(); GetPromptResult prompt = client.getPrompt( new GetPromptRequest("greeting", Map.of("name", "Spring")) ); // 添加/删除根目录 client.addRoot(new Root("file:///path", "description")); client.removeRoot("file:///path"); // 关闭客户端 client.closeGracefully();
ServerParameters params = ServerParameters.builder("npx") .args("-y", "@modelcontextprotocol/server-everything", "dir") .build(); McpTransport transport = new StdioClientTransport(params);
var capabilities = ClientCapabilities.builder() .roots(true) // 启用文件系统根目录支持,并提供列表变更通知 .sampling() // 启用 LLM 采样支持 .build();
// 动态添加根目录 client.addRoot(new Root("file:///path", "description")); // 删除根目录 client.removeRoot("file:///path"); // 通知服务器根目录列表已更改 client.rootsListChangedNotification();
// 配置采样处理程序 Function<CreateMessageRequest, CreateMessageResult> samplingHandler = request -> { // 与 LLM 接口的采样实现 return new CreateMessageResult(response); }; // 创建支持采样的客户端 var client = McpClient.sync(transport) .capabilities(ClientCapabilities.builder() .sampling() .build()) .sampling(samplingHandler) .build();
// 列出可用工具及其名称 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 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 prompts = client.listPrompts(); prompts.forEach(prompt -> System.out.println(prompt.getName())); // 使用参数执行提示模板 var response = client.executePrompt("echo", Map.of( "text", "Hello, World!" ));
Was this page helpful?