mcpField
W
weather

weather

本地服务
github.com/aitiwari媒体与设计184 周前更新

关于 weather

weather 是一个 Python MCP 服务示例,通过美国国家气象局 API 获取天气预警和预报,供 LLM 助手调用两个工具接入天气数据。

主要功能

  1. 01获取天气预警
  2. 02获取天气预报
  3. 03使用美国国家气象局 API

适用场景

  1. 01查询美国某州的有效天气预警
  2. 02获取美国地点的天气预报

MCP 相关

向兼容的助手公开 get_alerts 和 get_forecast 两个 MCP 工具。工具调用美国国家气象局 API,支持美国境内地点。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

暂未收录安装方式

我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。

代码仓库

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

Model Context Protocol(MCP)

🚀 为什么大家——突然之间!——都痴迷于 MCP/服务?(剧透:它正在重新定义 AI 编排)

Model Context Protocol(MCP)是 Anthropic 于 2024 年底开发的一项开放标准,旨在解决 AI 集成中的一个关键挑战:将 AI 助手连接到现实世界的数据源和系统[1][3]。MCP 为 AI 模型与外部工具、数据库和 API 交互提供了标准化接口,类似于 USB-C 作为设备通用接口的作用[4][7]。

主要特性和优势

  1. 标准化集成: MCP 无需定制集成,让开发者能够使用单一协议将 AI 模型连接到各种数据源。

  2. 动态发现: AI Agent 无需硬编码集成,即可自动检测并使用可用的 MCP 服务及其功能。

  3. 增强安全性: MCP 让开发者能够在服务中实施安全措施,确保 AI Agent 只能访问获准的数据或执行获准的操作。

  4. 灵活性: 该协议与模型无关,任何 AI 模型(例如 Claude、GPT-4、开源大模型)都可以使用支持 MCP 的工具。

  5. 生态系统发展: 自推出以来,MCP 已获得广泛关注;截至 2025 年 2 月,已有超过 1,000 个由社区构建的 MCP 服务。

对 AI 开发的影响

MCP 正通过以下方式改变 AI 格局:

  1. 简化集成: 将 AI 模型连接到外部系统的复杂问题从“N×M”问题简化为“N+M”问题。

  2. 支持复杂工作流: 为 AI Agent 实现跨多个系统的多步骤操作,例如涉及多个平台的活动策划。

  3. 促进协作: 为多 Agent 系统提供共享工作空间,让专业 AI Agent 能够高效协调任务。

  4. 增强个性化: 支持个人 AI 助手与用户数据和应用程序进行安全集成。

  5. 改善企业治理: 规范 AI 对内部工具的访问,并加强对 AI 交互的监控和控制。

截至 2025 年 3 月,MCP 已成为 AI 社区的重要议题,许多人认为它是开发集成度更高、上下文感知能力更强的 AI 系统的重要组成部分。其开放特性以及一家大型 AI 企业的支持,推动了它的快速普及和发展,使 MCP 有望成为 AI 领域集成的事实标准。


Model Context Protocol(MCP)——天气快速入门:

概述

本文档全面介绍如何构建一个简单的 Model Context Protocol(MCP)天气服务,并将其连接到主机 Claude for Desktop。该服务提供两个工具:get-alerts 和 get-forecast,用于通过美国国家气象局 API 获取天气预警和预报。

目录

  1. 简介
  2. 先决条件
  3. 系统要求
  4. 设置
  5. 构建服务
  6. 使用 Claude for Desktop 测试
  7. 幕后原理
  8. 故障排除

简介

本指南将带你创建一个 MCP 服务,使用实时天气数据增强大模型(如 Claude)。该服务利用 MCP 框架提供用于获取天气预警和预报的工具,从而弥补大模型缺乏原生环境感知能力的问题。

前提条件

开始之前,请确保你具备:

  • Python 使用经验
  • 了解 Claude 等大模型

系统要求

  • Python 3.10 或更高版本
  • MCP SDK 1.2.0 或更高版本

设置

  1. 安装 uv:

    window

    powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
    

    macos/linux

    curl -LsSf https://astral.sh/uv/install.sh | sh
    

    重启终端,确保系统能够识别 uv 命令。

  2. 创建并设置项目:

    window(cd to your dev repo_path run below command in powershell/..)

    # 为项目创建新目录
      uv init weather
      cd weather
    
      # 创建并激活虚拟环境
      uv venv
      .venv\Scripts\activate
    
      # 安装依赖
      uv add mcp[cli] httpx
    
      # 创建服务文件
      new-item weather.py
    

    macos/linux

    # 为项目创建新目录
    uv init weather
    cd weather
    
    # 创建并激活虚拟环境
    uv venv
    source .venv/bin/activate
    
    # 安装依赖
    uv add "mcp[cli]" httpx
    
    # 创建服务文件
    touch weather.py
    
    

构建服务

导入软件包并设置实例

将以下代码添加到 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"


#helper function
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')
运行服务

运行以下命令以验证服务:

uv run weather.py

使用 Claude for Desktop 测试服务

配置
  1. 安装/更新 Claude for Desktop: 确保已安装最新版本。
  2. 配置 MCP 服务: 打开或创建配置文件 ~/Library/Application Support/Claude/claude_desktop_config.json。

替代文本

-> 如果不起作用,请重启系统

  1. 添加服务配置:

    {
      "mcpServers": {
        "weather": {
          "command": "uv",
          "args": [
            "--directory",
            "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",# S:\\Dev\\weather
            "run",
            "weather.py"
          ]
        }
      }
    }
    

    将 /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather 替换为项目目录的正确绝对路径。你可能需要在 command 字段中提供 uv 可执行文件的完整路径(在 MacOS/Linux 上使用 which uv,或在 Windows 上使用 where uv 查找)。

  2. 重启 Claude for Desktop。

使用命令测试
  1. 确认工具已检测到: 在 Claude for Desktop 中查找锤子图标。点击后应列出 get_alerts 和 get_forecast 工具。

替代文本 2. 运行测试查询:

- “萨克拉门托的天气怎么样?”
- “德克萨斯州当前有哪些天气预警?”

注意:这些查询仅适用于美国地区,因为它们使用的是美国国家气象局的数据。

背后发生了什么

  1. 客户端将你的问题发送给 Claude。
  2. Claude 分析可用工具,并决定使用哪些工具。
  3. 客户端通过 MCP 服务执行选定的工具。
  4. 结果发送回 Claude。
  5. Claude 生成并显示自然语言回复。

故障排查

  • 获取 Claude for Desktop 的日志

    • mcp.log:MCP 连接和故障的常规日志。
    • mcp-server-SERVERNAME.log:指定服务的错误日志。
    tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
    
  • Claude 中未显示服务

    • 检查 claude_desktop_config.json 文件语法。
    • 确保项目路径为绝对路径。
    • 完全重启 Claude for Desktop。
  • 工具调用静默失败

    • 检查 Claude 的日志中是否有错误。
    • 确认服务可以成功构建并运行。
    • 尝试重启 Claude for Desktop。
  • 这些方法都不管用,该怎么办?

  • 错误:无法获取网格点数据

    • 坐标位于美国境外
    • NWS API 问题
    • 请求频率受限

    解决方法:

  • 错误:[STATE] 没有活动警报

    • 该州当前没有天气警报。请尝试其他州。

如需更高级的故障排查,请参阅 MCP 调试指南。

MCP Inspector

npx @modelcontextprotocol/inspector uv run weather.py

替代文本

替代文本

本地测试完成

已发布到 Github

🔗 Github - aitiwari/weather

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。