Python 天气服务器开发
环境配置
➡️ 安装 uv
首先需要安装 uv
工具:
curl -LsSf https://astral.sh/uv/install.sh | sh
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
注意:安装完成后,请重启终端以确保 uv 命令可以被正常使用。
➡️ 创建项目 执行以下命令来创建和设置项目:
# Create a new directory for our project
uv init weather
cd weather
# Create virtual environment and activate it
uv venv
source .venv/bin/activate
# Install dependencies
uv add "mcp[cli]" httpx
# Create our server file
touch weather.py
# Create a new directory for our project
uv init weather
cd weather
# Create virtual environment and activate it
uv venv
.venv\Scripts\activate
# Install dependencies
uv add mcp[cli] httpx
# Create our server file
new-item weather.py
➡️ 下一步
完成上述环境设置后,我们就可以开始构建天气服务器了。这些步骤已经:
- 创建了项目目录结构
- 设置了 Python 虚拟环境
- 安装了必要的依赖包
- 创建了服务器主文件
开始构建
让我们实现一个 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"
FastMCP 类使用 Python 类型提示和文档字符串来自动生成工具定义,这使得创建和维护 MCP 工具变得容易。
辅助函数
接下来,让我们添加辅助函数来查询和格式化来自国家气象服务 API 的数据:
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桌面端测试您的服务器。
测试你的服务器
温馨提示
Claude桌面端目前尚未在 Linux 上提供。Linux 用户可以继续参阅构建客户端教程,以构建一个连接到我们刚刚构建的服务器的 MCP 客户端。
首先,确保你已经安装了 Claude for Desktop。你可以在这里安装最新版本。如果你已经有 Claude for Desktop,确保它更新到最新版本。我们需要为你想要使用的任何 MCP 服务器配置 Claude for Desktop。为此,打开你的 Claude for Desktop 应用程序配置文件,路径为 ~/Library/Application Support/Claude/claude_desktop_config.json,使用文本编辑器打开。如果文件不存在,请确保创建该文件。举个例子,如果你安装了 VS Code:
code ~/Library/Application\ Support/Claude/claude_desktop_config.json
code $env:AppData\Claude\claude_desktop_config.json
然后你将在 mcpServers 键中添加你的服务器。只有在至少一个服务器正确配置的情况下,MCP UI 元素才会在 Claude 桌面版中显示。 在这种情况下,我们将以如下方式添加我们的单个天气服务器:
{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
"run",
"weather.py"
]
}
}
}
{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather",
"run",
"weather.py"
]
}
}
}
注意事项
您可能需要在命令字段中输入 uv 可执行文件的完整路径。您可以通过在 MacOS/Linux 上运行 which uv 或在 Windows 上运行 where uv 来获取此路径。
提示
确保您传入服务器的绝对路径。
这告诉桌面版 Claude:
- 有一个名为“天气”的 MCP 服务器。
- 通过运行 uv --directory /绝对/路径/到/父文件夹/weather run weather.py 启动它。
保存文件,并重启桌面版 Claude。
使用命令进行测试
让我们确保 Claude for Desktop 正在获取我们在天气服务器中暴露的两个工具。您可以通过寻找锤子图标来做到这一点:
点击锤子图标后,您应该可以看到两个工具列出。
如果您的服务器无法被Claude for Desktop识别,请前往故障排除部分获取调试提示。
如果锤子图标已经出现,您现在可以通过在Claude for Desktop中运行以下命令来测试您的服务器:
- Sacramento的天气如何?
- Texas的天气警报有哪些?
提示
由于这是美国国家气象局,因此查询只适用于美国地区。
发生了什么
当你提问时: 客户端将你的问题发送给Claude
- Claude分析可用的工具并决定使用哪个工具
- 客户端通过MCP服务器执行所选工具
- 结果被发送回Claude
- Claude形成自然语言回应
- 回应显示给你!
故障排除
Claude 桌面端故障排除
- 从 Claude for Desktop 获取日志
Claude.app 相关的 MCP 日志文件保存在 ~/Library/Logs/Claude
目录下:
mcp.log
- 包含关于 MCP 连接和连接失败的一般日志信息mcp-server-服务器名称.log
- 包含指定服务器的错误(stderr)日志
你可以运行以下命令来查看最近的日志并实时跟踪新日志:
# 检查 Claude 的错误日志
tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
- 服务器未在 Claude 中显示
- 检查你的
claude_desktop_config.json
文件语法 - 确保项目路径是绝对路径而不是相对路径
- 完全重启 Claude for Desktop
- 工具调用静默失败
如果 Claude 尝试使用工具但失败了:
- 检查 Claude 的错误日志
- 验证你的服务器构建和运行时没有错误
- 尝试重启 Claude for Desktop
- 以上方法都不起作用,我该怎么办?
请参考我们的调试指南以获取更好的调试工具和更详细的指导。
Weather API 故障排除
- 错误:无法获取网格点数据
这通常意味着以下情况之一:
- 坐标位置在美国境外
- NWS API 服务出现问题
- 你遇到了请求频率限制
解决方案:
验证你使用的是美国境内的坐标
在请求之间添加短暂延迟
检查 NWS API 状态页面
错误:[州名] 没有活动警报
这不是真正的错误 - 它只是表示该州目前没有天气警报。可以尝试查看其他州,或在恶劣天气期间再次检查。
提示
有关更高级的故障排除,请查看我们关于调试MCP的指南。