简介
MCP(Model Context Protocol)是一种用于模型上下文交互的协议,允许不同客户端与服务器进行通信,以获取特定服务或数据。下面我们将以一个天气服务的例子来介绍如何使用MCP Python SDK开发一个简单的天气服务器。
环境配置
步骤
-
安装uv命令
使用以下命令安装uv工具:curl -LsSf https://astral.sh/uv/install.sh | sh -
初始化项目
创建一个新项目文件夹,并初始化uv环境:uv init weather cd weather uv venv source .venv/bin/activate -
安装依赖
安装必要的依赖包:uv add "mcp[cli]" httpx -
创建服务器文件
创建一个名为weather.py的文件来编写服务器代码。
编写Server代码
代码示例
以下是使用MCP Python SDK编写的天气服务器示例代码:
from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP
# 初始化MCP服务器
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["properties"]
return f"""
事件:{props.get('event', '未知')}
区域:{props.get('areaDesc', '未知')}
严重程度:{props.get('severity', '未知')}
描述:{props.get('description', '无描述')}
指示:{props.get('instruction', '无具体指示')}
"""
@mcp.tool()
async def get_alerts(state: str) -> str:
"""获取美国某州的天气警报
参数:
state:美国州的两字母代码(例如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 "无法获取警报或无警报。"
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:
"""获取某地的天气预报
参数:
latitude:纬度
longitude:经度
"""
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]: # 只显示前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 Inspector运行服务
使用以下命令启动服务器:mcp dev weather.py成功后,可以通过访问
http://localhost:5173/来测试服务。 -
使用客户端调试
也可以通过支持MCP的客户端(如Cursor、Cline、Claude Desktop)进行调试。例如,在Cursor中添加一个新的MCP服务器,并设置运行命令。
调试工具
- MCP Inspector:用于调试和监控MCP服务的工具。
- Claude Desktop Developer Tools:提供开发者工具用于调试和监控。
- Server Logging:服务器日志用于跟踪和调试服务运行情况。
常见问题
- 版本不兼容:确保Node.js和npm版本兼容。例如,npm v11.2.0需要Node.js版本为^20.17.0或>=22.9.0。可以使用nvm工具来管理Node.js版本。