原文链接:https://www.ryanzoe.top/ai/mcp-server-%e5%bc%80%e5%8f%91%e6%95%99%e7%a8%8b/
MCP 官方文档
https://modelcontextprotocol.io/introduction
各个 clients 对 MCP 的支持情况
https://modelcontextprotocol.io/clients
MCP Python SDK:MCP Client 和 Server 官方 SDK
https://github.com/modelcontextprotocol/python-sdk
MCP Server Demo
开发语言:Python 3.13.2
环境:MacOS
MCP 客户端:Cursor、Cline、Claude Desktop
一、环境配置
安装 uv 命令
curl -LsSf https://astral.sh/uv/install.sh | 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 = "https://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 Nonedef 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 locationlongitude: Longitude of the location""" # First get the forecast grid endpointpoints_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 responseforecast_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 forecastperiods = forecast_data["properties"]["periods"]forecasts = []for period in periods[:5]: # Only show next 5 periodsforecast = 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 servermcp.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"]}} }
调试
https://modelcontextprotocol.io/docs/tools/debugging
调试工具
-
MCP Inspector https://modelcontextprotocol.io/docs/tools/inspector
-
Claude Desktop Developer Tools
-
Server Logging
MCP Python SDK
创建 Tools
-
提供清晰、描述性的名称和说明
-
使用详细的 JSON Schema 定义参数
-
在工具描述中包含示例,告诉模型应如何使用它们
-
实施适当的错误处理和验证
-
对长时间操作使用进度报告
-
保持工具操作集中且原子化
-
记录预期返回结果
-
实施适当的超时
-
考虑对资源密集型操作进行速率限制
-
用于调试和监控的日志工具使用情况