开始构建你自己的服务器,以便在 Claude for Desktop 以及其他客户端中使用。
在本教程中,我们将构建一个简单的 MCP 天气服务器,并将其连接到一个主机(Claude for Desktop)。我们将从基础配置开始,逐步过渡到更复杂的使用场景。
特别注意:本系列所有文章默认在windows环境下,编程语言默认使用Python。官方网站有mac、Linux、windows环境配置,示例编程语言有Python、Node、Java、Kotlin、C#。可在文章末尾查看原文!
我们将构建的内容
许多大型语言模型(LLM)目前尚无法获取天气预报和严重天气预警。我们将使用 MCP 来解决这个问题!
我们将构建一个服务器,暴露两个工具:get-alerts 和 get-forecast。然后我们将其连接到一个 MCP 主机(本例中为 Claude for Desktop):


为什么使用 Claude for Desktop 而不是 Claude.ai? 因为服务器是本地运行的,MCP 当前仅支持桌面主机。远程主机仍在开发中。
MCP 核心概念
MCP 服务器可以提供三种主要能力类型:
- Resources(资源):类似文件的数据,供客户端读取(如 API 响应、文件内容等)
- Tools(工具):可由 LLM 调用的函数(需用户授权)
- Prompts(提示词模板):帮助用户完成任务的预设文本结构
本教程将主要聚焦于 工具(Tools)。
现在开始构建我们的天气服务器吧!
👉 完整项目代码见此处
前置知识
本教程默认你已熟悉:
- Python 编程
- Claude 等大型语言模型(LLM)的使用
系统要求
- 安装 Python 3.10 或更高版本
- 安装 MCP Python SDK 版本 ≥ 1.2.0
设置开发环境
首先安装 uv:
#windowspowershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
安装后请重启终端,确保 uv 命令可用。
然后初始化你的项目:
# 创建项目目录uv init weathercd weather# 创建并激活虚拟环境uv venv.venv\Scripts\activate# 安装依赖包uv add mcp[cli] httpx# 创建服务器主文件new-item weather.py
构建你的服务器
导入模块与初始化实例
在 weather.py 顶部添加以下内容:
from typing import Anyimport httpxfrom mcp.server.fastmcp import FastMCP# Initialize FastMCP servermcp = FastMCP("weather")# ConstantsNWS_API_BASE = "https://api.weather.gov"USER_AGENT = "weather-app/1.0"
FastMCP 利用 Python 类型注解和文档字符串自动生成工具定义,便于维护和扩展。
辅助函数
添加用于从 NWS 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 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')
运行服务器:
uv run weather.py
在 Claude for Desktop 中测试服务器
Claude for Desktop 暂不支持 Linux。Linux 用户请参考构建客户端教程。
确保你已安装并更新至最新版本:
👉 点击下载
编辑配置文件:
code $env:AppData\Claude\claude_desktop_config.json
示例配置:
{"mcpServers": {"weather": {"command": "uv","args": ["--directory","C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather","run","weather.py"]}}}
你可能需要在
command中写入完整的uv路径(使用where uv或which uv获取) 。同时请务必使用绝对路径。
这告诉 Claude for Desktop:
- 有一个名为“weather”的 MCP 服务器。
- 要启动它,请运行以下命令:uv —directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather.py
保存文件,然后重启 Claude for Desktop。
测试工具是否加载成功
打开 Claude for Desktop,点击锤子图标:

你应该能看到展示的两个工具:

运行以下命令进行测试:
What’s the weather in Sacramento?What are the active weather alerts in Texas?


注意:由于使用的是美国国家气象局(NWS)数据,该服务仅适用于美国地区。
背后发生了什么?
- 客户端将你的问题发送至 Claude
- Claude 分析当前可用工具,决定调用哪个
- 客户端通过 MCP 协议调用服务器上的工具
- 工具执行结果返回给 Claude
- Claude 构造自然语言回答
- 回答展示在界面中
