地图服务代理工具

基于OpenAI Agents SDK实现的MCP地图服务器,提供实时地理编码、POI搜索、路线规划、历史旅行模式分析和天气环境数据服务。

  • by ddc002021
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 ddc002021/MapServerMCP

使用说明

丹妮·查因-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架构

此实现遵循模型上下文协议约定:

  1. 服务器参数 -每台服务器的配置
  2. 异步操作 -所有I/O都是非阻塞的
  3. 结构化响应 -一致性 {success, ...} 格式
  4. 工具定义 -OpenAI函数调用模式
  5. 资源管理 -适当清理 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"
}

这允许代理人:

  1. 检查操作是否成功
  2. 适当提取数据或报告错误
  3. 优雅地处理失败

🚧 扩展系统

向现有服务器添加新工具

  1. 在中向服务器类添加方法 servers/
  2. 将工具定义添加到 TOOLS 在 agent_tools.py
  3. 将路由案例添加到 execute_tool() 在 agent_tools.py
  4. 可选:在中编写测试 tests/test_servers.py

创建新服务器

  1. 创建 servers/new_server.py 随着 ServerParams 服务器类
  2. 导入并初始化 agent_tools.py
  3. 将工具定义添加到 TOOLS 列表
  4. 将路由案例添加到 execute_tool()
  5. 更新系统提示 agent.py
  6. 可选:编写测试

任务交付成果

  1. SUMMARY.md(拥抱面MCP文章和现有地图服务器摘要)
  2. REFLECTION.md(经验教训和潜在的下一步行动)
  3. 演员阵容:

https://github.com/user-attachments/assets/a032c84c-b936-4008-a52b-57ab35f456a4