在本教程中,您将学习如何构建一个由 LLM 驱动的聊天机器人客户端,并将其连接到 MCP 服务器。建议您先完成服务器快速入门,该指南将引导您了解构建第一个服务器的基础知识。
您可以在这里找到本教程的完整代码。

系统要求

开始之前,请确保您的系统满足以下要求
  • Mac 或 Windows 计算机
  • 已安装最新 Python 版本
  • 已安装最新版本的 uv

设置您的环境

首先,使用 uv 创建一个新的 Python 项目
# Create project directory
uv init mcp-client
cd mcp-client

# Create virtual environment
uv venv

# Activate virtual environment
# On Windows:
.venv\Scripts\activate
# On Unix or macOS:
source .venv/bin/activate

# Install required packages
uv add mcp anthropic python-dotenv

# Remove boilerplate files
# On Windows:
del main.py
# On Unix or macOS:
rm main.py

# Create our main file
touch client.py

设置您的 API 密钥

您需要从 Anthropic 控制台获取一个 Anthropic API 密钥。创建一个 .env 文件来存储它:
# Create .env file
touch .env
将您的密钥添加到 .env 文件中
ANTHROPIC_API_KEY=<your key here>
.env 添加到您的 .gitignore
echo ".env" >> .gitignore
请确保您的 ANTHROPIC_API_KEY 安全!

创建客户端

基本客户端结构

首先,让我们设置导入并创建基本的客户端类
import asyncio
from typing import Optional
from contextlib import AsyncExitStack

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

from anthropic import Anthropic
from dotenv import load_dotenv

load_dotenv()  # load environment variables from .env

class MCPClient:
    def __init__(self):
        # Initialize session and client objects
        self.session: Optional[ClientSession] = None
        self.exit_stack = AsyncExitStack()
        self.anthropic = Anthropic()
    # methods will go here

服务器连接管理

接下来,我们将实现连接到 MCP 服务器的方法
async def connect_to_server(self, server_script_path: str):
    """Connect to an MCP server

    Args:
        server_script_path: Path to the server script (.py or .js)
    """
    is_python = server_script_path.endswith('.py')
    is_js = server_script_path.endswith('.js')
    if not (is_python or is_js):
        raise ValueError("Server script must be a .py or .js file")

    command = "python" if is_python else "node"
    server_params = StdioServerParameters(
        command=command,
        args=[server_script_path],
        env=None
    )

    stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
    self.stdio, self.write = stdio_transport
    self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))

    await self.session.initialize()

    # List available tools
    response = await self.session.list_tools()
    tools = response.tools
    print("\nConnected to server with tools:", [tool.name for tool in tools])

查询处理逻辑

现在让我们添加处理查询和工具调用的核心功能
async def process_query(self, query: str) -> str:
    """Process a query using Claude and available tools"""
    messages = [
        {
            "role": "user",
            "content": query
        }
    ]

    response = await self.session.list_tools()
    available_tools = [{
        "name": tool.name,
        "description": tool.description,
        "input_schema": tool.inputSchema
    } for tool in response.tools]

    # Initial Claude API call
    response = self.anthropic.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=1000,
        messages=messages,
        tools=available_tools
    )

    # Process response and handle tool calls
    final_text = []

    assistant_message_content = []
    for content in response.content:
        if content.type == 'text':
            final_text.append(content.text)
            assistant_message_content.append(content)
        elif content.type == 'tool_use':
            tool_name = content.name
            tool_args = content.input

            # Execute tool call
            result = await self.session.call_tool(tool_name, tool_args)
            final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")

            assistant_message_content.append(content)
            messages.append({
                "role": "assistant",
                "content": assistant_message_content
            })
            messages.append({
                "role": "user",
                "content": [
                    {
                        "type": "tool_result",
                        "tool_use_id": content.id,
                        "content": result.content
                    }
                ]
            })

            # Get next response from Claude
            response = self.anthropic.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=1000,
                messages=messages,
                tools=available_tools
            )

            final_text.append(response.content[0].text)

    return "\n".join(final_text)

交互式聊天界面

现在我们将添加聊天循环和清理功能
async def chat_loop(self):
    """Run an interactive chat loop"""
    print("\nMCP Client Started!")
    print("Type your queries or 'quit' to exit.")

    while True:
        try:
            query = input("\nQuery: ").strip()

            if query.lower() == 'quit':
                break

            response = await self.process_query(query)
            print("\n" + response)

        except Exception as e:
            print(f"\nError: {str(e)}")

async def cleanup(self):
    """Clean up resources"""
    await self.exit_stack.aclose()

主入口点

最后,我们将添加主执行逻辑
async def main():
    if len(sys.argv) < 2:
        print("Usage: python client.py <path_to_server_script>")
        sys.exit(1)

    client = MCPClient()
    try:
        await client.connect_to_server(sys.argv[1])
        await client.chat_loop()
    finally:
        await client.cleanup()

if __name__ == "__main__":
    import sys
    asyncio.run(main())
您可以在这里找到完整的 client.py 文件。

关键组件说明

1. 客户端初始化

  • MCPClient 类通过会话管理和 API 客户端进行初始化
  • 使用 AsyncExitStack 进行适当的资源管理
  • 配置 Anthropic 客户端以进行 Claude 交互

2. 服务器连接

  • 支持 Python 和 Node.js 服务器
  • 验证服务器脚本类型
  • 设置适当的通信渠道
  • 初始化会话并列出可用工具

3. 查询处理

  • 维护对话上下文
  • 处理 Claude 的响应和工具调用
  • 管理 Claude 与工具之间的消息流
  • 将结果整合成连贯的响应

4. 交互式界面

  • 提供简单的命令行界面
  • 处理用户输入并显示响应
  • 包含基本的错误处理
  • 允许优雅退出

5. 资源管理

  • 妥善清理资源
  • 处理连接问题的错误
  • 优雅的关闭程序

常见自定义点

  1. 工具处理
    • 修改 process_query() 以处理特定工具类型
    • 为工具调用添加自定义错误处理
    • 实现特定于工具的响应格式化
  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
如果您正在继续服务器快速入门中的天气教程,您的命令可能类似于这样:python client.py .../quickstart-resources/weather-server-python/weather.py
客户端将
  1. 连接到指定的服务器
  2. 列出可用的工具
  3. 启动一个交互式聊天会话,您可以在其中
    • 输入查询
    • 查看工具执行情况
    • 获取来自 Claude 的响应
如果连接到服务器快速入门中的天气服务器,它应该看起来像这样

工作原理

当您提交查询时
  1. 客户端从服务器获取可用工具列表
  2. 您的查询连同工具描述一起发送给 Claude
  3. Claude 决定使用哪些工具(如果有的话)
  4. 客户端通过服务器执行任何请求的工具调用
  5. 结果被发送回 Claude
  6. Claude 提供自然语言响应
  7. 响应将显示给您

最佳实践

  1. 错误处理
    • 始终将工具调用包装在 try-catch 块中
    • 提供有意义的错误消息
    • 优雅地处理连接问题
  2. 资源管理
    • 使用 AsyncExitStack 进行妥善清理
    • 完成后关闭连接
    • 处理服务器断开连接的情况
  3. 安全
    • 将 API 密钥安全地存储在 .env
    • 验证服务器响应
    • 谨慎对待工具权限

故障排除

服务器路径问题

  • 仔细检查您的服务器脚本路径是否正确
  • 如果相对路径无效,请使用绝对路径
  • 对于 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: 检查您的服务器路径
  • Connection refused: 确保服务器正在运行且路径正确
  • Tool execution failed: 验证工具所需的环境变量是否已设置
  • Timeout error: 考虑在您的客户端配置中增加超时时间

后续步骤