简体中文
学习如何使用模型上下文协议(MCP协议)客户端与MCP服务器进行交互
// 使用自定义配置创建同步客户端 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!" ));