带LangGraph代理的MCP服务器
在此处阅读完整的媒体文章: 使用模型上下文协议(MCP)构建AI代理:完整指南
📖 概述
该项目展示了 模型上下文协议(MCP) 使用构建的智能代理 LangGraph 和 开放人工智能该系统使人工智能应用程序能够通过标准化协议与外部工具无缝交互。
🧩 什么是MCP(模型上下文协议)?
模型上下文协议(MCP) 是一个开放协议,规范了应用程序如何向大型语言模型(LLM)提供上下文。将其视为一个通用适配器,允许AI应用程序:
- 🔌 连接到外部数据源和工具
- 🛠️ 以标准化的方式执行操作
- 🔄 保持一致的沟通模式
- 🌐 实现跨不同AI系统的工具互操作性
关键概念
- MCP服务器:展示客户可以调用的工具/功能
- MCP客户端:使用MCP服务器上的工具
- JSON-RPC协议:请求/响应模式的通信标准
- 工具:服务器暴露的个人能力(如天气、网络搜索)
______________________________________________________________________
🏗️ 建筑
┌─────────────────────────────────────────────────────────────┐
│ USER INPUT │
│ "What's the weather in Mumbai?" │
└──────────────────────┬──────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ LANGGRAPH AGENT │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Routing │────────▶│ Response │ │
│ │ Node │ │ Node │ │
│ └──────┬───────┘ └──────────────┘ │
│ │ │
│ │ Uses OpenAI to determine: │
│ │ - Which tool to use │
│ │ - Extract parameters │
└─────────┼─────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ MCP CLIENT │
│ - Manages connection to MCP server │
│ - Sends JSON-RPC requests │
│ - Receives and processes responses │
└──────────────────────┬──────────────────────────────────────┘
│
│ JSON-RPC over STDIO
│
▼
┌─────────────────────────────────────────────────────────────┐
│ MCP SERVER │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ get_weather │ │ web_search │ │
│ │ Tool │ │ Tool │ │
│ └──────────────┘ └──────────────┘ │
│ │
│ Built with FastMCP framework │
└──────────────────────┬──────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ EXTERNAL APIs │
│ • wttr.in (Weather API) │
│ • Serper API (Web Search) │
└─────────────────────────────────────────────────────────────┘______________________________________________________________________
🔄 完整的流程说明
1. 系统初始化
# mcp_client.py starts the MCP server as a subprocess
server = subprocess.Popen(
[sys.executable, "mcp_server.py"],
stdin=subprocess.PIPE, # For sending requests
stdout=subprocess.PIPE, # For receiving responses
stderr=subprocess.PIPE, # For server logs
text=True
)发生了什么:
- 客户端将MCP服务器作为子进程生成
- 通过STDIO(标准输入/输出)进行通信
- JSON-RPC消息通过管道流动
2. MCP握手
# Client sends initialization request
send_request("initialize", {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "mcp-client", "version": "1.0.0"}
})
# Client sends initialized notification
send_notification("initialized")发生了什么:
- 客户端和服务器协商协议版本
- 服务器确认可用功能
- 连接已建立并准备好进行工具调用
3. 用户请求处理
步骤3.1:用户输入
User: "What's the weather in Mumbai?"步骤3.2:LangGraph路由节点
路由节点使用 OpenAI gpt-4o-mini 分析请求:
def route_request(state):
# LLM analyzes the user request
# Determines: tool="get_weather", parameters={"city": "Mumbai"}
result = call_mcp_tool("get_weather", {"city": "Mumbai"})
return {"tool_result": result}发生了什么:
- OpenAI分析用户的自然语言
- 确定需要哪个工具
- 从请求中提取参数
- 通往合适工具的路线
步骤3.3:MCP工具调用
# Client sends JSON-RPC request to server
{
"jsonrpc": "2.0",
"id": "1",
"method": "tools/call",
"params": {
"name": "get_weather",
"arguments": {"input": {"city": "Mumbai"}}
}
}发生了什么:
- JSON-RPC标准中的客户端格式请求
- 通过stdin发送到服务器
- 等待stdout上的响应
步骤3.4:MCP服务器执行
@mcp.tool()
def get_weather(input: WeatherInput):
url = f"https://wttr.in/{input.city}?format=j1"
response = requests.get(url)
# Process and return weather data发生了什么:
- 服务器收到工具调用
- 执行
get_weather函数 - 调用外部天气API
- 返回结构化数据
步骤3.5:响应生成
def generate_response(state):
# Uses OpenAI to convert tool data into natural language
# Input: Raw weather data
# Output: "The current weather in Mumbai is 28°C with clear skies..."发生了什么:
- LLM的原始工具数据已格式化
- OpenAI生成自然的对话式响应
- 用户收到友好的回答
______________________________________________________________________
🛠️ 可用工具
1.天气工具(get_weather)
- 目的:获取任何城市的当前天气
- API:wttr.in(免费,不需要API密钥)
- 输入:
{"city": "CityName"} - 输出:温度、条件、湿度、风速
例子:
Input: {"city": "Mumbai"}
Output: {
"location": "Mumbai, India",
"temperature": "28°C / 82°F",
"condition": "Partly cloudy",
"humidity": "70%",
"wind": "15 km/h"
}2.网络搜索工具(web_search)
- 目的:在网上搜索信息
- API:Serper API(需要API密钥)
- 输入:
{"query": "search terms"} - 输出:包含标题、链接和片段的前5个搜索结果
例子:
Input: {"query": "latest news about AI"}
Output: {
"query": "latest news about AI",
"results": [
{
"title": "AI Breakthrough...",
"link": "https://...",
"snippet": "..."
}
]
}______________________________________________________________________
📦 项目结构
mcp-server/
├── mcp_server.py # MCP server implementation (FastMCP)
├── mcp_client.py # MCP client + LangGraph agent
├── mcp-server.ipynb # Jupyter notebook for testing
├── requirements.txt # Python dependencies
├── .env # Environment variables (API keys)
└── README.md # This file文件描述
mcp_server.py
- 使用FastMCP框架实现MCP服务器
- 定义工具
@mcp.tool()装饰器 - 处理JSON-RPC请求
- 与外部API的接口
mcp_client.py
- 生成和管理MCP服务器进程
- 实现JSON-RPC客户端通信
- 使用路由逻辑构建LangGraph代理
- 为智能路由和响应编排OpenAI
requirements.txt
- 列出所有Python依赖项
- 包括MCP、LangGraph、OpenAI和实用程序
______________________________________________________________________
🚀 设置和安装
1.克隆存储库
git clone
cd mcp-server2.安装依赖项
pip install -r requirements.txt3.配置环境变量
创建一个 .env 项目根目录中的文件:
# OpenAI API Key (required)
OPEN_AI_KEY=your_openai_api_key_here
# Serper API Key (required for web search)
SERPER_API_KEY=your_serper_api_key_here
# OpenWeather API Key (optional, using free wttr.in instead)
OPENWEATHER_API_KEY=获取API密钥:
- 开放人工智能: https://platform.openai.com/api-keys
- 搜索: https://serper.dev/(免费版可用)
4.运行系统
python mcp_client.py______________________________________________________________________
💡 工作原理:分步示例
例如:“孟买的天气怎么样?”
步骤1:用户输入
User enters: "What's the weather in Mumbai?"第二步:LangGraph路由
LLM analyzes → Determines tool: get_weather
→ Extracts parameter: city = "Mumbai"步骤3:MCP通信
Client → Server: {
"method": "tools/call",
"params": {"name": "get_weather", "arguments": {"input": {"city": "Mumbai"}}}
}步骤4:服务器执行
Server calls wttr.in API → Gets weather data → Returns JSON response步骤5:生成响应
LLM receives raw data → Generates natural response
Output: "The weather in Mumbai is currently 28°C with partly cloudy skies.
The humidity is at 70% with winds at 15 km/h."______________________________________________________________________
🧪 测试
该系统包括4个测试用例:
tests = [
"What's the weather in Mumbai?", # Uses get_weather
"Tell me about the weather in Delhi", # Uses get_weather
"Search for latest news about AI", # Uses web_search
"What is Model Context Protocol?" # Uses web_search
]期望输出
USER: What's the weather in Mumbai?
🤖 Routing decision: User is asking for weather information
AGENT: The current weather in Mumbai is 28°C (82°F) with partly cloudy
conditions. Humidity is at 70% with winds at 15 km/h.______________________________________________________________________
🔧 关键技术
| 技术 | 目的 |
|---|---|
| FastMCP | 快速构建MCP服务器的框架 |
| LangGraph | 构建有状态、多步骤的LLM应用程序 |
| OpenAI gpt-4o-mini | 智能路由和自然语言生成 |
| JSON-RPC | 客户端-服务器通信协议 |
| 派丹蒂克 | 数据验证和模式定义 |
| 工作室 | 客户端和服务器之间的通信通道 |
______________________________________________________________________
🌟 为什么MCP很重要
传统方法(无MCP)
- 每个工具都需要自定义集成
- 没有标准化
- 难以维护和扩展
- 工具发现是手动的
使用MCP
- ✅ 标准化协议
- ✅ 自动工具发现
- ✅ 易于添加新工具
- ✅ 可跨不同AI系统互操作
- ✅ 明确区分关注点
______________________________________________________________________
🔒 安全考虑
- API密钥:存储在
.env文件,从不提交版本控制 - 输入验证:Pydantic模型验证所有输入
- 错误处理:API故障的优雅错误处理
- 超时:API调用超时以防止挂起
______________________________________________________________________
🚧 扩展系统
添加新工具
- 在中定义工具
mcp_server.py:
class CalculatorInput(BaseModel):
expression: str
@mcp.tool()
def calculate(input: CalculatorInput):
"""Evaluate mathematical expressions"""
try:
result = eval(input.expression) # Use safe_eval in production
return {"result": result}
except Exception as e:
return {"error": str(e)}- 更新中的路由逻辑
mcp_client.py:
# Add to available tools in routing_prompt
# The LLM will automatically learn to use it- 测试一下:
"What is 25 * 4 + 10?" # Should use calculator tool______________________________________________________________________
📊 LangGraph可视化
系统生成代理工作流的可视化表示:
┌─────────┐
│ START │
└────┬────┘
│
▼
┌─────────┐
│ Route │ ← Determines which tool to use
└────┬────┘
│
▼
┌──────────┐
│ Respond │ ← Generates natural language response
└────┬─────┘
│
▼
┌─────────┐
│ END │
└─────────┘另存为 langgraph_diagram.png
______________________________________________________________________
🐛 故障排除
问题:“未配置SERPER_API_KEY”
解决方案:将您的Serper API密钥添加到 .env 文件
问题:天气API超时
解决方案:检查互联网连接;wttr.in可能暂时不可用
问题:OpenAI API错误
解决方案:验证 OPEN_AI_KEY 在 .env 并检查API配额
问题:图形可视化失败
解决方案:安装graphviz: brew install graphviz (macOS)
______________________________________________________________________
📚 资源
- MCP规范: https://spec.modelcontextprotocol.io/
- FastMCP文档: https://github.com/jlowin/fastmcp
- LangGraph文档: https://langchain-ai.github.io/langgraph/
- OpenAI API: https://platform.openai.com/docs
______________________________________________________________________
📄 许可证
这个项目是为了教育目的。请确保您遵守所有使用的外部API的服务条款。
______________________________________________________________________
🤝 贡献
欢迎投稿!需要改进的地方:
- 添加更多工具(数据库查询、文件操作等)
- 实现HTTP传输(除了STDIO)
- 添加身份验证和授权
- 实施工具组合(链接多个工具)
- 添加对话记忆和上下文
______________________________________________________________________
📧 联系
如有疑问或反馈,请在存储库中打开问题。
______________________________________________________________________
由以下材料制成❤️ 使用MCP、LangGraph和OpenAI
