丹妮·查因-202107582
EECE798S-作业5
配备OpenAI代理SDK的MCP地图服务器
使用OpenAI代理SDK实现三个模型上下文协议(MCP)服务器,提供地图、旅行分析和天气/环境服务。
______________________________________________________________________
🎯 项目概述
该项目实施 三台MCP服务器 随着 总共11次操作 作为代理工具:
| 服务器 | 操作 | 描述 |
|---|---|---|
| 核心地图服务器 | 5 | 实时地理编码、POI搜索、路由 |
| 历史地图服务器 | 3 | 历史出行模式分析 |
| 天气与环境服务器 | 3 | 天气、空气质量、天文数据 |
______________________________________________________________________
🚀 快速开始
1.安装(3分钟)
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
# Configure OpenAI API key
cp .env.example .env
# Edit .env and add: OPENAI_API_KEY=sk-your-key-here注: 设置 verbose 参数在 agent.py 将“True”设置为“True”,以便打印代理在应答前进行的工具调用。
2.运行项目
交互式代理(带示例查询):
python agent.py运行测试:
pytest tests/ -v______________________________________________________________________
🎯 MCP架构
此实现遵循模型上下文协议约定:
- 服务器参数 -每台服务器的配置
- 异步操作 -所有I/O都是非阻塞的
- 结构化响应 -一致性
{success, ...}格式 - 工具定义 -OpenAI函数调用模式
- 资源管理 -适当清理
close()
刀具流
User Query
↓
OpenAI Agent (decides which tools to use)
↓
Tool Execution (agent_tools.py routes to server)
↓
MCP Server Method (performs operation)
↓
External API Call
↓
Structured Response
↓
Agent Formats Response for User______________________________________________________________________
📚 服务器详细信息
核心地图服务器(servers/core_map_server.py)
使用OpenStreetMap API进行实时映射。
操作:
geocode(query)-从地址获取坐标reverse_geocode(lat, lon)-从坐标中获取地址search_poi(lat, lon, radius, category, key)-查找附近的地点get_place_details(place_id)-详细的地点信息get_route(origin_lat, origin_lon, dest_lat, dest_lon, mode)-计算路线
外部API: 提名、OSRM、天桥
历史地图服务器(servers/history_map_server.py)
使用历史旅行数据进行旅行模式分析。
操作:
get_frequent_places(start_date, end_date, min_visits)-访问量最大的地点summarize_travel_stats(start_date, end_date)-旅行统计汇总get_typical_route(origin_label, dest_label, time_of_day)-路线模式
数据: 使用中发现的100个生成的行程 data/trip_history.json
天气与环境服务器(servers/weather_environment_server.py)
任何地点的天气和环境数据。
操作:
get_current_weather(lat, lon, include_forecast)-温度、条件、风get_air_quality(lat, lon)-空气质量指数、污染物、健康建议get_astronomy_data(lat, lon, date)-日出、日落、月相
外部API: 开放天气
______________________________________________________________________
💡 示例用法
python agent.py
💬 You: What's the weather in Paris?
🤖 Agent: [Uses geocode + get_current_weather tools]
💬 You: Find coffee shops near Times Square
🤖 Agent: [Uses geocode + search_poi tools]
💬 You: How's the air quality in Beijing?
🤖 Agent: [Uses geocode + get_air_quality tools]
💬 You: Route from Central Park to Brooklyn Bridge by walking
🤖 Agent: [Uses geocode + get_route tools]
💬 You: What are my travel statistics?
🤖 Agent: [Uses summarize_travel_stats tool]______________________________________________________________________
🗂️ 项目结构
mcp-map-servers/
├── agent.py # Main interactive agent
├── agent_tools.py # Tool definitions & routing
├── agent_prompt.txt # The agent prompt
├── servers/
│ ├── core_map_server.py # Geocoding, POI, routing
│ ├── history_map_server.py # Travel pattern analysis
│ └── weather_map_server.py # Weather & environment
├── tests/
│ └── test_servers.py # Unit tests
├── data/
│ └── trip_history.json # Generated data
├── requirements.txt
├── .env.example
└── README.md # This file
└── REFLECTION.md # Lessons learned and potential next steps
└── SUMMARY.md # Summary of the huggingface MCP article and existing map servers
└── Screencast.mp4 # Video showcasing examples and explaining implementation______________________________________________________________________
🧪 测试
运行所有测试:
pytest tests/ -v运行特定测试:
pytest tests/test_servers.py::TestCoreMapServer::test_geocode_success -v测试包括:
- 所有11个服务器操作
- 成功和错误案例
- 真正的API集成
- 数据结构验证
______________________________________________________________________
⚙️ 配置
环境变量(.env)
OPENAI_API_KEY=sk-your-key-here
API_RATE_LIMIT_DELAY=1.0
OPENAI_MODEL="gpt-4o"服务器参数
每台服务器使用 ServerParams 用于配置的数据类:
@dataclass
class ServerParams:
name: str = "server_name"
description: str = "Server description"
base_url: str = "https://api.example.com"
rate_limit_delay: float = float(os.getenv("API_RATE_LIMIT_DELAY"))______________________________________________________________________
🌐 外部API
| API | 用途 | 所需密钥 | 费率限制 |
|---|---|---|---|
| 提名 | 地理编码 | 否 | 1个要求/秒 |
| OSRM | 路由 | 否 | 合理使用 |
| 天桥 | POI搜索 | 否 | 合理使用 |
| Open Meteo | 天气与空气质量 | 否 | 合理使用 |
所有API都是 自由 和 无需身份验证.
______________________________________________________________________
🔐 错误处理
所有操作都返回一致的结构:
成功:
{
"success": True,
"data": "...",
# ... other fields
}失败:
{
"success": False,
"error": "Descriptive error message"
}这允许代理人:
- 检查操作是否成功
- 适当提取数据或报告错误
- 优雅地处理失败
______________________________________________________________________
🚧 扩展系统
向现有服务器添加新工具
- 在中向服务器类添加方法
servers/ - 将工具定义添加到
TOOLS在agent_tools.py - 将路由案例添加到
execute_tool()在agent_tools.py - 可选:在中编写测试
tests/test_servers.py
创建新服务器
- 创建
servers/new_server.py随着ServerParams服务器类 - 导入并初始化
agent_tools.py - 将工具定义添加到
TOOLS列表 - 将路由案例添加到
execute_tool() - 更新系统提示
agent.py - 可选:编写测试
______________________________________________________________________
任务交付成果
- SUMMARY.md(拥抱面MCP文章和现有地图服务器摘要)
- REFLECTION.md(经验教训和潜在的下一步行动)
- 演员阵容:
https://github.com/user-attachments/assets/a032c84c-b936-4008-a52b-57ab35f456a4
