构建MCP客户端
该教程介绍如何用Python搭建一个MCP客户端,通过单个Client对象管理连接生命周期,以子进程和stdio方式启动Python或Node.js服务器,并把查询与工具调用结果回传给Claude。
在此教程中, 您将学习如何构建一个 LLM 驱动的聊天器客户端, 连接到 MCP 服务器 。 在您开始前, 它会帮助您通过我们 [构建 MCP 服务器](<https://modelcontextprotocol.io/docs/2026-07-28/develop/build-server>) 教程,这样您就可以理解客户端和服务器是如何沟通的. - Python 键 - TypeScript - 爪哇语 - 科特林语Name - C# - 鲁比 - 锈 [您可以在此找到此教程的完整代码 。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-python>) ## 系统要求 在开始前,确保您的系统满足这些要求: - macOS, Windows, 或 Linux 计算机 - 已安装最新 Python 版本 - 最新版本 `uv` 已安装 - 您必须使用 Python MCP SDK 2.0.0 或更高版本 ## 设置您的环境 首先, 创建一个新的 Python 项目 。 `uv`: ``` # Create project directory uv init mcp-client cd mcp-client # Create virtual environment uv venv # Activate virtual environment source .venv/bin/activate # Install required packages uv add mcp anthropic python-dotenv # Remove boilerplate files rm main.py # Create our main file touch client.py ``` ``` # Create project directory uv init mcp-client cd mcp-client # Create virtual environment uv venv # Activate virtual environment .venv\Scripts\activate # Install required packages uv add mcp anthropic python-dotenv # Remove boilerplate files del main.py # Create our main file new-item client.py ``` ## 设置您的 API 密钥 您需要来自本地的 Anthropic API 密钥 [自动控制台](<https://console.anthropic.com/settings/keys>)创建 a `.env` 要存储的文件 : ``` echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env ``` 添加 `.env` 给您的 `.gitignore`: ``` echo ".env" >> .gitignore ``` 一定要留着你的 `ANTHROPIC_API_KEY` 安全了! 安全了! 快点! 安全了! ## 创建客户端 ### 导入和设置 首先,让我们来安排进口品 和剩下的文件份额: ``` import asyncio import sys from mcp import Client, StdioServerParameters from mcp.client.stdio import stdio_client from mcp_types import TextContent from anthropic import Anthropic from dotenv import load_dotenv load_dotenv() # load environment variables from .env MODEL = "claude-haiku-5-5" # The model thinks adaptively unless told otherwise, and max_tokens caps thinking # plus the reply, so leave room for both. MAX_TOKENS = 10000 MAX_TOOL_TURNS = 10 anthropic = Anthropic() ``` `Client` 是您程序通过服务器向服务器表达的单个对象。 列出工具, 拨打一个, 读取一个资源: 每个工具都是其中的一种方法 。 ### 服务器连接管理 接下来,我们将为给定的服务器脚本确定一个进程: ``` def server_params(server_script_path: str) -> StdioServerParameters: """Describe the subprocess that runs an MCP server Args: server_script_path: Path to the server script (.py or .js) """ if server_script_path.endswith(".py"): command = "python" elif server_script_path.endswith(".js"): command = "node" else: raise ValueError("Server script must be a .py or .js file") return StdioServerParameters(command=command, args=[server_script_path]) ``` `StdioServerParameters` 是配置,不是连接。 `stdio_client()` 把它变成运输工具,和 `Client` 当您进入其传送时, 打开该传送 `async with` 块。我们将在 `main()`. ### 查询处理逻辑 现在让我们加入处理查询和处理工具呼叫的核心功能: ``` async def process_query(client: Client, query: str) -> str: """Process a query using Claude and available tools""" messages = [ { "role": "user", "content": query } ] tool_list = await client.list_tools() available_tools = [{ "name": tool.name, "description": tool.description, "input_schema": tool.input_schema } for tool in tool_list.tools] final_text = [] # Initial Claude API call response = anthropic.messages.create( model=MODEL, max_tokens=MAX_TOKENS, messages=messages, tools=available_tools ) for _ in range(MAX_TOOL_TURNS): # Process response and collect tool calls tool_uses = [] for content in response.content: if content.type == 'text': final_text.append(content.text) elif content.type == 'tool_use': tool_uses.append(content) if not tool_uses: return "\n".join(final_text) tool_results = [] for tool_use in tool_uses: # Execute tool call result = await client.call_tool(tool_use.name, tool_use.input) final_text.append(f"[Calling tool {tool_use.name} with args {tool_use.input}]") tool_results.append({ "type": "tool_result", "tool_use_id": tool_use.id, "content": "\n".join( block.text for block in result.content if isinstance(block, TextContent) ), "is_error": result.is_error }) # Replay the assistant turn as returned, then answer all of its # tool calls in a single user message messages.append({"role": "assistant", "content": response.content}) messages.append({"role": "user", "content": tool_results}) # Get next response from Claude response = anthropic.messages.create( model=MODEL, max_tokens=MAX_TOKENS, messages=messages, tools=available_tools ) # The turn cap was hit. Keep the last response's text. If it asked for # more tools, say they were not run. final_text.extend(content.text for content in response.content if content.type == 'text') if any(content.type == 'tool_use' for content in response.content): final_text.append(f"[Stopped after {MAX_TOOL_TURNS} tool-use turns]") return "\n".join(final_text) ``` `call_tool` 返回 a `CallToolResult`. 其内容 `content` 是一个块列表, 这就是为什么我们缩小到 `TextContent` 阅读前 `.text`。在此不提出工具:它用 `is_error` 设定,然后在旗子上传递,让克劳德阅读消息并尝试别的东西. Ever turn replay 助理消息恰好与克劳德返回时一样,包含思维块,并回答每个 `tool_use` 块中一个用户消息。信件 API 拒绝这两个不排队的对话 。 `tools` 继续每通电话,这样克劳德可以继续呼叫工具, 循环运行直到克劳德回答,没有一个或 `MAX_TOOL_TURNS` 已到达,客户报告停止。 ### 交互式聊天界面 现在,我们将添加聊天循环: ``` async def chat_loop(client: Client) -> None: """Run an interactive chat loop""" print("\nMCP Client Started!") print("Type your queries or 'quit' to exit.") while True: try: query = (await asyncio.to_thread(input, "\nQuery: ")).strip() except EOFError: break if query.lower() == 'quit': break try: response = await process_query(client, query) print("\n" + response) except Exception as e: print(f"\nError: {e}") ``` `input()` 块,所以它运行在工人线条上。这样可以让事件循环在您输入时为连接服务。 ### 主条目 最后,我们将补充主要的执行逻辑: ``` async def main() -> None: if len(sys.argv) < 2: print("Usage: uv run client.py <path_to_server_script>") sys.exit(1) async with Client(stdio_client(server_params(sys.argv[1]))) as client: tool_list = await client.list_tools() tool_names = [tool.name for tool in tool_list.tools] print("\nConnected to server with tools:", tool_names) await chat_loop(client) if __name__ == "__main__": asyncio.run(main()) ``` 那个 `async with` 是整个连接寿命周期。输入后将启动服务器,并与之商定协议版本;将它断开并关闭子进程。手动关闭没有任何东西。您可以找到完整的程序。 `client.py` 文件 [这儿](<https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-python/client.py>). ## 已解释关键部件 ### 1. 客户端初始化 - 单人 `Client` 携带连接,以及 `async with` 是整个生命周期 - 没有连接/ 接近对呼叫, 之后没有东西要清理 - 配置用于 Claude 交互的 Anthropic 客户端 ### 2. 服务器连接 - 支持 Python 和 Node.js 服务器 - 验证服务器脚本类型 - 将服务器作为子进程启动, 并对它说话 stdio - 打开连接后列出可用的工具 ### 3. 查询处理 - 为每个查询启动新对话 - 处理克劳德的回应和工具呼叫 - 运行一个转弯的每个工具调用, 然后在一条信息中全部回答 - 克劳德要求工具时继续循环,最多 `MAX_TOOL_TURNS` - 将成果纳入协调一致的对策 ### 4. 交互式接口 - 提供简单的命令行界面 - 处理用户输入并显示响应 - 包括基本错误处理 - 允许优雅的退出 ### 5. 资源管理 - 离开 `async with` 屏蔽断开并关闭服务器子进程 - 报告失败的查询而不结束会话 - 键入 `quit`,或关闭标准输入,退出干净 ## 通用自定义点 1. **工具处理** - 修改 `process_query()` 用于处理特定工具类型 - 调整 `MAX_TOOL_TURNS` 以允许每次查询多或少轮工具调用 - 为工具调用添加自定义错误处理 - 执行特定工具的响应格式 2. **反应处理** - 自定义工具结果格式化方式 - 添加响应过滤或转换 - 执行自定义记录 3. **用户界面** - 添加 GUI 或 Web 界面 - 执行丰富的控制台输出 - 添加命令历史或自动补全 ## 运行客户端 要用 MCP 服务器运行您的客户端 : ``` uv run client.py path/to/server.py # python server uv run client.py path/to/build/index.js # node server ``` 如果你继续的话 [从服务器快速启动的天气教程](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python>)你的命令可能是这样的: `uv run client.py .../quickstart-resources/weather-server-python/weather.py` 客户将: 1. 连接到指定的服务器 2. 列出可用的工具 3. 启动交互聊天会话, 您可以在此进行 : - 输入查询 - 见工具处决 - 得到克劳德的答复 以下是从服务器快速启动连接到气象服务器时,  ## 如何运作 当您提交查询时 : 1. 客户端从服务器获取可用的工具列表 2. 您的查询随工具描述一起发送给 Claude 3. Claude决定使用哪些工具(如果有的话) 4. 客户端通过服务器执行任何请求的工具调用 5. 结果被送回Claude, 步骤 3 到5 重复, 而Claude 不断要求工具, 最多 `MAX_TOOL_TURNS` 6. Claude提供了一种自然语言的反应 7. 回复显示在您身上 ## 最佳做法 1. **处理错误** - 检查 `result.is_error` 而不是期待一个失败的工具来提高 - 保持工具循环封顶, 这样一个从未解决的查询仍然返回 - 提供有意义的错误信息 - 善于处理连接问题 2. **资源管理** - 琵秨 `async with` 块拥有连接 - 只要您需要服务器,就打开它 - 处理服务器断开 3. **警卫** - 安全存储 API 密钥 `.env` - 验证服务器响应 - 工具权限要小心 4. **工具名称** - 工具名可按指定格式验证 [这儿](<https://modelcontextprotocol.io/specification/2026-07-28/server/tools#tool-names>) - 如果一个工具名称符合指定格式, 它不应失败 MCP 客户端的验证 ## 解决问题 ### 服务器路径问题 - 双向检查您的服务器脚本路径正确 - 如果相对路径无效, 则使用绝对路径 - 对于 Windows 用户, 请在路径中确保使用前鞭 (/) 或逃脱后鞭 (\) - 验证服务器文件有正确的扩展名( Python 的.py 或 Node.js 的.js) 正确路径使用示例 : ``` # Relative path uv run client.py ./server/weather.py # Absolute path uv run client.py /Users/username/projects/mcp-server/weather.py # Windows path (either format works) uv run client.py C:/projects/mcp-server/weather.py uv run client.py C:\\projects\\mcp-server\\weather.py ``` ### 反应时间 - 第一个反应可能要花到30秒才能返回 - 这是正常的,而且发生时: - 服务器初始化 - Claude 处理查询 - 正在执行工具 - 随后的反应通常更快 - 在最初的等待期不要打断这一过程 ### 常见错误消息 若见: - `FileNotFoundError`:确保命令(`python`, `node`) 备有 - `Connection closed`: 检查您的服务器路径, 然后直接运行服务器命令, 以查看它是否开始 - `Tool execution failed`: 验证工具所需的环境变量已设定 - `Timeout error`: 考虑提高 `read_timeout_seconds` 编辑 `Client` [您可以在此找到此教程的完整代码 。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-typescript>) ## 系统要求 在开始前,确保您的系统满足这些要求: - macOS, Windows, 或 Linux 计算机 - 已安装的节点.js 20或更高 - 最新版本 `npm` 已安装 - Anthropic API 密钥 (克劳德) ## 设置您的环境 首先,让我们创造和建立我们的项目: ``` # Create project directory mkdir mcp-client-typescript cd mcp-client-typescript # Initialize npm project npm init -y # Install dependencies npm install @anthropic-ai/sdk @modelcontextprotocol/client dotenv # Install dev dependencies npm install -D @types/node typescript # Create source file touch index.ts ``` ``` # Create project directory md mcp-client-typescript cd mcp-client-typescript # Initialize npm project npm init -y # Install dependencies npm install @anthropic-ai/sdk @modelcontextprotocol/client dotenv # Install dev dependencies npm install -D @types/node typescript # Create source file new-item index.ts ``` 更新您的 `package.json` 设置 `type: "module"` 和构建脚本 : 软件包.json ``` { "type": "module", "scripts": { "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"" } } ``` 创建一个 `tsconfig.json` 在您的项目根中: tsconfig.json (英语). ``` { "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "types": ["node"], "outDir": "./build", "rootDir": "./", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["index.ts"], "exclude": ["node_modules"] } ``` ## 设置您的 API 密钥 您需要来自本地的 Anthropic API 密钥 [自动控制台](<https://console.anthropic.com/settings/keys>)创建 a `.env` 要存储的文件 : ``` echo "ANTHROPIC_API_KEY=<your key here>" > .env ``` 添加 `.env` 给您的 `.gitignore`: ``` echo ".env" >> .gitignore ``` 一定要留着你的 `ANTHROPIC_API_KEY` 安全了! 安全了! 快点! 安全了! ## 创建客户端 ### 基本客户结构 首先,让我们建立我们的进口 和创建基本的客户类 `index.ts`: ``` import { Anthropic } from "@anthropic-ai/sdk"; import { ContentBlockParam, MessageParam, Tool, ToolResultBlockParam, ToolUseBlock, } from "@anthropic-ai/sdk/resources/messages/messages.mjs"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import readline from "readline/promises"; import dotenv from "dotenv"; dotenv.config(); const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; if (!ANTHROPIC_API_KEY) { throw new Error("ANTHROPIC_API_KEY is not set"); } const MODEL = "claude-haiku-5-5"; // The model thinks adaptively unless told otherwise, and max_tokens caps // thinking plus the reply, so leave room for both. const MAX_TOKENS = 10000; const MAX_TOOL_TURNS = 10; class MCPClient { private mcp: Client; private anthropic: Anthropic; private transport: StdioClientTransport | null = null; private tools: Tool[] = []; constructor() { this.anthropic = new Anthropic({ apiKey: ANTHROPIC_API_KEY, }); // 'auto' probes server/discover, falling back to the 2025-11-25 handshake. // The SDK's default is 'legacy'. this.mcp = new Client( { name: "mcp-client-cli", version: "1.0.0" }, { versionNegotiation: { mode: "auto" } }, ); } // methods will go here } ``` ### 服务器连接管理 接下来, 我们将执行连接到 MCP 服务器的方法 : ``` async connectToServer(serverScriptPath: string) { try { const isJs = serverScriptPath.endsWith(".js"); const isPy = serverScriptPath.endsWith(".py"); if (!isJs && !isPy) { throw new Error("Server script must be a .js or .py file"); } const command = isPy ? process.platform === "win32" ? "python" : "python3" : process.execPath; this.transport = new StdioClientTransport({ command, args: [serverScriptPath], }); await this.mcp.connect(this.transport); const toolsResult = await this.mcp.listTools(); this.tools = toolsResult.tools.map((tool) => { return { name: tool.name, description: tool.description, input_schema: tool.inputSchema, }; }); console.log( "Connected to server with tools:", this.tools.map(({ name }) => name) ); } catch (e) { console.log("Failed to connect to MCP server: ", e); throw e; } } ``` ### 查询处理逻辑 现在让我们加入处理查询和处理工具呼叫的核心功能: ``` async processQuery(query: string) { const messages: MessageParam[] = [ { role: "user", content: query, }, ]; let response = await this.anthropic.messages.create({ model: MODEL, max_tokens: MAX_TOKENS, messages, tools: this.tools, }); const finalText: string[] = []; for (let turn = 0; turn < MAX_TOOL_TURNS; turn++) { const toolUses: ToolUseBlock[] = []; for (const block of response.content) { if (block.type === "text") { finalText.push(block.text); } else if (block.type === "tool_use") { toolUses.push(block); } } if (toolUses.length === 0) { return finalText.join("\n"); } const toolResults: ToolResultBlockParam[] = []; for (const toolUse of toolUses) { const toolArgs = toolUse.input as { [x: string]: unknown } | undefined; finalText.push( `[Calling tool ${toolUse.name} with args ${JSON.stringify(toolArgs)}]` ); const result = await this.mcp.callTool({ name: toolUse.name, arguments: toolArgs, }); toolResults.push({ type: "tool_result", tool_use_id: toolUse.id, content: result.content .filter((block) => block.type === "text") .map((block) => block.text) .join("\n"), is_error: result.isError === true, }); } messages.push({ role: "assistant", content: response.content as unknown as ContentBlockParam[], }); messages.push({ role: "user", content: toolResults }); response = await this.anthropic.messages.create({ model: MODEL, max_tokens: MAX_TOKENS, messages, tools: this.tools, }); } // The turn cap was hit. Keep the last response's text. If it asked for // more tools, say they were not run. let wantsTools = false; for (const block of response.content) { if (block.type === "text") { finalText.push(block.text); } else if (block.type === "tool_use") { wantsTools = true; } } if (wantsTools) { finalText.push(`[Stopped after ${MAX_TOOL_TURNS} tool-use turns]`); } return finalText.join("\n"); } ``` 每个转弯都收集到每个 `tool_use` 在调用服务器前, 将整个助手按返回时( 包括思维块) 调回, 然后再有一个用户信件 。 `tool_result` 区块每个呼叫。 `callTool` 返回 a `CallToolResult` 其专辑 `content` 是一个块列表,这就是为什么代码缩窄到 `text` 读取前的块 `.text`。失败的工具不会丢到这里:它用 `isError` 设定,然后以 `is_error` 让Claude读下留言,再尝试一些别的东西。 `tools`所以克劳德可以不停地呼叫工具 直到得到答案为止 `MAX_TOOL_TURNS` 轮回。 ### 交互式聊天界面 现在,我们将添加聊天循环和清理功能: ``` async chatLoop() { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); // rl.question() doesn't reject on stdin EOF on its own. Wire its close // event to an AbortSignal so EOF (Ctrl-D) and SIGINT both unblock it. const ac = new AbortController(); const onClose = () => ac.abort(); rl.on("close", onClose); const onSigint = () => rl.close(); process.once("SIGINT", onSigint); try { console.log("\nMCP Client Started!"); console.log("Type your queries or 'quit' to exit."); while (true) { let message: string; try { message = await rl.question("\nQuery: ", { signal: ac.signal }); } catch { break; } if (message.toLowerCase() === "quit") { break; } const response = await this.processQuery(message); console.log("\n" + response); } } finally { process.off("SIGINT", onSigint); rl.off("close", onClose); rl.close(); } } async cleanup() { await this.mcp.close(); } ``` 关闭 stdin( Ctrl- D) 或按下 Ctrl- C 中止待决事宜 `rl.question()` 并打破循环,所以客户端到达 `cleanup()` ,并带有状态 0 的退出,而不是以失败方式退出 `ERR_USE_AFTER_CLOSE`. ### 主条目 最后,我们将补充主要的执行逻辑: ``` async function main() { if (process.argv.length < 3) { console.log("Usage: node build/index.js <path_to_server_script>"); return; } const mcpClient = new MCPClient(); try { await mcpClient.connectToServer(process.argv[2]); await mcpClient.chatLoop(); } catch (e) { console.error("Error:", e); await mcpClient.cleanup(); process.exit(1); } finally { await mcpClient.cleanup(); process.exit(0); } } main(); ``` ## 运行客户端 要用 MCP 服务器运行您的客户端 : ``` # Build TypeScript npm run build # Run the client node build/index.js path/to/server.py # python server node build/index.js path/to/build/index.js # node server ``` 如果你继续的话 [从服务器快速启动的天气教程](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript>)你的命令可能是这样的: `node build/index.js .../quickstart-resources/weather-server-typescript/build/index.js` **客户将:** 1. 连接到指定的服务器 2. 列出可用的工具 3. 启动交互聊天会话, 您可以在此进行 : - 输入查询 - 见工具处决 - 得到克劳德的答复 ## 如何运作 当您提交查询时 : 1. 客户端从服务器获取可用的工具列表 2. 您的查询随工具描述一起发送给 Claude 3. Claude决定使用哪些工具(如果有的话) 4. 客户端通过服务器执行每个请求的工具调用 5. 助手转过身来,所有工具结果都回到克劳德身上 一次请求,再次附上工具 6. 克劳德要求更多的工具(循环允许最多 `MAX_TOOL_TURNS` )或提供自然语言反应 7. 回复显示在您身上 ## 最佳做法 1. **处理错误** - 使用 TypeScript 的类型系统来更好地检测错误 - 检查 `result.isError` 而不是期待一个失败的工具 - 提供有意义的错误信息 - 善于处理连接问题 2. **警卫** - 安全存储 API 密钥 `.env` - 验证服务器响应 - 工具权限要小心 ## 解决问题 ### 服务器路径问题 - 双向检查您的服务器脚本路径正确 - 如果相对路径无效, 则使用绝对路径 - 对于 Windows 用户, 请在路径中确保使用前鞭 (/) 或逃脱后鞭 (\) - 验证服务器文件有正确的扩展名(.js for Node.js 或.py for Python) 正确路径使用示例 : ``` # Relative path node build/index.js ./server/build/index.js # Absolute path node build/index.js /Users/username/projects/mcp-server/build/index.js # Windows path (either format works) node build/index.js C:/projects/mcp-server/build/index.js node build/index.js C:\\projects\\mcp-server\\build\\index.js ``` ### 反应时间 - 第一个反应可能要花到30秒才能返回 - 这是正常的,而且发生时: - 服务器初始化 - Claude 处理查询 - 正在执行工具 - 随后的反应通常更快 - 在最初的等待期不要打断这一过程 ### 常见错误消息 若见: - `Error: Cannot find module`: 检查您的构建文件夹并确保 TypeScript 汇编成功 - `Connection closed`: 检查您的服务器路径, 然后直接运行服务器命令, 以查看它是否开始 - `Tool execution failed`: 验证工具所需的环境变量已设定 - `ANTHROPIC_API_KEY is not set`: 检查您的 .env 文件和环境变量 - `TypeError`: 确保您在工具参数中使用正确的类型 - `BadRequestError`: 确保您有足够的学分访问 Anthropic API 此客户端使用MCP协议版本的2025 - 11 - 25, 由Java SDK的最新稳定发布所支持. 它连接了接受该版本的服务器, 但不能连接到只接受2026 - 07 - 28的服务器. See. [向后兼容性](<https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning#backward-compatibility-with-initialization-based-versions>). 这是一个基于 Spring AI MCP 自动配置和启动启动的快速启动演示。 要学习如何手动创建同步和ASync MCP 客户端, 请查看 [Java SDK 客户端](<https://java.sdk.modelcontextprotocol.io/>) 文档。 此示例说明如何构建一个交互式聊天器,将Spring AI的模型上下文协议(MCP)与 [勇敢的搜索 MCP 服务器](<https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search>). 应用程序创建了一个对话界面,由Anthropic的Claude AI模型提供动力,可以通过勇者搜索进行互联网搜索,使自然语言与实时网络数据互动成为可能. [您可以在此找到此教程的完整代码 。](<https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot>) ## 系统要求 在开始前,确保您的系统满足这些要求: - Java 17 或 更高 - 马文·3.6 + - 时间 : - Anthropic API 密钥 (克劳德) - 勇敢的搜索 API 密钥 ## 设置您的环境 1. 安装 [时间 :](<https://docs.npmjs.com/downloading-and-installing-node-js-and-npm>),其中包含 `npx`. 2. 清除仓库 : ``` git clone https://github.com/spring-projects/spring-ai-examples.git cd spring-ai-examples/model-context-protocol/web-search/brave-chatbot ``` 3. 设置您的 API 密钥 : ``` export ANTHROPIC_API_KEY='your-anthropic-api-key-here' export BRAVE_API_KEY='your-brave-api-key-here' ``` 4. 构建应用程序 : ``` ./mvnw clean install ``` 5. 使用 Maven 运行应用程序 : ``` ./mvnw spring-boot:run ``` 一定要留着你的 `ANTHROPIC_API_KEY` 财务报告和财务报告 `BRAVE_API_KEY` 钥匙安全! ## 如何运作 该应用程序通过多个组件将Spring AI与勇者搜索MCP服务器集成: ### MCP 客户端配置 1. pom.xml 中所需的依赖性 : ``` <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-mcp-client</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-anthropic</artifactId> </dependency> ``` 2. 应用程序属性( application. yml) : ``` spring: ai: mcp: client: enabled: true name: brave-search-client version: 1.0.0 type: SYNC request-timeout: 20s stdio: servers-configuration: classpath:/mcp-servers-config.json toolcallback: enabled: true anthropic: api-key: ${ANTHROPIC_API_KEY} ``` 这激活了 `spring-ai-starter-mcp-client` 创建一个或多个 `McpClient`s 是基于提供的服务器配置。 `spring.ai.mcp.client.toolcallback.enabled=true` 属性允许工具调用机制,即自动将所有 MCP 工具登记为弹簧 AI 工具。它默认是启用的。 3. MCP 服务器配置( X)`mcp-servers-config.json`): ``` { "mcpServers": { "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search@0.6.2"], "env": { "BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>" } } } } ``` ### 聊天执行 聊天台使用 Spring AI 的 ChatClient 使用 MCP 工具集成执行: ``` var chatClient = chatClientBuilder .defaultSystem("You are useful assistant, expert in AI and Java.") .defaultTools(SyncMcpToolCallbackProvider.builder().mcpClients(mcpSyncClients).build()) .defaultAdvisors(MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build()) .build(); ``` 主要特点: - 使用 Claude AI 模型来理解自然语言 - 通过 MCP 整合勇者搜索实时网络搜索能力 - 使用 MessageWindowChatMemory 维护对话内存 - 作为交互式命令行应用程序运行 ### 构建和运行 ``` ./mvnw clean install java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar ``` 或 时 间 ``` ./mvnw spring-boot:run ``` 应用程序将启动一个交互式聊天会话, 您可以在此提问。 聊天组在需要从互联网上查找信息时会使用“ 勇敢搜索” 来回答您的询问。 聊天组可以: - 利用其内在知识回答问题 - 需要时使用勇者搜索进行网页搜索 - 记住对话中以往信件的背景 - 综合多种来源的信息,以提供全面的答案 ### 高级配置 MCP客户端支持额外的配置选项: - 通过客户定制 `McpClientCustomizer<McpClient.SyncSpec>` 或 时 间 `McpClientCustomizer<McpClient.AsyncSpec>` 豆类 - 具有多种运输类型的多个客户端 : `STDIO` 和可流化的 HTTP - 与 Spring AI 的工具执行框架集成 - 客户端自动初始化和生命周期管理 要连接到一个远程的 MCP 服务器 超流的 HTTP, 配置连接 URL : ``` spring.ai.mcp.client.streamable-http.connections.server1.url=http://localhost:8080 ``` 对于基于WebFlux的应用程序,您可以使用WebFlux启动器代替: ``` <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-mcp-client-webflux</artifactId> </dependency> ``` 这提供了类似的功能,但采用了基于WebFlux的Streamable HTTP运输执行,推荐用于生产部署. 此客户端使用MCP协议版本2025 - 11 - 25, 由Kotlin SDK的最新稳定发布支持. 它连接到接受该版本的服务器,但不连接到只接受2026 - 07 - 28的服务器. See. [向后兼容性](<https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning#backward-compatibility-with-initialization-based-versions>). [您可以在此找到此教程的完整代码 。](<https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-client>) ## 系统要求 在开始前,确保您的系统满足这些要求: - JDK 17 或 以上 (中文(简体) ). - Anthropic API 密钥 (克劳德) ## 创造你的环境 首先,让我们安装 `java` 财务报告和财务报告 `gradle` 如果您尚未下载。 您可以下载 `java` 从 [官方甲骨文JDK网站](<https://www.oracle.com/java/technologies/downloads/>)校验您的 `java` 安装 : ``` java --version ``` 现在,让我们创建和设定您的项目: ``` # Create a new directory for our project mkdir kotlin-mcp-client cd kotlin-mcp-client # Initialize a new kotlin project gradle init ``` ``` # Create a new directory for our project md kotlin-mcp-client cd kotlin-mcp-client # Initialize a new kotlin project gradle init ``` 运行后 `gradle init`选择 **应用程序** 作为项目类型, **科特林语Name** 作为编程语言。在替代情况下,您可以使用 [IntelliJ IDEA 项目向导](<https://kotlinlang.org/docs/jvm-get-started.html>)创建此工程后, 替换您的 `build.gradle.kts` 改为: 建置. gradle.kts (中文(简体) ). ``` // Check latest versions at https://github.com/modelcontextprotocol/kotlin-sdk/releases val mcpVersion = "0.16.0" val ktorVersion = "3.2.3" val anthropicVersion = "2.15.0" val slf4jVersion = "2.0.17" plugins { kotlin("jvm") version "2.3.20" id("com.gradleup.shadow") version "8.3.9" application } version = "0.1.0" repositories { mavenCentral() } application { mainClass.set("MainKt") } dependencies { implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion") implementation("io.ktor:ktor-client-cio:$ktorVersion") implementation("com.anthropic:anthropic-java:$anthropicVersion") implementation("org.slf4j:slf4j-simple:$slf4jVersion") } ``` 校验所有设置是否正确: ``` ./gradlew build ``` ## 设置您的 API 密钥 您需要来自本地的 Anthropic API 密钥 [自动控制台](<https://console.anthropic.com/settings/keys>)设置您的 API 密钥 : ``` export ANTHROPIC_API_KEY='your-anthropic-api-key-here' ``` 一定要留着你的 `ANTHROPIC_API_KEY` 安全了! 安全了! 快点! 安全了! ## 创建客户端 ### 基本客户结构 首先,让我们创建基本的客户类: ``` private const val MODEL = "claude-haiku-5-5" // The model thinks adaptively unless told otherwise, and max_tokens caps thinking // plus the reply, so leave room for both. private const val MAX_TOKENS = 10_000L private const val MAX_TOOL_TURNS = 10 class MCPClient(apiKey: String) : AutoCloseable { private val anthropic = AnthropicOkHttpClient.builder() .apiKey(apiKey) .build() private val mcp: Client = Client( clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0") ) private var serverProcess: Process? = null private lateinit var tools: List<ToolUnion> // methods will go here override fun close() { runBlocking { mcp.close() } serverProcess?.destroy() anthropic.close() } } ``` ### 服务器连接管理 接下来, 我们将执行连接到 MCP 服务器的方法 : ``` suspend fun connectToServer(serverScriptPath: String) { val command = buildList { when (serverScriptPath.substringAfterLast(".")) { "js" -> add("node") "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3") "jar" -> addAll(listOf("java", "-jar")) else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file") } add(serverScriptPath) } val process = ProcessBuilder(command).start() serverProcess = process val transport = StdioClientTransport( input = process.inputStream.asSource().buffered(), output = process.outputStream.asSink().buffered(), ) mcp.connect(transport) val toolsResult = mcp.listTools() tools = toolsResult.tools.map { tool -> ToolUnion.ofTool( Tool.builder() .name(tool.name) .description(tool.description ?: "") .inputSchema( Tool.InputSchema.builder() .type(JsonValue.from(tool.inputSchema.type)) .properties(tool.inputSchema.properties?.toJsonValue() ?: EmptyJsonObject.toJsonValue()) .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required)) .build(), ) .build(), ) } println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}") } ``` JsonObject .to JsonValue () 帮助器 此帮助转换 kotlinx. 串行化 `JsonObject` 改为Athropic SDK `JsonValue` 使用杰克逊: ``` private fun JsonObject.toJsonValue(): JsonValue { val mapper = ObjectMapper() val node = mapper.readTree(this.toString()) return JsonValue.fromJsonNode(node) } ``` ### 查询处理逻辑 现在让我们添加处理查询和处理工具调用的核心功能。克劳德可以一次请求几个工具,在读取其结果后可以请求更多,所以客户端运行一个循环:它执行每个请求的工具,将所有结果都发回到一个消息中,并重复到克劳德回答,没有工具调用或 `MAX_TOOL_TURNS` 到达 : ``` suspend fun processQuery(query: String): String { val messages = mutableListOf( MessageParam.builder() .role(MessageParam.Role.USER) .content(query) .build(), ) var response = anthropic.messages().create( MessageCreateParams.builder() .model(MODEL) .maxTokens(MAX_TOKENS) .messages(messages) .tools(tools) .build(), ) val finalText = mutableListOf<String>() repeat(MAX_TOOL_TURNS) { val toolUses = mutableListOf<ToolUseBlock>() response.content().forEach { block -> when { block.isText() -> finalText.add(block.text().get().text()) block.isToolUse() -> toolUses.add(block.toolUse().get()) } } if (toolUses.isEmpty()) return finalText.joinToString("\n") val toolResults = toolUses.map { toolUse -> val toolArgs = toolUse._input().convert(object : TypeReference<Map<String, JsonValue>>() {}) finalText.add("[Calling tool ${toolUse.name()} with args $toolArgs]") val result = mcp.callTool( name = toolUse.name(), arguments = toolArgs ?: emptyMap(), ) // content is a list of block types, so forward only the text ones. MCP // and Anthropic block shapes differ, so other kinds need converting. ContentBlockParam.ofToolResult( ToolResultBlockParam.builder() .toolUseId(toolUse.id()) .content(result.content.filterIsInstance<TextContent>().joinToString("\n") { it.text }) .apply { if (result.isError == true) isError(true) } .build(), ) } // Replay the full assistant turn, tool_use blocks included, then send // every tool result of this turn in one user message. messages.add( MessageParam.builder() .role(MessageParam.Role.ASSISTANT) .contentOfBlockParams(response.content().map { it.toParam() }) .build(), ) messages.add( MessageParam.builder() .role(MessageParam.Role.USER) .contentOfBlockParams(toolResults) .build(), ) response = anthropic.messages().create( MessageCreateParams.builder() .model(MODEL) .maxTokens(MAX_TOKENS) .messages(messages) .tools(tools) .build(), ) } // The turn cap was hit. Keep the last response's text. If it asked for // more tools, say they were not run. var wantsTools = false response.content().forEach { block -> when { block.isText() -> finalText.add(block.text().get().text()) block.isToolUse() -> wantsTools = true } } if (wantsTools) finalText.add("[Stopped after $MAX_TOOL_TURNS tool-use turns]") return finalText.joinToString("\n") } ``` `callTool` 返回 a `CallToolResult`. 其内容 `content` 是一个块列表,这就是为什么代码缩窄到 `TextContent` 阅读前 `.text`。失败的工具不会丢到这里:它用 `isError` 将旗子通过 `ToolResultBlockParam` 让Claude读到信息并尝试其他东西。每个工具结果都带有 `id` 会 议 日 程 和 议 程 `tool_use` 屏蔽它的答复,助手转回原样,所以对话对下一个呼叫仍然有效。 ### 交互式聊天 我们将会加入聊天圈: ``` suspend fun chatLoop() { println("\nMCP Client Started!") println("Type your queries or 'quit' to exit.") while (true) { print("\nQuery: ") val message = readlnOrNull() ?: break if (message.trim().lowercase() == "quit") break try { val response = processQuery(message) println("\n$response") } catch (e: Exception) { println("\nError: ${e.message}") } } } ``` ### 主要切入点 最后,我们将增加主要执行职能: ``` fun main(args: Array<String>) = runBlocking { require(args.isNotEmpty()) { "Usage: java -jar <path> <path_to_server_script>" } val apiKey = System.getenv("ANTHROPIC_API_KEY") require(!apiKey.isNullOrBlank()) { "ANTHROPIC_API_KEY environment variable is not set" } val client = MCPClient(apiKey) client.use { client.connectToServer(args.first()) client.chatLoop() } } ``` ## 运行客户端 要用 MCP 服务器运行您的客户端 : ``` ./gradlew build # Run the client java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.jar # JVM server java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/server.py # Python server java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar path/to/build/index.js # Node server ``` 或者,您可以直接使用 Gradle 运行 : ``` ./gradlew run --args="path/to/server.jar" ``` 如果你继续从服务器快速启动的天气辅导, 您的命令可能看起来是这样的: `java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar .../samples/weather-stdio-server/build/libs/weather-stdio-server-0.1.0-all.jar` **客户将:** 1. 连接到指定的服务器 2. 列出可用的工具 3. 启动交互聊天会话, 您可以在此进行 : - 输入查询 - 见工具处决 - 得到克劳德的答复 ## 如何运作 以下是高级工作流程计划: 当您提交查询时: 1. 客户端从服务器获取可用的工具列表 2. 您的查询随工具描述一起发送给 Claude 3. Claude决定使用哪些工具(如果有的话) 4. 客户端通过服务器执行每个请求的工具调用并转发 `isError` 失败的呼叫的旗帜 5. 客户端重放助手转身后,将所有工具结果以一个消息的形式发回克劳德,工具描述再次附上 6. 步骤 3 到5 重复,直到克劳德回答,没有工具呼叫或 `MAX_TOOL_TURNS` 已到达 7. 回复显示在您身上 ## 最佳做法 1. **处理错误** - 检查 `result.isError` 每个工具结果并用 `isError(true)`,因为一个失败的工具用那面旗帜回答,而不是扔 - 保留 `MAX_TOOL_TURNS` 设置了这样一个运行, 持续请求工具以可见消息停止 - 利用Kotlin的类型系统来明确模拟错误 - 环绕外部工具和 API 呼叫 `try-catch` 可能例外时的块 - 提供明确和有意义的错误信息 - 处理网络超时和连接问题 2. **警卫** - 安全存储 API 密钥和秘密 `local.properties`,环境变量,或秘密管理器 - 验证所有外部响应, 以避免意外或不安全的数据使用 - 在使用工具时要谨慎使用权限和信任边界 3. **环境** - 设定 `ANTHROPIC_API_KEY` 通过环境变量而不是硬编码 - 使用( U) `.env` 带有相应文件的文件 `.gitignore` 地方发展规则 ## 解决问题 ### 服务器路径问题 - 双向检查您的服务器脚本路径正确 - 如果相对路径无效, 则使用绝对路径 - 对于 Windows 用户, 请在路径中确保使用前鞭 (/) 或逃脱后鞭 (\) - 确保安装所需的运行时间(Java的java、Node.js的npm或Python的uv) - 验证服务器文件有正确的扩展名(Java的.jar,节点的.js或Python的.py) 正确路径使用示例 : ``` # Relative path java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar ./server/build/libs/server.jar # Absolute path java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar /Users/username/projects/mcp-server/build/libs/server.jar # Windows path (either format works) java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar C:/projects/mcp-server/build/libs/server.jar java -jar build/libs/kotlin-mcp-client-0.1.0-all.jar C:\\projects\\mcp-server\\build\\libs\\server.jar ``` ### 构建问题 - 使用( U) `./gradlew build` 或 时 间 `./gradlew shadowJar` (无) `./gradlew jar`) 创建带有所有依赖性的阴影 JAR - 如果您获得 JDK 版本错误, 请确保您安装的 JDK 是 17 或更高版本 ### 反应时间 - 第一个反应可能要花到30秒才能返回 - 这是正常的,而且发生时: - 服务器初始化 - Claude 处理查询 - 正在执行工具 - 随后的反应通常更快 - 在最初的等待期不要打断这一过程 ### 常见错误消息 若见: - `Connection closed`: 检查您的服务器路径, 然后直接运行服务器命令, 以查看它是否开始 - `Tool execution failed`: 验证工具所需的环境变量已设定 - `[Stopped after 10 tool-use turns]`: Claude 仍在要求工具时 `MAX_TOOL_TURNS` 已耗尽,所以要加盖或缩小查询范围 - `ANTHROPIC_API_KEY is not set`: 检查您的环境变量 [您可以在此找到此教程的完整代码 。](<https://github.com/modelcontextprotocol/csharp-sdk/tree/main/samples/QuickstartClient>) ## 系统要求 在开始前,确保您的系统满足这些要求: - .NET 10.0 或 以上 - Anthropic API 密钥 (克劳德) - 视窗、 Linux 或 macOS ## 创造你的环境 首先,创建一个新的.NET项目: ``` dotnet new console -n QuickstartClient cd QuickstartClient ``` 然后,在您的项目中添加所需的依赖性 : ``` dotnet add package ModelContextProtocol dotnet add package Anthropic dotnet add package Microsoft.Extensions.Hosting dotnet add package Microsoft.Extensions.AI ``` ## 设置您的 API 密钥 您需要来自本地的 Anthropic API 密钥 [自动控制台](<https://console.anthropic.com/settings/keys>). ``` dotnet user-secrets init dotnet user-secrets set "ANTHROPIC_API_KEY" "<your key here>" ``` ## 创建客户端 ### 基本客户结构 首先,让我们在文档中设置基本的客户类 `Program.cs`: ``` using Anthropic; using Microsoft.Extensions.AI; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using ModelContextProtocol.Client; var builder = Host.CreateApplicationBuilder(args); builder.Configuration .AddEnvironmentVariables() .AddUserSecrets<Program>(); ``` 这会创建一个 .NET 控制台应用的雏形,该应用可以从用户机密中读取 API 密钥。接下来,我们将设置 MCP 客户端: ``` var (command, arguments) = GetCommandAndArguments(args); var clientTransport = new StdioClientTransport(new() { Name = "Demo Server", Command = command, Arguments = arguments, }); await using var mcpClient = await McpClient.CreateAsync(clientTransport); var tools = await mcpClient.ListToolsAsync(); foreach (var tool in tools) { Console.WriteLine($"Connected to server with tools: {tool.Name}"); } ``` 在结尾添加此函数 `Program.cs` 文件 : ``` static (string command, string[] arguments) GetCommandAndArguments(string[] args) { return args switch { [var script] when script.EndsWith(".py") => ("python", args), [var script] when script.EndsWith(".js") => ("node", args), [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(".csproj")) => ("dotnet", ["run", "--project", script, "--no-build"]), _ => throw new NotSupportedException("An unsupported server script was provided. Supported scripts are .py, .js, or .csproj") }; } ``` 这将创建一个 MCP 客户端, 连接到作为命令行参数提供的服务器, 然后从连接的服务器中列出可用的工具 。 ### 查询处理逻辑 现在让我们加入处理查询和处理工具呼叫的核心功能: ``` using var anthropicClient = new AnthropicClient(new() { ApiKey = builder.Configuration["ANTHROPIC_API_KEY"] }) .AsIChatClient("claude-haiku-5-5") .AsBuilder() .UseFunctionInvocation() .Build(); var options = new ChatOptions { MaxOutputTokens = 10000, Tools = [.. tools] }; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("MCP Client Started!"); Console.ResetColor(); PromptForInput(); while(Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrWhiteSpace(query)) { PromptForInput(); continue; } await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options)) { Console.Write(message); } Console.WriteLine(); PromptForInput(); } static void PromptForInput() { Console.WriteLine("Enter a command (or 'exit' to quit):"); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("> "); Console.ResetColor(); } ``` ## 已解释关键部件 ### 1. 客户端初始化 - 客户端初始化使用 `McpClient.CreateAsync()`,它设置了运行服务器的传输类型和命令。 ### 2. 服务器连接 - 支持Python,Node.js和.NET服务器. - 服务器开始使用参数中指定的命令. - 配置用于与服务器通信的 stdio 。 - 初始化会话和可用工具。 ### 3. 查询处理 - 积蓄 [微软. Extensions.AI](<https://learn.microsoft.com/dotnet/ai/ai-extensions>) 用于聊天客户端. - 配置 `IChatClient` 以使用自动工具(功能)引用。 - 客户端读取用户输入并发送给克劳德. - 当克劳德要求工具时,客户端在服务器上调用,并将结果发回克劳德. - 客户端显示克劳德对用户的回应. ## 运行客户端 要用 MCP 服务器运行您的客户端 : ``` dotnet run -- path/to/server.csproj # dotnet server dotnet run -- path/to/server.py # python server dotnet run -- path/to/server.js # node server ``` 如果你继续从服务器快速启动的天气辅导, 您的命令可能看起来是这样的: `dotnet run -- path/to/QuickstartWeatherServer`. 客户将: 1. 连接到指定的服务器 2. 列出可用的工具 3. 启动交互聊天会话, 您可以在此进行 : - 输入查询 - 得到克劳德的答复 4. 完成时退出会话 以下是一个实例, 说明如果连接到天气服务器的快速启动,  [您可以在此找到此教程的完整代码 。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-ruby>) ## 系统要求 在开始前,确保您的系统满足这些要求: - macOS, Windows, 或 Linux 计算机 - Ruby 3.2.0 或 以上设备已安装(由 [Anhropic SDK (英语).](<https://github.com/anthropics/anthropic-sdk-ruby>)) - Anthropic API 密钥 (克劳德) ## 设置您的环境 首先,创建一个新的Ruby项目: ``` # Create project directory mkdir mcp-client cd mcp-client # Create a Gemfile bundle init # Add required dependencies bundle add anthropic dotenv mcp # Create our main file touch client.rb ``` ``` # Create project directory mkdir mcp-client cd mcp-client # Create a Gemfile bundle init # Add required dependencies bundle add anthropic dotenv mcp # Create our main file new-item client.rb ``` ## 设置您的 API 密钥 您需要来自本地的 Anthropic API 密钥 [自动控制台](<https://console.anthropic.com/settings/keys>)创建 a `.env` 要存储的文件 : ``` echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env ``` 添加 `.env` 给您的 `.gitignore`: ``` echo ".env" >> .gitignore ``` 一定要留着你的 `ANTHROPIC_API_KEY` 安全了! 安全了! 快点! 安全了! ## 创建客户端 ### 基本客户结构 首先,让我们确定我们的要求,创建基本的客户阶层: ``` require "anthropic" require "dotenv/load" require "json" require "mcp" class MCPClient ANTHROPIC_MODEL = "claude-haiku-5-5" # The model thinks adaptively unless told otherwise, and max_tokens caps thinking # plus the reply, so leave room for both. MAX_TOKENS = 10000 MAX_TOOL_TURNS = 10 def initialize @mcp_client = nil @transport = nil @anthropic_client = nil end # methods will go here end ``` ### 服务器连接管理 接下来, 我们将执行连接到 MCP 服务器的方法 : ``` def connect_to_server(server_script_path) command = case File.extname(server_script_path) when ".rb" "ruby" when ".py" "python3" when ".js" "node" else raise ArgumentError, "Server script must be a .rb, .py, or .js file." end @transport = MCP::Client::Stdio.new(command: command, args: [server_script_path]) @mcp_client = MCP::Client.new(transport: @transport) @mcp_client.connect tool_names = @mcp_client.tools.map(&:name) puts "\nConnected to server with tools: #{tool_names}" end ``` ### 查询处理逻辑 现在让我们添加处理查询和处理工具调用的核心功能。每个转弯都会运行克劳德要求的每一个工具,将所有结果放回一条信息中,并用所附工具再次给克劳德打电话,直到克劳德回答时没有工具调用或 `MAX_TOOL_TURNS` 到达 : ``` def process_query(query) messages = [{ role: "user", content: query }] available_tools = @mcp_client.tools.map do |tool| { name: tool.name, description: tool.description, input_schema: tool.input_schema } end final_text = [] # Initial Claude API call with tools. response = chat(messages, available_tools) # Keep calling tools until Claude answers without one, up to a cap. MAX_TOOL_TURNS.times do tool_uses = [] response.content.each do |block| case block when Anthropic::Models::TextBlock final_text << block.text when Anthropic::Models::ToolUseBlock tool_uses << block end end return final_text.join("\n") if tool_uses.empty? # Execute every tool call in this response and collect the results. tool_results = tool_uses.map do |tool_use| result = @mcp_client.call_tool(name: tool_use.name, arguments: tool_use.input) final_text << "[Calling tool #{tool_use.name} with args #{tool_use.input.to_json}]" is_error = result.dig("result", "isError") == true # content is a list of block types, so forward only the text ones. tool_result_content = result.dig("result", "content") result_text = if tool_result_content.is_a?(Array) tool_result_content.filter_map { |content_item| content_item["text"] }.join("\n") else tool_result_content.to_s end { type: "tool_result", tool_use_id: tool_use.id, content: result_text, is_error: is_error } end # Append the assistant's response and all tool results, in one user # message, to the history. Every tool_use needs a matching tool_result. messages << { role: "assistant", content: assistant_content(response) } messages << { role: "user", content: tool_results } response = chat(messages, available_tools) end # The turn cap was hit. Keep the last response's text. If it asked for # more tools, say they were not run. response.content.each do |block| final_text << block.text if block.is_a?(Anthropic::Models::TextBlock) end if response.content.any?(Anthropic::Models::ToolUseBlock) final_text << "[Stopped after #{MAX_TOOL_TURNS} tool-use turns]" end final_text.join("\n") end ``` ### 交互式聊天界面 现在,我们将添加聊天循环和清理功能,然后是私人帮助者 `process_query` 依赖 : ``` def chat_loop puts <<~MESSAGE MCP Client Started! Type your queries or 'quit' to exit. MESSAGE loop do print "\nQuery: " line = $stdin.gets break if line.nil? query = line.chomp.strip break if query.downcase == "quit" next if query.empty? begin response = process_query(query) puts "\n#{response}" rescue => e puts "\nError: #{e.message}" end end end def cleanup @transport&.close end private # Convert a response's content blocks back into request parameters. Thinking # blocks must go back unchanged, signature included, or the API rejects the # follow-up request. def assistant_content(response) response.content.filter_map do |block| case block when Anthropic::Models::TextBlock { type: "text", text: block.text } when Anthropic::Models::ToolUseBlock { type: "tool_use", id: block.id, name: block.name, input: block.input } when Anthropic::Models::ThinkingBlock { type: "thinking", thinking: block.thinking, signature: block.signature } when Anthropic::Models::RedactedThinkingBlock { type: "redacted_thinking", data: block.data } end end end # Tools are passed on every call so Claude can keep calling them across turns. def chat(messages, tools) anthropic_client.messages.create( model: ANTHROPIC_MODEL, max_tokens: MAX_TOKENS, messages: messages, tools: tools ) end def anthropic_client @anthropic_client ||= Anthropic::Client.new(api_key: ENV["ANTHROPIC_API_KEY"]) end ``` ### 主条目 最后,我们将补充主要的执行逻辑: ``` if ARGV.empty? puts "Usage: ruby client.rb <path_to_server_script>" exit 1 end client = MCPClient.new begin client.connect_to_server(ARGV[0]) api_key = ENV["ANTHROPIC_API_KEY"] if api_key.nil? || api_key.empty? puts <<~MESSAGE No ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key: export ANTHROPIC_API_KEY=your-api-key-here MESSAGE exit end client.chat_loop rescue => e puts "Error: #{e.message}" exit 1 ensure client.cleanup end ``` 你可以找到完整的东西 `client.rb` 文件 [这儿](<https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-ruby/client.rb>). ## 已解释关键部件 ### 1. 客户端初始化 - 那个... `MCPClient` 类初始化,对于懒惰的设置则无参考文献 - Anthropic 客户端通过 `anthropic_client` 方法 - 用途 `dotenv` 以装入环境变量 `.env` ### 2. 服务器连接 - 支持Ruby、Python和Node.js服务器 - 用途 `File.extname` 确定服务器脚本类型 - 用途 `MCP::Client::Stdio` 标准运输 - 初始化 MCP 客户端并列出可用的工具 ### 3. 查询处理 - 将 MCP 工具映射到 Anthropic 工具格式(`name`, `description`, `input_schema`) - 用途 `Anthropic::Models::TextBlock` 财务报告和财务报告 `Anthropic::Models::ToolUseBlock` 用于图案匹配 - 循环至 `MAX_TOOL_TURNS` 时间, 在每次响应中运行每个工具调用 - 执行工具调用 `@mcp_client.call_tool` - 提取工具结果内容 `result.dig("result", "content")` 和错误标记 `result.dig("result", "isError")` - 发送全部转弯 `tool_result` 在单个用户消息中块,每个带其 `tool_use_id` 财务报告和财务报告 `is_error` - 重玩助手转身 `assistant_content`来回思考 和他们的签名完全一样 - 使用 `chat` 帮助者, 传递 `tools` 财务报告和财务报告 `MAX_TOKENS` 每一次API电话 ### 4. 交互式接口 - 提供简单的命令行界面 - 处理用户输入并显示响应 - 跳过空查询 - 包括基本错误处理 ### 5. 资源管理 - 适当清理途经的运输 `begin`…`ensure` - 顶级 `rescue` 用于处理错误 - API 服务器连接后的密钥验证 ## 运行客户端 要用 MCP 服务器运行您的客户端 : ``` bundle exec ruby client.rb path/to/server.rb # ruby server bundle exec ruby client.rb path/to/server.py # python server bundle exec ruby client.rb path/to/build/index.js # node server ``` 如果你继续的话 [从服务器快速启动的天气教程](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-ruby>)你的命令可能是这样的: `bundle exec ruby client.rb /path/to/weather-server-ruby/weather.rb` 客户将: 1. 连接到指定的服务器 2. 列出可用的工具 3. 启动交互聊天会话, 您可以在此进行 : - 输入查询 - 见工具处决 - 得到克劳德的答复 ## 如何运作 当您提交查询时 : 1. 客户端从服务器获取可用的工具列表 2. 您的查询随工具描述一起发送给 Claude 3. Claude决定使用哪些工具(如果有的话) 4. 客户端通过服务器执行每个请求的工具调用 5. 助手转弯,所有工具结果都送回克劳德,工具再次附着 6. 步骤 3 到5 重复,直到克劳德回答,没有工具呼叫或 `MAX_TOOL_TURNS` 已到达 7. Claude提供了一种自然语言的反应 8. 回复显示在您身上 ## 最佳做法 1. **处理错误** - 环绕工具调用 `begin`…`rescue` 块 - 检查 `isError` 每个工具结果,并转发为 `is_error` 而不是期待一个失败的工具来提高 - 提供有意义的错误信息 - 善于处理连接问题 2. **资源管理** - 完成后总是关闭传送 - 使用( U) `begin`…`ensure` 进行适当的清理 - Cap 工具使用转动 `MAX_TOOL_TURNS` 因此,一个查询不能无限循环 - 处理服务器断开 3. **警卫** - 安全存储 API 密钥 `.env` - 验证服务器响应 - 工具权限要小心 4. **工具名称** - 工具名可按指定格式验证 [这儿](<https://modelcontextprotocol.io/specification/2026-07-28/server/tools#tool-names>) - 如果一个工具名称符合指定格式, 它不应失败 MCP 客户端的验证 ## 解决问题 ### 服务器路径问题 - 双向检查您的服务器脚本路径正确 - 如果相对路径无效, 则使用绝对路径 - 对于 Windows 用户, 请在路径中确保使用前鞭 (/) 或逃脱后鞭 (\) - 校验服务器文件有正确的扩展名( Python 的.py, Node.js 的.js, 或 Ruby 的.rb) 正确路径使用示例 : ``` # Relative path bundle exec ruby client.rb ./server/weather.rb # Absolute path bundle exec ruby client.rb /Users/username/projects/mcp-server/weather.rb # Windows path (either format works) bundle exec ruby client.rb C:/projects/mcp-server/weather.rb bundle exec ruby client.rb C:\\projects\\mcp-server\\weather.rb ``` ### 反应时间 - 第一个反应可能要花到30秒才能返回 - 这是正常的,而且发生时: - 服务器初始化 - Claude 处理查询 - 正在执行工具 - 随后的反应通常更快 - 在最初的等待期不要打断这一过程 ### 常见错误消息 若见: - `Failed to spawn server process`:确保命令(`ruby`, `python3`, `node`) 备有 - `Server process has exited` 或 时 间 `Failed to write to server process`: 检查您的服务器路径, 然后直接运行服务器命令, 以查看它是否开始 - `Tool execution failed`: 验证工具所需的环境变量已设定 - `Anthropic::Errors::AuthenticationError`: 检查您 `.env` 文件有效 `ANTHROPIC_API_KEY` - `[Stopped after 10 tool-use turns]`Claude不断要求工具 所以客户端停了下来 `MAX_TOOL_TURNS` 然后还原了迄今为止收集的文本 [您可以在此找到此教程的完整代码 。](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client-rust>) ## 系统要求 在开始前,确保您的系统满足这些要求: - [铁和货物](<https://www.rust-lang.org/tools/install>) 1.88 或更新 - Anthropic API 密钥 (克劳德) - 连接到的 Python、Node.js 或可执行的 MCP 服务器 ## 设置您的环境 首先,创建一个新的 Rust 项目: ``` cargo new mcp-client-rust cd mcp-client-rust ``` 替换 `Cargo.toml` 含下列内容: 货物.toml ``` [package] name = "mcp-client-rust" version = "0.1.0" edition = "2024" [dependencies] anyhow = "1.0.104" jsonschema = "0.59" # Only the client half of rmcp is needed, over a child-process stdio transport. rmcp = { version = "3.4", features = [ "client", "transport-io", "transport-child-process", ], default-features = false } # The Messages API is called directly, which keeps the provider's content # blocks verbatim. That matters for signed thinking blocks; see request_model. reqwest = { version = "0.13", features = ["json"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0.151" tokio = { version = "1.53", features = ["full"] } dotenvy = "0.15.7" ``` 那个... [`rmcp`](<https://github.com/modelcontextprotocol/rust-sdk>) 板条箱提供了 Rust MCP SDK 和子进程 stdio 传输。仅启用了它的客户端的一半。客户端呼叫 [信件 API](<https://docs.anthropic.com/en/api/messages>) 直接与 [`reqwest`](<https://docs.rs/reqwest>)。拨打 API 直接保留每次回复的内容块,当回复包含一个签名的思维块时,这些内容块就很重要。 [`jsonschema`](<https://docs.rs/jsonschema>) 箱对照一个工具宣布的计划验证结构化工具结果 。 ## 设置您的 API 密钥 您需要来自本地的 Anthropic API 密钥 [自动控制台](<https://console.anthropic.com/settings/keys>)创建 a `.env` 要存储的文件 : ``` echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env ``` 添加 `.env` 给您的 `.gitignore`: ``` echo ".env" >> .gitignore ``` 客户端加载 `.env` 当文件存在时。导出 `ANTHROPIC_API_KEY` 在壳里也起作用。 一定要留着你的 `ANTHROPIC_API_KEY` 安全了! 安全了! 快点! 安全了! ## 创建客户端 打开 `src/main.rs` 并替换其内容,因为您正在通过以下各节工作。 ### 进口和客户结构 第一,增加进口和常数: ``` use anyhow::{Context, Result, bail}; use jsonschema::Validator; use rmcp::model::{ CallToolRequestParams, CallToolResult, ClientCapabilities, ClientConfig, Implementation, ProtocolVersion, Tool as McpTool, }; use rmcp::service::{ClientLifecycleMode, ClientServiceExt, RoleClient, RunningService}; use rmcp::transport::TokioChildProcess; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::collections::HashMap; use std::time::Duration; use tokio::io::{self, AsyncBufReadExt, BufReader}; use tokio::process::Command; const MODEL_ANTHROPIC: &str = "claude-haiku-5-5"; /// The model may think before answering, and max_tokens caps thinking /// plus the reply, so leave room for both. const MAX_TOKENS: u32 = 10000; const MAX_TOOL_TURNS: usize = 10; const ANTHROPIC_API_BASE: &str = "https://api.anthropic.com"; const ANTHROPIC_VERSION: &str = "2023-06-01"; const REQUEST_TIMEOUT: Duration = Duration::from_secs(120); ``` `MAX_TOKENS` 将思考和回答放在一起。 `MAX_TOOL_TURNS` 限定一个查询可能要使用多少轮工具。 `REQUEST_TIMEOUT` 适用于发送到信件的每个请求 API.Next, 添加信件 API 的类型和客户端结构 : ``` /// One turn of the conversation, as the Messages API takes it. /// /// `content` is a list of raw blocks rather than typed ones on purpose. An /// assistant turn is fed straight back on the next request, and Claude requires /// the blocks it sent to return unchanged -- a thinking block's `signature` /// included. Reserialising through a narrower type would drop whatever it does /// not model. #[derive(Serialize, Clone)] struct Message { role: &'static str, content: Vec<Value>, } impl Message { fn user(content: Vec<Value>) -> Self { Message { role: "user", content, } } fn assistant(content: Vec<Value>) -> Self { Message { role: "assistant", content, } } } /// A tool as the Messages API declares it, converted from an MCP tool. #[derive(Serialize, Clone)] struct ToolDefinition { name: String, #[serde(skip_serializing_if = "Option::is_none")] description: Option<String>, input_schema: Value, } #[derive(Serialize)] struct MessagesRequest<'a> { model: &'a str, max_tokens: u32, messages: &'a [Message], tools: &'a [ToolDefinition], } #[derive(Deserialize)] struct MessagesResponse { content: Vec<Value>, } /// The `type` of a content block, when it has one. fn block_type(block: &Value) -> &str { block .get("type") .and_then(Value::as_str) .unwrap_or_default() } struct MCPClient { http: reqwest::Client, session: Option<RunningService<RoleClient, ClientConfig>>, tools: Vec<ToolDefinition>, /// Compiled `outputSchema` per tool name. rmcp does not validate results, /// so this client does it with the `jsonschema` crate. output_schemas: HashMap<String, Validator>, } ``` `Message` 将一个回合的内容块作为原始 `serde_json::Value`s. 助理在下一个请求时返回API,没有改变,并带有任何思维障碍及其 `signature` 完好无损 `ToolDefinition` 当信件 API 声明它时,它是一个工具。 `MCPClient` 保留 HTTP 客户端、 活跃的 MCP 会话、 信件 API 表格中的工具, 以及每个工具中一个编译的验证符, 声明一个 `outputSchema`. ### 客户端初始化 接下来,打开 `impl MCPClient` 块与构造器。以下各节中的方法将进入此块内,然后关闭 `cleanup`: ``` impl MCPClient { fn new() -> Result<Self> { Ok(MCPClient { http: reqwest::Client::builder() .timeout(REQUEST_TIMEOUT) .build() .context("Failed to build HTTP client")?, session: None, tools: Vec::new(), output_schemas: HashMap::new(), }) } ``` `new` 构建一个 `reqwest::Client` 与请求超时。当请求被发送时, API 密钥会在稍后被读取, 因此连接到服务器, 并列出其工具在无此功能的情况下工作 。 ### 验证结构化工具输出 将此方法添加到 `impl MCPClient` 块 : ``` /// Check a result against its tool's declared `outputSchema`. Error results /// are exempt: they carry a message, not data. fn validate_tool_output(&self, name: &str, result: &CallToolResult) -> Result<()> { let Some(validator) = self.output_schemas.get(name) else { return Ok(()); }; if result.is_error.unwrap_or(false) { return Ok(()); } let Some(structured) = &result.structured_content else { bail!("Tool {name} declares an output schema but returned no structured content"); }; if let Err(error) = validator.validate(structured) { bail!("Structured content from tool {name} does not match its output schema: {error}"); } Ok(()) } ``` 工具可以声明: `outputSchema`,且规格要求客户端验证 `structuredContent` 反之。 Rmcp 不这样做, 所以客户端保存一个编译器 `jsonschema::Validator` 每个工具并检查每个成功结果。 `is_error` 设置中包含一个消息,因此可以免责。一个宣布一个计划而返回没有结构化内容的工具会被报告为错误。 ### 服务器连接管理 将此方法添加到 `impl MCPClient` 块 : ``` async fn connect_to_server(&mut self, server_args: &[String]) -> Result<()> { if self.session.is_some() { bail!("Client is already connected to a server"); } let mut command = Command::new(&server_args[0]); command.args(&server_args[1..]); let process = TokioChildProcess::new(command) .with_context(|| format!("Failed to spawn server process for {:?}", server_args))?; // Without a ClientConfig the client would report rmcp's own crate name // and version rather than its own. let config = ClientConfig::new( ClientCapabilities::default(), Implementation::new("mcp-client-rust", "1.0.0"), ); // `Auto` probes server/discover and falls back to the 2025-11-25 // initialize handshake, matching the Python and TypeScript clients. // `serve` alone would only ever do the legacy handshake, under which a // server cannot offer this era's features -- an array-rooted // `outputSchema`, for one, which get_alerts uses. let session = config .serve_with_lifecycle( process, ClientLifecycleMode::Auto { preferred_versions: vec![ProtocolVersion::V_2026_07_28], legacy_version: Some(ProtocolVersion::V_2025_11_25), }, ) .await?; let rmcp_tools = session .list_all_tools() .await .context("Unable to list tools from server")?; let tool_names: Vec<String> = rmcp_tools .iter() .map(|tool| tool.name.to_string()) .collect(); let protocol_version = session .peer_info() .map(|info| info.protocol_version.to_string()) .unwrap_or_else(|| "unknown".to_string()); println!("Connected over protocol {protocol_version} with tools: {tool_names:?}"); // An outputSchema root may be any JSON Schema, not just an object. for tool in &rmcp_tools { let Some(schema) = &tool.output_schema else { continue; }; let schema = Value::Object(schema.as_ref().clone()); let validator = Validator::new(&schema).with_context(|| { format!("Failed to compile output schema of tool {}", tool.name) })?; self.output_schemas.insert(tool.name.to_string(), validator); } self.tools = convert_tools(&rmcp_tools); self.session = Some(session); Ok(()) } ``` 这种方法 : 1. 使用命令行上提供的命令和参数启动服务器为子进程 2. 客户端名称 `mcp-client-rust` 通过a `ClientConfig` 3. 谈判协议 `serve_with_lifecycle` 财务报告和财务报告 `ClientLifecycleMode::Auto`,该探测器 `server/discover` (单位:千美元) `2026-07-28` 然后掉回原地 回到原地 `2025-11-25` `initialize` 握手时 4. 列出服务器广告的所有工具, 并用工具名称打印协议版本 5. 从每个工具编译一个验证符 `outputSchema` 6. 将工具转换为模型请求中使用的窗体 rmcp 数据 `serve` 方法本身只进行遗留的握手。 `Auto` 模式使当前修订版的特性可以达到,包括 `outputSchema` 其根为阵. ### 查询处理逻辑 现在在内部添加核心查询处理方法 `impl MCPClient`: ``` async fn process_query(&mut self, query: &str) -> Result<String> { let session = self .session .as_ref() .context("Client is not connected to any server")?; let mut messages = vec![Message::user(vec![json!({"type": "text", "text": query})])]; let mut final_text = Vec::new(); // Initial Claude API call with tools let mut content = self.request_model(&messages).await?; // Keep calling tools until Claude answers without one, up to a cap. for _ in 0..MAX_TOOL_TURNS { let mut tool_uses = Vec::new(); for block in &content { match block_type(block) { "text" => { if let Some(text) = block.get("text").and_then(Value::as_str) { final_text.push(text.to_string()); } } "tool_use" => tool_uses.push(block.clone()), _ => {} } } if tool_uses.is_empty() { return Ok(final_text.join("\n")); } // Execute every tool call in this response and collect the results let mut tool_results = Vec::new(); for tool_use in &tool_uses { let name = tool_use .get("name") .and_then(Value::as_str) .context("tool_use block has no name")?; let id = tool_use .get("id") .and_then(Value::as_str) .context("tool_use block has no id")?; let input = tool_use.get("input").cloned().unwrap_or(json!({})); // Add information about the tool call to final text final_text.push(format!("[Calling tool {name} with args {input}]")); // Query the MCP server let mut params = CallToolRequestParams::new(name.to_string()); if let Some(arguments) = input.as_object().cloned() { params = params.with_arguments(arguments); } let tool_result = match session.call_tool(params).await { Ok(result) => result, // A rejected call is the model's mistake to correct, so it // goes back as a failed tool_result rather than ending the // query. Every tool_use still needs a matching result. Err(error) => { final_text.push(format!("[{name} failed: {error}]")); tool_results.push(json!({ "type": "tool_result", "tool_use_id": id, "content": format!("Tool call {name} failed: {error}"), "is_error": true, })); continue; } }; self.validate_tool_output(name, &tool_result)?; // structured_content is data the application can use directly. if let Some(Value::Array(items)) = &tool_result.structured_content { final_text.push(format!("[{name} returned {} items]", items.len())); } // content is a list of block types; forward only the text ones. let mut payload = tool_result .content .iter() .filter_map(|block| block.as_text().map(|text| text.text.as_str())) .collect::<Vec<_>>() .join("\n"); // A structured result SHOULD also carry serialized JSON in a text // block, but only SHOULD, so fall back to serializing it rather // than sending the model an empty result. if payload.is_empty() { if let Some(structured) = &tool_result.structured_content { payload = structured.to_string(); } } tool_results.push(json!({ "type": "tool_result", "tool_use_id": id, "content": payload, "is_error": tool_result.is_error.unwrap_or(false), })); } // Append the assistant's response and all tool results, in one user // message, to the history. Every tool_use needs a matching // tool_result, and the assistant's blocks go back as they arrived. messages.push(Message::assistant(content)); messages.push(Message::user(tool_results)); content = self.request_model(&messages).await?; } // The turn cap was hit. Keep the last response's text. If it asked for // more tools, say they were not run. let mut wants_tools = false; for block in &content { match block_type(block) { "text" => { if let Some(text) = block.get("text").and_then(Value::as_str) { final_text.push(text.to_string()); } } "tool_use" => wants_tools = true, _ => {} } } if wants_tools { final_text.push(format!("[Stopped after {MAX_TOOL_TURNS} tool-use turns]")); } Ok(final_text.join("\n")) } ``` 该方法将用户的查询与服务器的工具一起发送给Claude,然后循环。每次通过都会收集回复的文本块并收集其文本块。 `tool_use` 块。当一个答复没有使用工具时,将返回所收集的文本。否则客户端通过 MCP 会话调用每个请求的工具并构建一个 `tool_result` 每块 `tool_use`。服务器拒绝的电话会与 `is_error` 设置,这样 Claude 可以读取信件并尝试其它东西。成功的结果会对照其输出方案进行检查。它的文本块会被合并并转发给 Claude, 当它没有文本块时, 序列化 `structured_content` 被送到他们的位置。 `structured_content` 是一个数组,客户端打印项目计数作为直接使用结构化数据的例子。助手的块恰好在到达时被附加到历史中,然后一个用户消息持有所有工具结果,然后发出下一个请求。循环停止于 `MAX_TOOL_TURNS` 回合。最后的回复文本保存下来,当克劳德要求获得更多工具时,会添加一个注释。 ### 发送模式请求 在内部添加此帮助方法 `impl MCPClient`: ``` /// Call Claude with the current history and return the content blocks of /// its reply, untouched. Tools are passed on every call so Claude can keep /// calling them across turns. async fn request_model(&self, messages: &[Message]) -> Result<Vec<Value>> { let api_key = std::env::var("ANTHROPIC_API_KEY").context("ANTHROPIC_API_KEY is not set")?; // The base URL is configurable so the client can point at a local stand-in. let base_url = std::env::var("ANTHROPIC_BASE_URL").unwrap_or_else(|_| ANTHROPIC_API_BASE.to_string()); let request = MessagesRequest { model: MODEL_ANTHROPIC, max_tokens: MAX_TOKENS, messages, tools: &self.tools, }; let response = self .http .post(format!("{}/v1/messages", base_url.trim_end_matches('/'))) .header("x-api-key", api_key) .header("anthropic-version", ANTHROPIC_VERSION) .json(&request) .send() .await .context("Anthropic request failed")?; let status = response.status(); let body = response .text() .await .context("Unable to read the Anthropic response")?; if !status.is_success() { bail!("Anthropic request failed with {status}: {body}"); } let parsed: MessagesResponse = serde_json::from_str(&body).context("Unable to parse the Anthropic response")?; Ok(parsed.content) } ``` `request_model` 读取 `ANTHROPIC_API_KEY` 并张贴历史 `/v1/messages` 与 `x-api-key` 财务报告和财务报告 `anthropic-version` 头目. `ANTHROPIC_BASE_URL` 覆盖端点, 这样可以将客户端指向本地站点。 每次请求都会发送工具, Claude 都可以不停地交叉调用它们。 非成功状态会成为一个包含响应机构的错误。 回复的内容块会返回到未更改的位置 。 ### 交互式聊天界面 在内部添加交互式终端循环 `impl MCPClient`: ``` async fn chat_loop(&mut self) -> Result<()> { println!("\nMCP Client Started!"); println!("Type your queries or 'quit' to exit."); let mut stdin = BufReader::new(io::stdin()); let mut input = String::new(); loop { print!("\nQuery: "); std::io::Write::flush(&mut std::io::stdout())?; input.clear(); if stdin.read_line(&mut input).await? == 0 { break; // EOF } let query = input.trim(); if query.eq_ignore_ascii_case("quit") { break; } if query.is_empty() { continue; } match self.process_query(query).await { Ok(response) => println!("\n{}", response), Err(err) => println!("\nError: {:#}", err), } } Ok(()) } ``` 循环接受查询,直到用户输入 `quit` 或关闭标准输入。在不终止客户端的情况下打印查询错误。 `{:#}` 格式打印整个 `anyhow` 上下文链条。 ### 清理 在内部添加此方法 `impl MCPClient` 停止 MCP 会话和子进程。 `impl MCPClient` 块 : ``` async fn cleanup(&mut self) -> Result<()> { if let Some(session) = self.session.take() { let _ = session.cancel().await; } Ok(()) } } ``` ### 主条目 下一个,在 `impl MCPClient` 块 : ``` #[tokio::main] async fn main() -> Result<()> { // .env is optional; the key may come from the environment instead. let _ = dotenvy::dotenv(); let mut args = std::env::args(); let _ = args.next(); let server_args: Vec<String> = args.collect(); if server_args.is_empty() { eprintln!("Usage: cargo run -- <server_script_or_binary> [args...]"); std::process::exit(1); } let mut client = MCPClient::new()?; let result = async { client.connect_to_server(&server_args).await?; // Connecting and listing tools needs no credentials; querying them // does. Matching the Python and TypeScript clients, report and exit // rather than failing, so the connection itself can be exercised // without a key. // Empty counts as unset, as it does in the other clients: `KEY= cmd` // is how the smoke test forces this path. if std::env::var("ANTHROPIC_API_KEY").map_or(true, |key| key.is_empty()) { println!( "\nNo ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:" ); println!(" export ANTHROPIC_API_KEY=your-api-key-here"); return Ok(()); } client.chat_loop().await } .await; let cleanup_result = client.cleanup().await; result?; cleanup_result?; Ok(()) } ``` 输入点负载 `.env` 当文件存在时,将所有剩余的命令行参数作为服务器命令处理,连接客户端,并确保退出前的清理运行。当 `ANTHROPIC_API_KEY` 未设置或空的,客户端会在列出服务器工具后打印如何设置密钥和退出。此操作没有证书的 MCP 连接 。 ### 向模型描述工具 最后,在 `impl MCPClient` 块 : ``` fn convert_tools(tools: &[McpTool]) -> Vec<ToolDefinition> { tools .iter() .map(|tool| ToolDefinition { name: tool.name.to_string(), description: tool.description.as_deref().map(str::to_string), input_schema: Value::Object(tool.input_schema.as_ref().clone()), }) .collect() } ``` MCP和Messages API描述了不同Rust类型中具有相同信息的工具. `convert_tools` 复制每个 MCP 工具的名称、描述和输入方案 `ToolDefinition`,将它序列化到形状 `tools` 参数预期。当一个工具没有时,此描述会被省略。 ### 校验完整文件 在运行客户端之前, 请确认其中的项目 `src/main.rs` 置于正确的范围: - `new`, `validate_tool_output`, `connect_to_server`, `process_query`, `request_model`, `chat_loop`,以及 `cleanup` 是单项内的方法 `impl MCPClient` 块,在客户端初始化中打开,然后关闭 `cleanup`. - `user` 财务报告和财务报告 `assistant` 属于 `impl Message` 块。 - `block_type`, `main`,以及 `convert_tools` 均为两者外的函数 `impl` 块。 Rust 不要求这些项目以特定的顺序出现, 但方法和自由函数必须置于正确的范围。 将您的文件与 [完成 `src/main.rs` 实例](<https://github.com/modelcontextprotocol/quickstart-resources/blob/main/mcp-client-rust/src/main.rs>),然后检查它是否汇编: ``` cargo fmt --check cargo check ``` ## 运行客户端 使用( U) `cargo run --` 随后您通常用来启动 MCP 服务器的命令 : ``` # Python server cargo run -- python path/to/server.py # Node.js server cargo run -- node path/to/build/index.js # Executable server cargo run -- path/to/server-binary ``` 光着身子跑 `cargo run` 没有服务器命令,则会打印使用中的消息和退出。 如果你继续的话 [从服务器快速启动的天气教程](<https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-rust>),先构建服务器,然后运行类似于 : `cargo run -- ../weather-server-rust/target/debug/weather` 客户将: 1. 启动并连接到指定的 MCP 服务器 2. 打印协议版本和该服务器可用的工具 3. 启动交互聊天会话, 您可以在此进行 : - 输入查询 - 见工具处决 - 得到克劳德的答复 连接到天气服务器会打印一行, 如 : ``` Connected over protocol 2026-07-28 with tools: ["get_alerts", "get_forecast"] ``` 没有 `ANTHROPIC_API_KEY`,客户端在此行后停止并打印如何设置密钥。 ## 如何运作 当用户提交查询时: 1. 客户端向克劳德发送查询和服务器的工具定义 2. 克劳德决定使用哪些工具,如果有的话。 3. 客户端通过 MCP 会话执行每个请求的工具,并根据输出计划验证结构化结果 4. 工具结果,包括以下列标记的失败 `is_error`与克劳德自己的街区一起送回克劳德,没有改变 5. 步骤2通过4重复,直到克劳德回答时没有工具呼叫或 `MAX_TOOL_TURNS` 已到达 6. 收集的文本显示在终端中 ## 最佳做法 1. **处理错误** - 将上下文添加到进程错误中, MCP, 以及模型 API 边界 - 向克劳德发送一个被拒绝的工具呼叫 `tool_result` 与 `is_error` 设定,所以每个 `tool_use` 得到一个答案 - 在不终止交互会话的情况下报告单个查询错误 2. **对话历史** - 进食助手在他们到达时 完全挡住他们 思考障碍和他们的签名 - 每个请求都通过工具列表,让克劳德可以不停地调用工具交叉 - 将每个查询的工具转动次数限制在标签上 3. **资源管理** - 清除时总是取消 MCP 会话 - 即使连接或聊天访问操作失败, 也要确保清理运行 - 在会话活动时避免启动第二个服务器 4. **警卫** - 安全存储 API 密钥 `.env` 或环境 - 对照其申报的产出计划验证结构化工具结果 - 只连接到可信任的服务器和可执行命令 ## 解决问题 ### 服务器命令问题 之后的论据 `cargo run --` 必须形成完整的命令。解释的服务器脚本需要运行时间 : ``` # Correct cargo run -- python ./server/weather.py cargo run -- node ./server/build/index.js # Incorrect: a Python script is not necessarily executable by itself cargo run -- ./server/weather.py ``` 如果找不到命令,请使用命令的绝对路径,或验证命令是否可用。 `PATH`. ### 环境文件问题 那个... `.env` 文件是可选的。丢失时,客户端会读取 `ANTHROPIC_API_KEY` 从环境中。当密钥未设置或为空时,客户端会连接、打印服务器的工具,并带有设置密钥的指令退出。导出密钥,或创建 `.env` 在客户端运行的目录中包含: ``` ANTHROPIC_API_KEY=your-api-key-goes-here ``` ### 工具和反应错误 - `Unable to list tools from server`: 验证服务器成功启动并在 stdio 上进行通信 - `[... failed: ...]` 在输出中: 服务器拒绝了工具调用 。 消息也会以失败方式发送给 Claude `tool_result`,所以克劳德可能会用不同的论据重新尝试 - `Tool ... declares an output schema but returned no structured content` 或 时 间 `Structured content from tool ... does not match its output schema`: 服务器的结果不能满足自身要求 `outputSchema` - `Anthropic request failed with ...`: 反应机构跟踪状态并命名原因, 如无效的密钥或信用值不足 - `[Stopped after 10 tool-use turns]`: 已达查询 `MAX_TOOL_TURNS`。提高需要更多回合的工作流程的常数 ## 今后的步骤 ## 示例服务器 请检查access-date=中的日期值 (帮助) 官方MCP服务器与执行 这页有用吗?
查看原始来源