🤖 MCP聊天机器人客户端
将Claude AI连接到无限MCP服务器
一个生产就绪的Python聊天机器人,利用 模型上下文协议 以动态地发现和使用来自任何MCP兼容服务器的工具。
   
______________________________________________________________________
🎯 MCP解决的问题
MCP之前:M×N积分问题
graph TB
subgraph "5 AI Applications"
A1[Claude Desktop]
A2[VSCode]
A3[Cursor]
A4[Windsurf]
A5[Custom App]
end
subgraph "10 Tools"
T1[GitHub]
T2[Slack]
T3[Database]
T4[FileSystem]
T5[Web Search]
T6[Email]
T7[Calendar]
T8[CRM]
T9[Analytics]
T10[Cloud Storage]
end
A1 -.Custom Integration.-> T1
A1 -.Custom Integration.-> T2
A1 -.Custom Integration.-> T3
A2 -.Custom Integration.-> T1
A2 -.Custom Integration.-> T4
A3 -.Custom Integration.-> T5
style A1 fill:#e1f5fe
style A2 fill:#e1f5fe
style A3 fill:#e1f5fe
style T1 fill:#f3e5f5
style T2 fill:#f3e5f5
style T3 fill:#f3e5f5
Note1[5 Apps × 10 Tools = 50 integrations 😱]
style Note1 fill:#ffebee,stroke:#c62828,stroke-width:2px使用MCP:M+N解决方案
graph LR
subgraph "AI Applications"
A1[Claude Desktop]
A2[VSCode]
A3[Cursor]
A4[Custom App]
end
subgraph "MCP Protocol"
MCP[Model Context Protocol]
end
subgraph "MCP Servers"
S1[GitHub Server]
S2[Slack Server]
S3[FileSystem Server]
S4[Web Search Server]
end
A1 --> MCP
A2 --> MCP
A3 --> MCP
A4 --> MCP
MCP --> S1
MCP --> S2
MCP --> S3
MCP --> S4
style MCP fill:#4caf50,stroke:#2e7d32,stroke-width:3px,color:#fff
style A1 fill:#e1f5fe
style A2 fill:#e1f5fe
style A3 fill:#e1f5fe
style A4 fill:#e1f5fe
style S1 fill:#f3e5f5
style S2 fill:#f3e5f5
style S3 fill:#f3e5f5
style S4 fill:#f3e5f5
Note2[4 Apps + 4 Servers = 8 integrations 🎉]
style Note2 fill:#e8f5e9,stroke:#2e7d32,stroke-width:2pxMCP就像AI的USB -使AI集成即插即用的通用标准!
______________________________________________________________________
✨ 特性
🔌 多服务器架构
通过动态发现同时连接到无限MCP服务器
🎯 零配置
通过JSON配置添加新服务器-无需更改代码
🤖 克劳德AI供电
利用Anthropic的最新模型和工具调用
⚡ AsyncExitStack模式
用于生产的可扩展异步架构
🛡️ 坚固耐用
单个服务器故障不会导致应用程序崩溃
🔒 设计安全
环境变量、沙盒文件访问、API密钥保护
______________________________________________________________________
🏗️ 建筑
系统概述
flowchart TB
User([👤 User])
subgraph ChatBot["🤖 MCP Chatbot Client"]
Config[📋 Load server_config.json]
Launch[🚀 Launch MCP Servers]
Discover[🔍 Discover Tools]
Chat[💬 Interactive Chat Loop]
Config --> Launch
Launch --> Discover
Discover --> Chat
end
subgraph Servers["MCP Servers (Subprocesses)"]
FS[📁 Filesystem Server
Node.js via npx]
Fetch[🌐 Fetch Server
Python via uvx]
Custom[🔧 Custom Servers
Your tools]
end
subgraph Claude["🧠 Claude AI"]
API[Anthropic API
claude-sonnet-4]
end
User |Natural Language| Chat
Chat |Messages + Tools| API
Chat -->|Tool Calls| FS
Chat -->|Tool Calls| Fetch
Chat -->|Tool Calls| Custom
FS -->|Results| Chat
Fetch -->|Results| Chat
Custom -->|Results| Chat
style ChatBot fill:#e3f2fd,stroke:#1976d2,stroke-width:2px
style Servers fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
style Claude fill:#fff3e0,stroke:#f57c00,stroke-width:2px
style User fill:#e8f5e9,stroke:#388e3c,stroke-width:2px对话流程
sequenceDiagram
participant User
participant Chatbot
participant Claude
participant MCPServer as MCP Server
(filesystem)
User->>Chatbot: "Read the README.md file"
Chatbot->>Claude: Send message + available tools
Note over Claude: Analyzes request
Decides to use read_file
Claude->>Chatbot: Tool call: read_file(path="README.md")
Chatbot->>MCPServer: Execute: read_file
Note over MCPServer: Reads file from disk
MCPServer->>Chatbot: File content
Chatbot->>Claude: Tool result + content
Note over Claude: Processes result
Generates response
Claude->>Chatbot: Final response
Chatbot->>User: "I've read your README..."
rect rgb(200, 255, 200)
Note over User,MCPServer: ✅ Complete conversation with tool usage
end______________________________________________________________________
🚀 快速开始
先决条件
安装
# Clone the repository
git clone https://github.com/yourusername/mcp-chatbot-client.git
cd mcp-chatbot-client
# Install dependencies
uv sync
# Configure API key
echo "ANTHROPIC_API_KEY=your_api_key_here" > .env
# Run!
uv run python main.py首次运行输出
🚀 Setting up MCP Chatbot...
==================================================
✅ Loaded configuration from server_config.json
📋 Found 2 server(s)
🔌 Connecting to 'filesystem' server...
✅ Connected to 'filesystem' with 3 tool(s)
🔌 Connecting to 'fetch' server...
✅ Connected to 'fetch' with 1 tool(s)
==================================================
✅ Setup complete! 4 total tools available
==================================================
🤖 MCP Chatbot Ready!
You: _______________________________________________________________________
💬 用法
交互式命令
| 命令 | 描述 |
|---|---|
tools | 查看连接服务器上的所有可用工具 |
quit 或 exit | 优雅地退出聊天机器人 |
| `` | 使用MCP工具与Claude聊天 |
对话示例
📖 读取文件
You: Read the README.md file
🔧 Calling tool 'read_file' with args: {'path': 'README.md'}
✅ Tool executed
Claude: I've read your README.md file. It describes an MCP chatbot
client that connects Claude AI to external MCP servers...🌐 获取Web内容
You: Fetch https://www.anthropic.com and summarize the content
🔧 Calling tool 'fetch' with args: {'url': 'https://www.anthropic.com'}
✅ Tool executed
Claude: Anthropic is an AI safety company. Their website describes their
mission to build reliable, interpretable, and steerable AI systems...📝 多步操作
You: List all Python files in this directory, then create a summary document
🔧 Calling tool 'list_directory' with args: {'path': '.'}
✅ Tool executed
🔧 Calling tool 'write_file' with args: {'path': 'summary.txt', ...}
✅ Tool executed
Claude: I've analyzed the directory and created summary.txt with details
about all 3 Python files found...______________________________________________________________________
⚙️ 配置
服务器配置文件
创建 server_config.json 在项目根目录中:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
"env": {}
},
"fetch": {
"command": "uvx",
"args": ["--quiet", "mcp-server-fetch"],
"env": {}
}
}
}配置架构
graph TD
Config[server_config.json]
Config --> Servers[mcpServers Object]
Servers --> Server1[Server 1
e.g., 'filesystem']
Servers --> Server2[Server 2
e.g., 'fetch']
Servers --> ServerN[Server N
e.g., 'custom']
Server1 --> Cmd1[command: string]
Server1 --> Args1[args: array]
Server1 --> Env1[env: object
optional]
style Config fill:#fff3e0,stroke:#f57c00,stroke-width:3px
style Servers fill:#e1f5fe,stroke:#0277bd,stroke-width:2px
style Server1 fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
style Server2 fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
style ServerN fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px添加更多服务器
只需更新JSON,无需更改代码!
{
"mcpServers": {
"filesystem": {...},
"fetch": {...},
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "your_api_key"
}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "your_token"
}
}
}
}可用的MCP服务器
探索 MCP服务器注册表:
| 服务器 | 描述 | 提供者 |
|---|---|---|
| 📁 文件系统 | 文件操作(读、写、列表) | 人为 |
| 🌐 获取 | 网络内容为降价 | 拟人化 |
| 🔍 勇敢的搜寻 | 网络搜索 | 人类学 |
| 🐙 GitHub | 存储库管理 | Anthropic |
| 📊 SQLite | 数据库查询 | Anthropic |
| 💬 松弛 | 团队沟通 | 社区 |
| 🐘 Postgres | PostgreSQL访问 | 社区 |
______________________________________________________________________
🎨 关键设计模式
AsyncExitStack模式
问题: 无法在嵌套的循环中动态管理异步上下文 async with 阻碍。
解决方案:
graph LR
subgraph "Traditional Nested (❌ Doesn't Scale)"
N1[async with server1:]
N2[async with server2:]
N3[async with server3:]
N1 --> N2
N2 --> N3
N3 --> Loop1[chat_loop]
Note1[Nesting depth = # of servers]
style N1 fill:#ffebee
style N2 fill:#ffebee
style N3 fill:#ffebee
style Note1 fill:#ffebee,stroke:#c62828
end
subgraph "AsyncExitStack (✅ Scalable)"
S1[async with AsyncExitStack]
S2[for server in servers:
stack.enter_async_context]
S1 --> S2
S2 --> Loop2[chat_loop]
Note2[Constant depth = 2
Unlimited servers!]
style S1 fill:#e8f5e9
style S2 fill:#e8f5e9
style Loop2 fill:#e8f5e9
style Note2 fill:#e8f5e9,stroke:#2e7d32
end实施:
async def connect_to_servers_and_run(self):
async with AsyncExitStack() as stack:
# Dynamically add unlimited servers
for server_name, config in servers.items():
read, write = await stack.enter_async_context(
stdio_client(server_params)
)
session = await stack.enter_async_context(
ClientSession(read, write)
)
# All contexts stay alive!
# Run chat with all servers connected
await self.chat_loop()______________________________________________________________________
💰 成本优化
模型比较
graph TB
subgraph Models["Claude Models"]
Haiku[⚡ Haiku 4.5
$1 / $5 per MTok
Fast & Cheap]
Sonnet[🚀 Sonnet 4.5
$3 / $15 per MTok
Balanced]
Opus[🎯 Opus 4
$15 / $75 per MTok
Premium]
end
subgraph Usage["Use Cases"]
Dev[🧪 Testing &
Development]
Prod[🏭 Production
Applications]
Premium[💎 Critical
Tasks]
end
Haiku -.->|Recommended| Dev
Sonnet -.->|Recommended| Prod
Opus -.->|Recommended| Premium
style Haiku fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
style Sonnet fill:#e3f2fd,stroke:#1976d2,stroke-width:2px
style Opus fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
Note[💡 Haiku is 67% cheaper than Sonnet!]
style Note fill:#fff3e0,stroke:#f57c00,stroke-width:2px切换模型
在 chatbot.py,更新模型参数(出现在2个位置):
# For testing (cheaper):
model='claude-haiku-4-5-20251001'
# For production (better quality):
model='claude-sonnet-4-20250514'成本节约示例:
- 使用Haiku进行1000次查询:约10美元
- 使用Sonnet进行1000次查询:约30美元
- 节省:20美元(便宜67%!)
______________________________________________________________________
📁 项目结构
mcp-chatbot-client/
│
├── 📄 chatbot.py # Core MCP chatbot implementation
├── 📄 main.py # Application entry point
│
├── ⚙️ server_config.json # MCP server configuration
├── 🔐 .env # API keys (gitignored)
│
├── 📋 pyproject.toml # Python dependencies
├── 🔒 uv.lock # Locked dependency versions
│
├── 📖 README.md # This file
└── 📘 GUIDE.md # Detailed learning guide______________________________________________________________________
🧪 发展
测试单个服务器
# Test filesystem server
npx -y @modelcontextprotocol/server-filesystem .
# Test fetch server
uvx --quiet mcp-server-fetch构建自定义MCP服务器
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("my-custom-server")
@mcp.tool()
def process_text(text: str) -> str:
"""Process text and return result"""
return f"Processed: {text.upper()}"
if __name__ == "__main__":
mcp.run()添加到配置:
{
"my-server": {
"command": "uv",
"args": ["run", "my_server.py"]
}
}______________________________________________________________________
🐛 故障排除
常见问题
❌ "ANTHROPIC_API_KEY not found"
解决方案:
# Create .env file with your key
echo "ANTHROPIC_API_KEY=sk-ant-..." > .env
# Verify it's not tracked by git
git status # .env should not appear❌ "npx: command not found"
解决方案:
# Ubuntu/Debian
sudo apt install nodejs npm
# macOS
brew install node
# Windows
# Download from nodejs.org❌ "Failed to parse JSONRPC message"
解决方案: 添加 --quiet 用于抑制npm输出的标志:
{
"fetch": {
"command": "uvx",
"args": ["--quiet", "mcp-server-fetch"]
}
}______________________________________________________________________
🤝 贡献
我们欢迎捐款!以下是如何参与其中:
graph LR
A[🍴 Fork Repo] --> B[🌿 Create Branch]
B --> C[💻 Make Changes]
C --> D[✅ Test Changes]
D --> E[📝 Commit]
E --> F[⬆️ Push]
F --> G[🔄 Open PR]
style A fill:#e8f5e9,stroke:#2e7d32
style B fill:#e3f2fd,stroke:#1976d2
style C fill:#fff3e0,stroke:#f57c00
style D fill:#f3e5f5,stroke:#7b1fa2
style E fill:#fce4ec,stroke:#c2185b
style F fill:#e0f2f1,stroke:#00897b
style G fill:#e8eaf6,stroke:#3949ab贡献方式
- 🐛 报告Bug -公开详细问题
- 💡 建议功能 -分享你的想法
- 📖 改进文档 -帮助他人学习
- 🔧 提交拉取请求 -修复错误,添加功能
- ⭐ 为存储库添加星号 -表示支持
代码指南
- 跟随 PEP 8 风格指南
- 添加 类型提示 功能
- 包含 文档字符串 对于类和方法
- 写 清除提交消息
- 添加 测试 对于新功能
______________________________________________________________________
📚 资源
官方文件
学习资源
- 🎓 深度学习。人工智能课程 -完成MCP课程
- 📖 MCP快速入门 -快速开始
- 💬 社区论坛 -提问
______________________________________________________________________
🎓 你将学到什么
mindmap
root((MCP Chatbot
Client))
MCP Protocol
Client Architecture
Server Communication
Tool Discovery
JSON-RPC 2.0
Python Async
AsyncExitStack
Context Managers
Concurrent Operations
AI Integration
Claude API
Tool Calling
Conversation Management
Production Skills
Error Handling
Configuration Management
Security Best Practices
Scalable Design______________________________________________________________________
📊 项目统计
| 度量 | 值 |
|---|---|
| 代码行 | ~200 |
| 依赖项 | 4个核心包 |
| 支持的服务器 | 无限制♾️ |
| 工具发现 | 自动🤖 |
| 设置时间 | \<5分钟⚡ |
| 可扩展性 | 生产就绪🚀 |
______________________________________________________________________
📝 许可证
该项目根据 MIT许可证 -看看 许可证 文件以获取详细信息。
______________________________________________________________________
🙏 致谢
______________________________________________________________________
🌟 星迹
如果这个项目对你有帮助,请主演! ⭐
它帮助其他人发现项目并激励持续开发。

______________________________________________________________________
📬 支持与联系
| 频道 | 链接 |
|---|---|
| 🐛 问题 | |
| 💬 讨论 | |
| 📧 电子邮件 | jorgegoco70@gmail.com |
| 🎓 课程 | MCP:用Anthropic构建丰富的上下文AI应用程序 |
______________________________________________________________________
内置于❤️ 使用模型上下文协议
MCP是用于AI的USB-一种协议,无限可能
