Claude中调用mcp天气服务

之前很早就听说mcp了,但是一直没尝试下,今天试了下官方示例感觉还不错的样子。

官方的示例是一个调用天气接口获取天气预警和预报的服务

python 复制代码
from typing import Any

import httpx
from mcp.server.fastmcp import FastMCP

# 初始化 FastMCP server
mcp = FastMCP("weather")

# 定义天气查询工具
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"



async def make_nws_request(url:str)->dict[str,Any] | None:
    """使用NWS API进行天气查询"""
    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:
    """格式化天气预警"""
    props = feature.get("properties", {})
    if not props:
        return "无预警信息"
    alert = feature.get("properties", {})
    title = alert.get("title", "无标题")
    description = alert.get("description", "无描述")
    area_desc = alert.get("areaDesc", "未知区域")
    return f"标题: {title}\n描述: {description}\n区域: {area_desc}"

@mcp.tool()
async def get_alerts(state:str)-> str:
    """获取天气预警"""
    url = f"{NWS_API_BASE}/alerts/active?area={state}"
    data = await make_nws_request(url)
    if not data or "features" not in data:
        return "无法获取天气预警信息"
    if not data['features']:
        return "没有天气预警信息"
    
    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:
    """获取天气预报"""
    points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
    points_data = await make_nws_request(points_url)

    if not points_data:
        return "无法获取此位置的天气预报信息"
    
    forecast_url = points_data['properties']['forecast']
    forecast_data = await make_nws_request(forecast_url)

    if not forecast_data:
        return '无法获取天气预报信息'
    
    periods = forecast_data['properties']['periods']
    forecasts = []
    for period in periods[:5]:
        forecast = f"""
        {period['name']}:
        温度: {period['temperature']}°{period['temperatureUnit']}
        风速: {period['windSpeed']} {period['windDirection']}
        预测: {period['detailedForecast']}
        """
        forecasts.append(forecast)

    return "\n---\n".join(forecasts)


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

代码很简单,有两个mcp服务get_alerts是获取天气预警的,get_forecast是获取天气预报的

写完这些代码后,还需要配置Claude的配置文件,主要是配置程序运行路径

json 复制代码
{
    "mcpServers": {
        "weather": {
            "command": "uv",
            "args": [
                "--directory",
                "C:\\Users\\jesse\\Documents\\workspace\\mcp\\weather",
                "run",
                "weather.py"
            ]
        }
    }
}

重新启动后,会有两个mcp服务

这是mcp的使用效果

参考资料

天气应用官方示例

uv的安装

uv-速度飞快的pip替代 - 知乎

相关推荐
Wellijohn2 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
跨境Jacky12 小时前
sorftime-cli实战:61个跨境数据接口一次调通
跨境电商·mcp·sorftime
Wellijohn12 小时前
MCP 实战:不到 60 行 Python,给 Cursor 装上你自己的工具
mcp
Danny转行做跨境1 天前
跨境 CLI 实战:一个工具调 61 个数据接口
跨境电商·mcp·sorftime
xrlfreedom1 天前
MCP 面试高频考点:企业内网统一管理多个 MCP Server,stdio 与 TypeScript SDK 怎么答到位?
mcp·stdio 传输·typescript mcp sdk
Wellijohn2 天前
让 AI 能改数据库,但不能背着你改:我给 MCP Server 装了一道审批闸
python·架构·mcp
Wellijohn2 天前
我把公司内部的 12 个 CRUD 接口交给了 AI Agent,然后省出了两周
人工智能·python·mcp
Thanks_ks2 天前
AI Agent 开发入门:用 Function Calling 让大模型学会 “动手干活”,附订单查询机器人实战
python·ai·大模型·openai·agent·通义千问·mcp
xrlfreedom2 天前
MCP 面试高频考点:给 MCP Server 加日志、指标和分布式追踪,OAuth 2.1 与 JSON Schema 怎么配合?
json schema·mcp·oauth 2.1
塑料铲子3 天前
MCP 协议入门,让你的 Agent 连接微信、文档和数据库
mcp·cline