天气数据服务

一个基于MCP协议的天气数据服务器,提供标准化的天气信息查询接口,适用于AI代理或客户端应用获取天气数据。

  • by ramonbnuezjr
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 ramonbnuezjr/mcp-weather-server

使用说明

MCP气象服务器

项目概述

该项目实现了一个模型上下文协议(MCP)服务器,旨在为给定位置提供当前天气信息。它充当一个标准化的接口,使AI代理或其他客户端应用程序能够获取天气数据,而无需直接与各种外部天气API交互。核心思想是抽象外部服务的复杂性,为数据检索和错误处理提供一致的协议。

该服务器使用Python和FastAPI框架构建,目前从OpenWeatherMap API检索天气数据。虽然该项目侧重于天气工具,但MCP架构被设计为可扩展的,作为人工智能代理通过一致协议访问各种工具和API(内部和外部)的标准化网关。

主要特点:

  • 标准化MCP接口: 遵循定义的请求/响应结构(使用Pydantic模型)以便于集成。
  • 气象数据检索: 获取当前温度、条件、湿度、风速和压力。
  • 外部API摘要: 保护客户免受OpenWeatherMap API的具体影响。
  • 错误处理: 为无效位置或API关键问题等问题提供清晰、标准化的MCP错误消息。
  • 异步操作: 用途 httpx 用于对外部天气API的非阻塞调用。
  • 数据验证: 利用Pydantic进行请求和响应数据验证。
  • 配置管理: 从 .env 文件。
  • 综合测试: 包括客户端模拟脚本和 pytest 用于单元和集成测试的套件。
  • 简单代理CLI: 命令行界面(weather_agent_cli.py)演示了代理如何与此MCP服务器交互。

建筑

服务器通过以下方式促进通信:

  1. 客户端(AI代理/测试脚本) 向发送MCP格式的JSON请求 /mcp/weather 终点。
  2. MCP气象服务器 (此应用程序)解析请求并提取必要的参数(例如位置)。
  3. MCP服务器的“天气工具”处理程序调用 OpenWeatherMap API 带有位置及其配置的API密钥。
  4. OpenWeatherMap返回原始天气数据。
  5. MCP服务器将此原始数据转换为标准化的MCP响应格式。
  6. MCP服务器将MCP格式的JSON响应发送回客户端。
sequenceDiagram
    participant Client as AI Agent / Test Script
    participant MCPServer as MCP Weather Server (FastAPI)
    participant ExtWeatherAPI as OpenWeatherMap API

    Client->>+MCPServer: 1. Request Weather (MCP Format via HTTP POST)
    MCPServer->>+ExtWeatherAPI: 2. Fetch Weather Data (HTTP GET with API Key)
    ExtWeatherAPI-->>-MCPServer: 3. Weather Data Response (JSON)
    MCPServer-->>-Client: 4. Weather Information (MCP Format via HTTP Response)

先决条件

  • Python 3.8+(开发过程中使用Python 3.13)
  • 来自的API密钥 OpenWeatherMap (适用于“当前天气数据”API)。

设置和安装

  1. 克隆存储库(如果适用):

    git clone <your-repository-url>
    cd mcp-weather-server
    
    
  2. 创建并激活虚拟环境:

    python3 -m venv venv
    source venv/bin/activate  # On macOS/Linux
    # For Windows (Command Prompt): venv\Scripts\activate.bat
    # For Windows (PowerShell): venv\Scripts\Activate.ps1
    
    
  3. 安装依赖项: 确保你有一个 requirements.txt 文件(典型内容见下文“项目结构”)。然后运行:

    pip install -r requirements.txt
    
    
  4. 配置API密钥:

    • 创建一个 .env 项目目录根目录中的文件(例如。, mcp-weather-server/.env).

    • 将您的OpenWeatherMap API密钥添加到其中:

      # .env
      OPENWEATHERMAP_API_KEY="YOUR_ACTUAL_API_KEY_HERE"
      
      
    • 重要提示: 确保 .env 已列在您的 .gitignore 文件,以阻止将API密钥提交到版本控制。

运行MCP服务器

  1. 确保您的虚拟环境已激活。

  2. 导航到项目根目录(mcp-weather-server).

  3. 使用Uvicorn启动服务器:

    uvicorn app.main:app --reload --port 8000
    
    
    • app.main:app:指向 app 中的FastAPI实例 app/main.py.
    • -reload:在开发过程中启用自动重新加载。如果检测到代码更改,服务器将重新启动。
    • -port 8000:指定服务器将侦听的端口。

服务器将可在以下位置访问 http://localhost:8000.

API文档(自动生成)

FastAPI自动生成交互式API文档:

  • Swagger用户界面: http://localhost:8000/docs
  • 重新记录: http://localhost:8000/redoc

这些接口允许您查看详细的端点信息、模式,并直接从浏览器中试用API。

API端点

获取当前天气

  • 网址: /mcp/weather

  • 方法: POST

  • 请求正文(JSON-MCP格式):

    {
      "protocol_version": "1.0",
      "tool_id": "weather_tool",
      "method": "get_current_weather",
      "parameters": {
        "location": "CityName,CountryCode" // e.g., "London,UK" or "Paris"
      }
    }
    
    
  • 成功响应(HTTP 200 OK-MCP格式):

    {
      "protocol_version": "1.0",
      "tool_id": "weather_tool",
      "status": "success",
      "data": {
        "location": "London",
        "temperature_celsius": 15.5,
        "temperature_fahrenheit": 59.9,
        "condition": "Clouds",
        "description": "Broken clouds",
        "humidity_percent": 75.0,
        "wind_kph": 10.8,
        "pressure_hpa": 1012.0
      },
      "error_message": null
    }
    
    
  • 应用程序错误响应(HTTP 200正常,错误状态为MCP格式): (即使应用程序级错误,MCP服务器也会返回HTTP 200,错误详细信息在有效载荷中)

    {
      "protocol_version": "1.0",
      "tool_id": "weather_tool",
      "status": "error",
      "data": null,
      "error_message": "Weather data not found for location: InvalidCity."
    }
    
    

测试

该项目包括多种测试应用程序的方法:

1.手动测试 curl 或API客户端

您可以将POST请求发送到 /mcp/weather 端点使用 curl 或者像Postman或Insomnia这样的工具。 示例 curl 命令:

curl -X POST "http://localhost:8000/mcp/weather" \
-H "Content-Type: application/json" \
-d '{
      "protocol_version": "1.0",
      "tool_id": "weather_tool",
      "method": "get_current_weather",
      "parameters": {
        "location": "Berlin,DE"
      }
    }'

2.端到端客户端模拟(test_mcp_client.py)

Python脚本(test_mcp_client.py)位于项目根目录中的模拟客户端向正在运行的MCP服务器发出各种请求。这对于快速进行端到端检查非常有用。

  • 要运行:
    1. 确保您的MCP服务器正在运行(请参阅“运行MCP服务器”)。

    2. 激活您的虚拟环境。

    3. 在单独的终端中,从项目根目录运行:

      python3 test_mcp_client.py
      
      

3.自动化测试 pytest

该项目使用 pytest 用于服务器组件的单元和集成测试。这些测试位于 tests/ 目录和覆盖API端点(具有模拟服务)和服务层逻辑(具有模拟外部HTTP调用)。

  • 设置:pytest 和 pytest-asyncio 应该列在你的 requirements.txt 并在初始设置期间安装。
  • 要运行:
    1. 激活您的虚拟环境。

    2. 从项目根目录运行:

      pytest
      
      

      或者获取更详细的输出:

      pytest -v
      
      

简单AI代理CLI(weather_agent_cli.py)

命令行界面(CLI)代理(weather_agent_cli.py)在项目根目录中提供,以演示代理如何与MCP Weather Server交互。它需要简单的文本命令来获取和显示天气信息。

  • 要运行:
    1. 确保您的MCP服务器正在运行(请参阅“运行MCP服务器”)。

    2. 激活您的虚拟环境。

    3. 在单独的终端中,从项目根目录运行:

      python3 weather_agent_cli.py
      
      
    4. 按照提示操作。命令示例: weather in London, weather Tokyo, quit.

项目结构

mcp-weather-server/
├── .vscode/                # VS Code specific settings (optional)
│   └── settings.json
├── app/                    # Main application source code
│   ├── __init__.py
│   ├── main.py             # FastAPI app instance, MCP endpoint(s)
│   ├── models.py           # Pydantic models for MCP & data structures
│   ├── services.py         # Business logic (e.g., calling weather API)
│   └── core/
│       ├── __init__.py
│       └── config.py       # Configuration management (e.g., API keys)
├── tests/                  # Automated pytest tests
│   ├── __init__.py
│   ├── test_main.py        # Tests for API endpoints (app.main)
│   └── test_services.py    # Unit tests for service logic (app.services)
├── .env                    # Local environment variables (API_KEY) - NOT COMMITTED
├── .gitignore              # Specifies intentionally untracked files by Git
├── CHANGELOG.md            # Log of notable project changes
├── requirements.txt        # Python dependencies for the project
├── README.md               # This file (main project documentation)
├── weather_agent_cli.py    # Simple CLI agent for demonstration
├── test_mcp_client.py      # End-to-end client simulation script
└── venv/                   # Python virtual environment directory

未来增强功能(潜在想法)

  • 支持更多天气数据点(例如,多日预报、紫外线指数)。
  • 向MCP服务器添加更多工具(例如,新闻、计算器、日历)。
  • 实现更复杂的错误处理和详细的日志记录。
  • 对应用程序进行Docker化,以便于部署和移植。
  • 开发具有更好NLP功能的更高级的AI代理。
  • 如果要公开MCP服务器,请向其添加身份验证/授权。

许可证

(在此处为您的项目指定许可证,例如MIT许可证。如果不确定,您可以添加“待定”或研究常见的开源许可证。)