天气服务服务器

一个基于Open-Meteo API和OpenStreetMap地理编码的天气信息服务器,提供当前天气状况和多日天气预报功能。

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

使用说明

MCP气象服务器

模型上下文协议(MCP)服务器,使用Open-Meteo API和OpenStreetMap进行地理编码,为城市提供天气信息。

特性

  • 🌤️ 当前天气状况
  • 📅 多日天气预报(最多16天)
  • 🌍 通过OpenStreetMap地理编码提供全球城市支持
  • 🔌 stdio和HTTP服务器模式
  • 🧪 全面的测试能力
  • 📝 详细的天气格式

快速开始

  1. 设置环境:

    chmod +x setup.sh
    ./setup.sh setup
    
  2. 运行服务器(MCP客户端的stdio模式):

    ./setup.sh run-stdio
    
  3. 或者以HTTP模式运行进行测试:

    ./setup.sh run-http
    

用法

MCP客户端集成(stdio模式)

与Claude Desktop等MCP客户端集成:

./setup.sh run-stdio

服务器将按照MCP协议通过JSON-RPC在stdin/stdout上进行通信。

HTTP模式(用于测试)

对于手动测试和调试:

./setup.sh run-http

服务器将于启动 http://localhost:8000 具有以下端点:

  • GET /weather?city=<city>&forecast_days=<days> -获取天气数据
  • GET /health -健康检查
  • GET /tools -列出可用工具
  • GET / -API文件

HTTP示例

# Get weather for London with 5-day forecast
curl "http://localhost:8000/weather?city=London&forecast_days=5"

# Get weather for New York with 3-day forecast
curl "http://localhost:8000/weather?city=New%20York&forecast_days=3"

# Health check
curl "http://localhost:8000/health"

测试

自动化测试

对两种服务器模式运行测试:

# Test stdio server
./setup.sh test-stdio

# Test HTTP server
./setup.sh test-http

手动测试

使用MCP客户端测试stdio服务器

您可以使用任何MCP客户端或通过发送JSON-RPC消息来测试stdio服务器:

echo '{"protocolVersion": "2024-11-05","capabilities": {},"clientInfo": {"name": "test-client","version": "1.0.0"}}' | python weather_server.py

使用curl测试HTTP服务器

# Start the HTTP server
./setup.sh run-http

# In another terminal, test the endpoints
curl "http://localhost:8000/weather?city=Paris&forecast_days=3"
curl "http://localhost:8000/health"
curl "http://localhost:8000/tools"

可用工具

get_weather

获取指定城市的当前天气状况和预报。

参数:

  • city (string,必填):要获取天气的城市名称
  • forecast_days (整数,可选):预测天数(1-16,默认值:5)

示例响应:

Weather for London
==================

Current Weather:
  Condition: Partly cloudy
  Temperature: 15.2°C
  Humidity: 73%
  Wind: 12.5 km/h at 245°

Forecast:
  2024-01-15: Partly cloudy, 8°C - 16°C, 0.2mm rain
  2024-01-16: Light rain, 10°C - 14°C, 3.1mm rain
  2024-01-17: Clear sky, 6°C - 18°C, 0.0mm rain
  2024-01-18: Overcast, 9°C - 15°C, 1.2mm rain
  2024-01-19: Mainly clear, 7°C - 17°C, 0.0mm rain

配置

环境变量

您可以使用环境变量自定义服务器行为:

  • WEATHER_SERVER_PORT:HTTP服务器端口(默认值:8000)
  • WEATHER_SERVER_HOST:HTTP服务器主机(默认:localhost)
  • LOG_LEVEL:日志记录级别(默认值:INFO)

API集成

服务器遵守外部API的速率限制:

  • 开放式API:不需要API密钥,合理的费率限制
  • OpenStreetMap提名:每秒1个请求,包括适当的用户代理

文件结构

mcp-weather-server/
├── weather_server.py      # Main MCP server (stdio mode)
├── weather_http_server.py # HTTP server for testing
├── requirements.txt       # Python dependencies
├── setup.sh               # Setup and management script
├── test_mcp_client.py     # Helper script to test the stdio server
└── README.md              # This documentation

建筑

组件

  1. WeatherServer类:核心天气功能

    • 通过OpenStreetMap Nomatim API进行地理编码
    • 从Open-Meteo API获取天气数据
    • 响应格式和错误处理
  2. MCP服务器(stdio):模型上下文协议实现

    • 通过stdin/stdout进行JSON-RPC通信
    • 工具注册和执行
    • MCP协议合规性
  3. HTTP服务器:测试调试界面

    • REST API端点
    • JSON响应格式
    • 健康监测

数据流

  1. 城市输入 → 地理编码 → 天气API → 格式化响应
  2. 客户请求城市天气
  3. 服务器将城市地理编码为纬度/经度坐标
  4. 服务器从Open Meteo获取天气数据
  5. 服务器格式化并返回人类可读的天气信息

外部API

  • OpenStreetMap提名:免费地理编码服务

    • 端点: https://nominatim.openstreetmap.org/search
    • 不需要API密钥
    • 速率限制:~1个请求/秒
  • Open Meteo:免费天气API

    • 端点: https://api.open-meteo.com/v1/forecast
    • 不需要API密钥
    • 支持当前天气和预报

故障排除

常见问题

“找不到模块”错误

# Ensure virtual environment is activated
source venv/bin/activate

# Reinstall dependencies
pip install -r requirements.txt

地理编码失败

  • 检查互联网连接
  • 验证城市名称拼写
  • 一些非常小的城镇可能找不到
  • 尝试使用州/国家:“法国巴黎”,而不仅仅是“巴黎”

天气API超时

  • 检查互联网连接
  • Open-Meteo API可能暂时不可用
  • 服务器包括用于暂时故障的重试逻辑

HTTP服务器无法启动

# Check if port is already in use
lsof -i :8000

# Use different port
WEATHER_SERVER_PORT=8001 ./setup.sh run-http

调试模式

启用详细日志记录:

# Set log level to DEBUG
export LOG_LEVEL=DEBUG
./setup.sh run-stdio

网络问题

如果你在公司防火墙后面:

  1. 确保访问:

    • https://nominatim.openstreetmap.org
    • https://api.open-meteo.com
  2. 如果需要,配置代理:

    export HTTP_PROXY=http://your-proxy:port
    export HTTPS_PROXY=https://your-proxy:port
    

MCP客户端集成

克劳德桌面

添加到您的Claude Desktop配置中:

{
  "mcpServers": {
    "weather": {
      "command": "/path/to/venv/python",
      "args": ["/path/to/weather_server.py"],
      "env": {}
    }
  }
}

自定义MCP客户端

服务器实现MCP协议版本2024-11-05:

# Example client interaction
import json
import subprocess

# Start server process
proc = subprocess.Popen(
    ['python', 'weather_server.py'],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    text=True
)

# Send initialize request
init_request = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
        "protocolVersion": "2024-11-05",
        "capabilities": {},
        "clientInfo": {"name": "my-client", "version": "1.0.0"}
    }
}

proc.stdin.write(json.dumps(init_request) + '\n')
proc.stdin.flush()

# Read response
response = proc.stdout.readline()
print(json.loads(response))

api参考

MCP方法

工具/列表

列出可用工具。

请求:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list"
}

答复:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      {
        "name": "get_weather",
        "description": "Get current weather and forecast for a city",
        "inputSchema": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "Name of the city"},
            "forecast_days": {"type": "integer", "minimum": 1, "maximum": 16}
          },
          "required": ["city"]
        }
      }
    ]
  }
}

工具/调用

执行一个工具。

请求:

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": {
      "city": "Tokyo",
      "forecast_days": 7
    }
  }
}

答复:

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "Weather for Tokyo\n==================\n\nCurrent Weather:\n  Condition: Clear sky\n  Temperature: 22.5°C\n  ..."
      }
    ]
  }
}

HTTP端点

GET/天气

获取城市的天气信息。

参数:

  • city (必填):城市名称
  • forecast_days (可选):预测天数(1-16,默认值:5)

例子:

curl "http://localhost:8000/weather?city=Berlin&forecast_days=5"

答复:

{
  "city": "Berlin",
  "coordinates": {"latitude": 52.5200, "longitude": 13.4050},
  "formatted_weather": "Weather for Berlin\n==================\n...",
  "raw_data": { /* Open-Meteo API response */ }
}

GET/健康

健康检查端点。

答复:

{
  "status": "healthy",
  "service": "weather-server"
}

GET/工具

列出可用工具和使用信息。

答复:

{
  "tools": [
    {
      "name": "get_weather",
      "description": "Get current weather and forecast for a city",
      "parameters": {
        "city": "Name of the city (required)",
        "forecast_days": "Number of forecast days (1-16, default: 5)"
      },
      "example": "/weather?city=London&forecast_days=3"
    }
  ]
}

贡献

  1. 分叉存储库
  2. 创建要素分支
  3. 进行更改
  4. 添加新功能的测试
  5. 运行测试套件
  6. 提交拉取请求

许可证

CC0 1.0通用(CC0 1.0)公共领域专用