简体中文
学习如何使用 Model Context Protocol (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();
// 列出可用资源及其名称 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", "你好,世界!" ));