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替代 - 知乎

相关推荐
kaizq14 小时前
AI-MCP-SQLite-SSE本地服务及CherryStudio便捷应用
python·sqlite·llm·sse·mcp·cherry studio·fastmcp
太空眼睛17 小时前
【MCP】使用SpringBoot基于Streamable-HTTP构建MCP-Server
spring boot·sse·curl·mcp·mcp-server·spring-ai·streamable
康de哥1 天前
MCP Unity + Claude Code 配置关键步骤
unity·mcp·claude code
田井中律.1 天前
MCP协议
mcp
通义灵码2 天前
Qoder 支持通过 DeepLink 添加 MCP Server
人工智能·github·mcp
酩酊仙人3 天前
fastmcp构建mcp server和client
python·ai·mcp
kwg1263 天前
本地搭建 OPC UA MCP 服务
python·agent·mcp
小小工匠3 天前
LLM - 从通用对话到自治智能体:Agent / Skills / MCP / RAG 三层架构实战
agent·rag·skill·mcp
小小工匠3 天前
LLM - 将业务 SOP 变成 AI 能力:用 Skill + MCP 驱动 Spring AI 应用落地不完全指南
人工智能·skill·spring ai·mcp
Esun_R4 天前
当 LLM 开始连接真实世界:MCP 的原理、通信与工程落地
node.js·openai·mcp