大家好,我是 同学小张,+v: jasper_8017 一起交流,持续学习AI大模型应用实战案例,持续分享,欢迎大家点赞+关注,订阅我的大模型专栏,共同学习和进步。
在本文中,我们将从零到一构建一个简单的MCP天气服务器,从实践过程中,熟悉MCP协议的使用。
1. MCP 服务器介绍
服务器提供专门的上下文和功能,通过 MCP 原语公开资源、工具和提示,独立运行,具有明确的职责,通过客户端接口请求采样,必须遵守安全约束,可以是本地进程或远程服务。
MCP服务器可以提供三种主要功能:
-
Resources: 资源,可以由客户端读取的类文件数据(如API响应或文件内容)
-
Tools: 工具,LLM可以调用的函数(经用户批准)
-
Prompts: 提示,帮助用户完成特定任务的预先编写的模板
本文主要实战的是工具Tools
2. MCP环境配置
2.1 依赖
- Python 3.10或更高版本
- Python MCP SDK 1.2.0或更高版本
2.2 创建环境
(1)安装uv
curl -LsSf https://astral.sh/uv/install.sh | sh
(2)利用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
3. 实战 - 你的MCP天气服务器
3.1 MCP服务构建接口:FastMCP
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("weather")
FastMCP类使用Python类型提示和文档字符串自动生成工具定义,使创建和维护MCP工具变得容易。
3.2 构建天气查询Tool函数
(1)辅助函数:make_nws_request
,用来请求天气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