原文链接:MCP Server 开发实战指南(Python版)
原文链接:MCP Server 开发实战指南(Python版)
MCP 官方文档
modelcontextprotocol.io/introductio…
各个 clients 对 MCP 的支持情况
modelcontextprotocol.io/clients
MCP Python SDK:MCP Client 和 Server 官方 SDK
MCP Server Demo
开发语言:Python 3.13.2
环境:MacOS
MCP 客户端:Cursor、Cline、Claude Desktop
一、环境配置
安装 uv 命令
curl -LsSf astral.sh/uv/install.… | sh
初始化项目
# 给项目创建一个文件夹 uv init weather cd weather
创建一个虚拟环境并激活
uv venv source .venv/bin/activate
安装依赖
uv add "mcp[cli]" httpx
创建 server 文件
touch weather.py
二、编写Server 代码
from typing import Any import httpx from mcp.server.fastmcp import FastMCP
Initialize FastMCP server
mcp = FastMCP("weather")
Constants
NWS_API_BASE = "api.weather.gov" USER_AGENT = "weather-app/1.0"
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')
三、运行服务
MCP Inspector
mcp dev weather.py
当看到以下界面,说明服务运行成功。打开 http://localhost:5173/ 即可进行功能测试
Cursor
也可以通过一些支持 MCP Server 的客户端进行调试
设置 -> MCP → Add new MCP server
类型选择 command,名称可以自定义,执行的命令如下,需要指定路径
uv --directory /Users/ryanjhzheng/Documents/my_mcp/weather run weather.py
Cline
"mcpServers": {
"weather": {
"command": "uv",
"args": \[
"\--directory",
"/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
"run",
"weather.py"
modelcontextprotocol.io/docs/tools/…
调试工具
-
MCP Inspector modelcontextprotocol.io/docs/tools/…
-
Claude Desktop Developer Tools
-
Server Logging
MCP Python SDK
创建 Tools
-
提供清晰、描述性的名称和说明
-
使用详细的 JSON Schema 定义参数
-
在工具描述中包含示例,告诉模型应如何使用它们
-
实施适当的错误处理和验证
-
对长时间操作使用进度报告
-
保持工具操作集中且原子化
-
记录预期返回结果
-
实施适当的超时
-
考虑对资源密集型操作进行速率限制
-
用于调试和监控的日志工具使用情况
常见问题
版本不兼容
ERROR: npm v11.2.0 is known not to run on Node.js v14.21.3. This version of npm supports the following node versions: `^20.17.0 || >=22.9.0`. You can find the latest version at nodejs.org/.
遇到的错误表明当前使用的 npm 版本(v11.2.0)与 Node.js 版本(v14.21.3)不兼容。当前的 npm 版本仅支持 Node.js 版本 ^20.17.0 || >=22.9.0。将 Node.js 版本更新到支持的版本,如 ^20.17.0 || >=22.9.0
# 安装最新的 Node.js 版本 nvm install node
或者安装指定的 Node.js 版本
nvm install 20.17.0
使用已安装的 Node.js 版本
nvm use 20.17.0