在本教程中,您将学习如何构建一个连接到MCP服务器的基于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 Console的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. 用户界面
    • 添加一个图形用户界面或网页界面
    • 实现丰富的控制台输出
    • 添加命令历史或自动补全

运行客户端

使用任何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 用户请确保在路径中使用正斜杠(/)或转义反斜杠(\)
  • 检查服务器文件具有正确的文件扩展名(.py 适合 Python 或 .js 适合 Node.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: Check your server path
  • Connection refused: 确保服务器正在运行且路径正确
  • 工具执行失败: 验证工具所需的环境变量是否已设置
  • 超时错误:考虑在您的客户端配置中增加超时时间

后续步骤