Python 快速搭建MCP天气查询服务(Stdio)

半兽人 发表于: 2025-04-24   最后更新时间: 2025-12-08 19:59:32  
{{totalSubscript}} 订阅, 120 游览

本教程将带你通过 Python 快速构建一个基于MCP的天气服务工具,并将其无缝集成到 Cursor 中。我们将使用现代 Python 工具链 —— uv 来管理环境,httpx 进行异步网络请求,结合 mcp[cli] 实现一个完整可调用的天气服务。

该项目将展示如何用纯 Python 构建一个支持命令式调用的微服务,功能包括:

  • 查询指定美国州的气象警报;
  • 获取指定经纬度位置的详细天气预报。

教程结构:

  1. Python 环境搭建 & 服务开发:基于 uv 初始化项目,开发并运行天气服务。
  2. Cursor 集成使用:配置 MCP,让该 Python 工具在 Cursor 编辑器中可调用。

一、搭建MCP 快速入门天气服务器

首先,uv安装

pip install uv

通过uv,创建Python项目并初始化它

# 创建项目,并初始化
uv init weather
cd weather

# 创建虚拟环境并激活它
uv venv
.venv\Scripts\activate

# 安装依赖
uv add "mcp[cli]" httpx

创建weather.py,输入以下代码:

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

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

# Constants
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
async def make_nws_request(url: str) -> dict[str, Any] | None:
    """Make a request to the NWS API with proper error handling."""
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "application/geo+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
def format_alert(feature: dict) -> str:
    """Format an alert feature into a readable string."""
    props = feature["properties"]
    return f"""
Event: {props.get('event', 'Unknown')}
Area: {props.get('areaDesc', 'Unknown')}
Severity: {props.get('severity', 'Unknown')}
Description: {props.get('description', 'No description available')}
Instructions: {props.get('instruction', 'No specific instructions provided')}
"""

@mcp.tool()
async def get_alerts(state: str) -> str:
    """Get weather alerts for a US state.
    Args:
        state: Two-letter US state code (e.g. CA, NY)
    """
    url = f"{NWS_API_BASE}/alerts/active/area/{state}"
    data = await make_nws_request(url)
    if not data or "features" not in data:
        return "Unable to fetch alerts or no alerts found."
    if not data["features"]:
        return "No active alerts for this state."
    alerts = [format_alert(feature) for feature in data["features"]]
    return "\n---\n".join(alerts)

@mcp.tool()
async def get_forecast(latitude: float, longitude: float) -> str:
    """Get weather forecast for a location.
    Args:
        latitude: Latitude of the location
        longitude: Longitude of the location
    """
    # First get the forecast grid endpoint
    points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
    points_data = await make_nws_request(points_url)
    if not points_data:
        return "Unable to fetch forecast data for this location."
    # Get the forecast URL from the points response
    forecast_url = points_data["properties"]["forecast"]
    forecast_data = await make_nws_request(forecast_url)
    if not forecast_data:
        return "Unable to fetch detailed forecast."
    # Format the periods into a readable forecast
    periods = forecast_data["properties"]["periods"]
    forecasts = []
    for period in periods[:5]:  # Only show next 5 periods
        forecast = f"""
{period['name']}:
Temperature: {period['temperature']}°{period['temperatureUnit']}
Wind: {period['windSpeed']} {period['windDirection']}
Forecast: {period['detailedForecast']}
"""
        forecasts.append(forecast)
    return "\n---\n".join(forecasts)

if __name__ == "__main__":
    # Initialize and run the server
    mcp.run(transport='stdio')

执行weather.py

uv run weather.py

正常情况应该是什么都不会输出。

二、Cursor中配置

打开 Cursor,点击右上角的「配置」,在面板中选择 「MCP」 标签页,然后点击 「Add new global MCP server」 添加新的 MCP 服务。

Curosr配置MCP

填写如下配置(记得将路径替换为你实际的本地路径):

{
  "mcpServers": {
    ...
    "weather": {
      "command": "uv",
      "args": [
        "--directory /Users/xxxx/project/python/python-mcp run weather.py"
      ]
    }
  }
}

询问天气

what is the weather in newyork?

可以看到调用了MCP工具get_forcast

cursor调用天气MCP

询问预警,可以看到调用了MCP工具get_alerts

what is the weather alert in New York

cursor调用天气MCP

这样,你就集成了一个天气功能,给Cursor调用咯。

更新于 2025-12-08

查看MCP更多相关的文章或提一个关于MCP的问题,也可以与我们一起分享文章