多服务器MCP架构
一个演示项目,展示如何使用LangChain和谷歌的Gemini AI模型创建和使用多个模型上下文协议(MCP)服务器。该项目实现了两个MCP服务器——一个用于算术运算的数学服务器和一个用于基于位置的天气查询的天气服务器。
概述
该项目展示了:
- 使用FastMCP创建MCP服务器
- 将多个MCP服务器连接到单个客户端
- 使用不同的传输协议(stdio和HTTP)
- 将MCP工具与LangChain代理集成
- 利用谷歌的Gemini 2.0 Flash模型进行人工智能响应
建筑
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ client.py │ │ mathserver.py │ │ weatherserver.py│
│ │ │ │ │ │
│ ┌─────────────┐ │ │ ┌──────────────┐ │ │ ┌─────────────┐ │
│ │ LangChain │ │ │ │ FastMCP │ │ │ │ FastMCP │ │
│ │ Agent │ │ │ │ Math Tools │ │ │ │ Weather API │ │
│ │ │◄┼────┼►│ - add() │ │ │ │ - get_weather│ │
│ │ Gemini 2.0 │ │ │ │ - multiply() │ │ │ │ │ │
│ │ Flash │ │ │ └──────────────┘ │ │ └─────────────┘ │
│ └─────────────┘ │ │ │ │ │
└─────────────────┘ │ Transport: stdio │ │ Transport: HTTP │
└──────────────────┘ └─────────────────┘先决条件
- Python 3.8+
- Gemini的Google API密钥
- 必需的Python包(请参阅安装)
安装
- 克隆存储库:
git clone https://github.com/naakaarafr/Multi-Server-MCP-Architecture.git
cd Multi-Server-MCP-Architecture- 安装所需的软件包:
pip install langchain-mcp-adapters langgraph langchain-google-genai python-dotenv mcp- 设置环境变量:
创建一个 .env 项目根目录中的文件:
GOOGLE_API_KEY=your_google_api_key_here获取Google API密钥:
- 访问 谷歌人工智能工作室
- 创建新的API密钥
- 将密钥复制到您的
.env文件
项目结构
Multi-Server-MCP-Architecture/
│
├── client.py # Main client that connects to MCP servers
├── mathserver.py # MCP server for math operations
├── weatherserver.py # MCP server for weather queries
├── .env # Environment variables (Google API key)
├── LICENSE # MIT License
└── README.md # This file文件描述
客户端.py
主要客户端应用程序:
- 配置并连接到多个MCP服务器
- 使用Gemini 2.0 Flash设置LangChain代理
- 通过示例查询演示工具用法
- 处理每台服务器的不同传输协议
数学服务器.py
提供数学运算的简单MCP服务器:
add(a, b):将两个整数相加multiply(a, b):将两个整数相乘- 使用stdio传输进行通信
weatherserver.py
模拟天气MCP服务器:
get_weather(location):返回某个位置的天气信息- 使用HTTP传输进行通信
- 返回用于演示的模拟响应
用法
启动服务器
数学服务器(stdio传输)由客户端自动启动。对于天气服务器,您有两个选项:
选项1:让客户处理 (如果使用兼容的MCP客户端): 客户端将尝试自动启动天气服务器。
选项2:手动启动 (推荐):
# In a separate terminal
python weatherserver.py运行客户端
python client.py客户将:
- 连接到两个MCP服务器
- 执行一个数学查询:“什么是(3+5)x 12?”
- 执行一个天气查询:“加利福尼亚州的天气怎么样?”
- 显示结果
期望输出
Math response: To calculate (3 + 5) x 12, I need to first add 3 and 5, then multiply by 12.
First: 3 + 5 = 8
Then: 8 × 12 = 96
Therefore, (3 + 5) x 12 = 96
Weather response: According to the weather service, it's always raining in California.传输协议
本项目演示了两种MCP传输协议:
STDIO传输(mathserver.py)
- 通过标准输入/输出进行通信
- 适用于本地基于流程的服务器
- 由客户端自动管理
HTTP传输(weatherserver.py)
- 通过HTTP请求进行通信
- 适用于基于网络的服务器
- 需要手动启动服务器或进行服务管理
定制
添加新的数学运算
要向数学服务器添加新的数学运算,请执行以下操作:
@mcp.tool()
def subtract(a: int, b: int) -> int:
"""Subtract b from a"""
return a - b
@mcp.tool()
def divide(a: float, b: float) -> float:
"""Divide a by b"""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b创建真实天气集成
用真正的API替换mock weather函数:
import requests
@mcp.tool()
async def get_weather(location: str) -> str:
"""Get real weather data for a location"""
api_key = "your_weather_api_key"
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}"
response = requests.get(url)
data = response.json()
if response.status_code == 200:
temp = data['main']['temp'] - 273.15 # Convert from Kelvin to Celsius
description = data['weather'][0]['description']
return f"Weather in {location}: {temp:.1f}°C, {description}"
else:
return f"Could not get weather for {location}"添加更多服务器
要添加其他MCP服务器,请更新客户端配置:
client = MultiServerMCPClient({
"math": {
"command": "python",
"args": ["mathserver.py"],
"transport": "stdio",
},
"weather": {
"url": "http://localhost:8000/mcp",
"transport": "streamable_http",
},
"newserver": {
"command": "python",
"args": ["newserver.py"],
"transport": "stdio",
}
})故障排除
常见问题
- Google API密钥错误:
- 确保您的 .env 文件包含有效 GOOGLE_API_KEY - 检查API密钥是否具有必要的权限
- 气象服务器连接失败:
- 确保天气服务器正在运行 http://localhost:8000/mcp - 检查端口冲突
- 未找到数学服务器:
- 确保 mathserver.py 与位于同一目录中 client.py - 检查文件权限
- 模块导入错误:
- 验证是否安装了所有必需的软件包 - 检查Python版本兼容性
调试模式
要启用更详细的日志记录,请将以下内容添加到您的客户端:
import logging
logging.basicConfig(level=logging.DEBUG)贡献
为该项目做出贡献:
- 分叉存储库
- 创建要素分支
- 添加您的改进
- 彻底测试
- 提交拉取请求
许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
仓库
github:
资源
后续步骤
考虑通过以下方式扩展此项目:
- 向服务器添加身份验证
- 实现错误处理和重试逻辑
- 为客户端创建web界面
- 添加更复杂的工具和服务器
- 实施服务器健康检查和监控
