天气微服务

一个基于FastMCP构建的简单天气微服务,提供天气预报和当前天气数据。

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

使用说明

MCP服务器天气

一个使用FastMCP构建的简单天气微服务,使用Open-Meteo API提供天气预报和当前天气数据。


目录


特性

  • 获取天气预报 适用于任何位置(纬度/经度)
  • 获取当前天气 适用于任何位置(纬度/经度)
  • 异步HTTP请求以实现快速响应
  • 易于集成为MCP工具

需求

  • Python>=3.13
  • httpx>=0.28.1
  • mcp[cli]>=1.9.2

安装

  1. 克隆存储库:
    git clone https://github.com/yourusername/mcp-server-weather.git
    cd mcp-server-weather
    
  2. (可选)创建并激活虚拟环境:
    python3 -m venv .venv
    source .venv/bin/activate
    
  3. 安装依赖项:
    pip install -r requirements.txt
    # or, if using pyproject.toml
    pip install .
    

用法

运行服务器:

python server.py

服务器公开了两个主要工具:

1.获取预测

获取给定纬度和经度的每日天气预报。

@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str
  • 退货: 带有每日最高/最低温度、降水量和天气代码的格式化字符串。

输出示例:

Date: 2024-06-01
Max Temperature: 22°C
Min Temperature: 14°C
Precipitation: 0.5 mm
Weather Code: 2
---
Date: 2024-06-02
Max Temperature: 20°C
Min Temperature: 13°C
Precipitation: 1.2 mm
Weather Code: 3

2.获取当前天气

获取给定纬度和经度的当前天气数据。

@mcp.tool()
async def get_current_weather(latitude: float, longitude: float) -> str
  • 退货: 包含当前天气详细信息(温度、风、湿度等)的JSON字符串

输出示例:

{
  "current": {
    "temperature_2m": 21.3,
    "is_day": 1,
    "showers": 0.0,
    "cloud_cover": 45,
    "wind_speed_10m": 5.2,
    "wind_direction_10m": 180,
    "pressure_msl": 1012.3,
    "snowfall": 0.0,
    "precipitation": 0.0,
    "relative_humidity_2m": 60,
    "apparent_temperature": 21.0,
    "rain": 0.0,
    "weather_code": 2,
    "surface_pressure": 1012.3,
    "wind_gusts_10m": 8.0
  }
}

API和工具架构

获取预测

  • 输入:
    • latitude (浮动)
    • longitude (浮动)
  • 输出:
    • 包含每日天气数据的格式化字符串(见上例)

get_current天气

  • 输入:
    • latitude (浮动)
    • longitude (浮动)
  • 输出:
    • 带有当前天气数据的JSON对象(见上例)

项目结构

.
├── server.py           # Main server code, defines weather tools
├── pyproject.toml      # Project metadata and dependencies
├── README.md           # Project documentation
├── project.md          # Project code summary
├── .gitignore          # Git ignore file
├── .python-version     # Python version file
├── uv.lock             # Lock file for uv package manager
├── .venv/              # Virtual environment (not committed)
└── __pycache__/        # Python cache files

建筑

graph TD;
    A[Client (Claude Desktop, etc)] -- stdio --> B(MCP Server: server.py)
    B -- HTTPX async requests --> C(Open-Meteo API)
    B -- Exposes tools --> D[LLM/Client]
    B -- Returns weather data --> A
  • 客户端:通过stdio连接到MCP服务器(例如Claude Desktop)
  • MCP服务器:处理请求,公开工具,从Open Meteo获取数据
  • 开放式API:提供天气和预报数据
  • 法学硕士/客户:消耗数据并生成响应

教程

使用Python和Open-Meteo API创建MCP服务器

MCP服务器通过将语言模型连接到数据源和服务来扩展语言模型的功能。

MCP服务器公开了三个主要原语:

资源(客户控制)

  • 根据请求向客户端公开用作上下文的数据。
  • 当您想被动地向MCP客户端公开数据或内容时,请使用资源,并让客户端选择何时访问它。

工具(模型控制)

  • 向客户端模型公开可执行功能。
  • 当您希望客户端执行操作时,请使用工具,例如从API请求内容、转换数据或发送电子邮件。

提示(用户控制)

  • 向用户公开可重用的提示和工作流。
  • 当您希望客户端向用户显示提示和工作流时,可以使用提示,例如简化与资源或工具的交互。

示例:将天气数据转换为自然语言

LLM非常适合将数据转换为自然语言。例如,他们可以将温度、风速、露点等天气数据转化为对天气感觉的描述,以及对穿哪种衣服的建议。

分步教程

0.要求

  • Claude.ai帐户(MCP支持所有帐户类型)
  • 克劳德桌面应用程序(macOS/Windows)
  • 代码编辑器(例如VS Code)
  • uv(基于Rust的Python包管理器)
    • macOS: brew install uv
    • 窗户: winget install --id=astral-sh.uv -e

1.设立项目

要设置项目,请打开要添加项目的文件夹中的代码编辑器。然后按照以下步骤设置您的项目:

使用编辑器工具或终端创建一个名为mcp server weather的新文件夹:

mkdir mcp-server-weather

导航到终端中的文件夹:

cd mcp-server-weather

启动一个新的紫外线项目:

uv init

使用uv创建虚拟环境:

uv venv

启动虚拟环境:

source .venv/bin/activate

注意:要停止虚拟环境,请在终端中运行deactivate。

在虚拟环境中安装带有CLI扩展和其他Python依赖项的Python MCP SDK:

uv add "mcp[cli]" httpx

2.构建气象MCP服务器

创建 server.py 并添加以下脚手架:

from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("weather")

# ... your code here ...

if __name__ == "__main__":
    mcp.run(transport='stdio')

添加常量和辅助函数

OPENMETEO_API_BASE = "https://api.open-meteo.com/v1"
USER_AGENT = "weather-app/1.0"

# Helper function to make a request to the Open-Meteo API
async def make_openmeteo_request(url: str) -> dict[str, Any] | None:
    """Make a request to the Open-Meteo API with proper error handling."""
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "application/json"
    }
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except Exception:
            return None

添加工具

@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
    # ...

@mcp.tool()
async def get_current_weather(latitude: float, longitude: float) -> str:
    """Get current weather for a location.

    Args:
        latitude: Latitude of the location
        longitude: Longitude of the location
    """
    
    url = f"{OPENMETEO_API_BASE}/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,is_day,showers,cloud_cover,wind_speed_10m,wind_direction_10m,pressure_msl,snowfall,precipitation,relative_humidity_2m,apparent_temperature,rain,weather_code,surface_pressure,wind_gusts_10m"
    
    data = await make_openmeteo_request(url)

    if not data:
        return "Unable to fetch current weather data for this location."

    return data

3.测试和运行MCP服务器

mcp dev server.py
  • 打开http://localhost:5173在您的浏览器中
  • 连接、列出工具并使用纬度/经度进行测试

4.扩展MCP服务器

  • 添加更多工具(例如get_location)
  • 使用Open-Meteo地理编码API进行位置搜索

贡献

欢迎投稿!请打开问题或提交改进、错误修复或新功能的拉取请求。

许可证

麻省理工学院

作者