使用说明
HW5:具有模型上下文协议的地图服务器
使用模型上下文协议(MCP)和OpenAI代理集成的三个地图相关服务器的完整实现。
🚀 快速入门(Docker-推荐)
-
创建
.env文件:[System.IO.File]::WriteAllText("$PWD\.env", "OPENAI_API_KEY=your-key-here`n", [System.Text.Encoding]::UTF8) -
运行自动演示 (6个预编程查询):
docker-compose up agent -
运行交互模式 (键入您自己的问题):
docker-compose run --rm agent
就是这样!自动演示将显示所有服务器功能。
📁 项目结构
HW5/
├── servers/
│ ├── geocoding_server.py # Address ↔ coordinates, place search (3 operations)
│ ├── routing_server.py # Routes, distances, nearby POIs (3 operations)
│ └── weather_server.py # Current & forecast weather (3 operations)
├── tests/
│ ├── test_geocoding.py # 9 tests
│ ├── test_routing.py # 9 tests
│ └── test_weather.py # 8 tests
├── agent_demo.py # OpenAI agent integration
├── Dockerfile # Container definition
├── docker-compose.yml # 4 services: agent, demo, test, dev
├── requirements.txt # Python dependencies
├── .env # API keys (you create this)
├── summary.md # MCP concepts (required deliverable)
└── reflection.md # Lessons learned (required deliverable)
🎯 每台服务器做什么
| 服务器 | 操作 | 示例 |
|---|---|---|
| 地理编码 | geocode, reverse_geocode, search_places |
“埃菲尔铁塔在哪里?” |
| 路由 | calculate_route, distance_matrix, find_nearby |
“纽约到洛杉矶有多远?” |
| 天气 | get_weather, weather_forecast, location_weather_info |
“东京的天气怎么样?” |
总计:3台服务器上的9次操作,26次单元测试
💻 本地设置(无Docker)
# Install dependencies
pip install -r requirements.txt
# Create .env file
echo OPENAI_API_KEY=your-key-here > .env
# Run demo
python agent_demo.py
🧪 运行测试
码头工人: docker-compose run --rm test
本地: pytest
所有26项测试都应通过(API调用需要互联网)。
🐳 Docker命令
# Automated demo (shows all features)
docker-compose up agent
# Interactive mode (type your questions)
docker-compose run --rm agent
# Run tests
docker-compose run --rm test
# Shell access
docker-compose run --rm dev
# Rebuild after changes
docker-compose build
# Cleanup
docker-compose down
💡 要尝试的示例查询
- “巴黎的天气怎么样?”
- “从纽约到洛杉矶有多远?”
- “查找埃菲尔铁塔附近的咖啡店”
- “自由女神像的地址是什么?”
- “给我看东京的7天天气预报”
- “计算从伦敦到曼彻斯特的路线”
自动演示(选项1)运行以下6个查询:
- 埃菲尔铁塔地理编码
- 反向地理编码巴黎坐标
- 纽约到洛杉矶的距离
- 巴黎天气预报
- 东京7天天气预报
- 埃菲尔铁塔附近的咖啡馆
🔧 故障排除
之后无法键入 docker-compose up agent?
→ Use docker-compose run --rm agent 用于交互式输入
.env编码错误? → 使用UTF-8重新创建:
[System.IO.File]::WriteAllText("$PWD\.env", "OPENAI_API_KEY=your-key-here`n", [System.Text.Encoding]::UTF8)
测试失败?
→ 检查互联网连接(API需要访问)
→ 验证Python 3.11+
→ 重新安装: pip install -r requirements.txt
Docker构建失败?
→ 确保Docker桌面正在运行
→ Try: docker-compose build --no-cache
🛠️ 技术
- Python 3.11:异步/等待,aiohttp
- OpenAI API:函数调用(GPT-4)
- Docker/作曲:多用途集装箱
- pytest:使用pytest asyncio进行单元测试
- 应用程序编程接口:OpenStreetMap提名(地理编码),Open Meteo(天气)
更多的信息:参见 summary.md MCP概念和 reflection.md 在开发过程中吸取的经验教训。