背景
MCP(Model Context Protocol)是大模型智能体的开源标准协议,旨在解决大模型内容非实时性及工具调用复杂的问题。通过 MCP,可以构建服务器提供工具,并将其连接到主机(如 Claude for Desktop),实现大模型与外部数据的交互。
MCP 示例
本案例构建一个简单的 MCP 天气预报服务器,提供获取警报(get-alerts)和获取预报(get-forecast)两个工具,并连接至 Claude for Desktop。
环境配置
- 安装 uv
curl -LsSf https://astral.sh/uv/install.sh | sh
-
安装所需的依赖包
-
在 server.py 中构建相应的 get-alerts 和 get-forecast 工具:
from typing import Any
import asyncio
import httpx
from mcp.server.models import InitializationOptions
import mcp.types as types
from mcp.server import NotificationOptions, Server
import mcp.server.stdio
NWS_API_BASE = "https://api.weather.gov"
USER_AGENT = "weather-app/1.0"
server = Server("weather")
@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
""" List available tools. Each tool specifies its arguments using JSON Schema validation. """
return [
types.Tool(
name="get-alerts",
description="Get weather alerts for a state",
inputSchema={
"type": "object",
"properties": {
"state": {
"type": "string",
"description": "Two-letter state code (e.g. CA, NY)",
},
},
"required": ["state"],
},
),
types.Tool(
name="get-forecast",
description="Get weather forecast for a location",
inputSchema={
"type": "object",
"properties": {
"latitude": {
"type": "number",
"description": "Latitude of the location",
},
"longitude": {
"type": "number",
"description": "Longitude of the location",
},
},
"required": ["latitude", "longitude"],
},
),
]
async def make_nws_request(client: httpx.AsyncClient, 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" }
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 concise string."""
props = feature["properties"]
return (
f"Event: {props.get('event', 'Unknown')}\n"
f"Area: {props.get('areaDesc', 'Unknown')}\n"
f"Severity: {props.get('severity', 'Unknown')}\n"
f"Status: {props.get('status', 'Unknown')}\n"
f"Headline: {props.get('headline', 'No headline')}\n"
"---"
)
@server.call_tool()
async def handle_call_tool(
name: str,
arguments: dict | None
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
""" Handle tool execution requests. Tools can fetch weather data and notify clients of changes. """
if not arguments:
raise ValueError("Missing arguments")
if name == "get-alerts":
state = arguments.get("state")
if not state:
raise ValueError("Missing state parameter")
state = state.upper()
if len(state) != 2:
raise ValueError("State must be a two-letter code (e.g. CA, NY)")
async with httpx.AsyncClient() as client:
alerts_url = f"{NWS_API_BASE}/alerts?area={state}"
alerts_data = await make_nws_request(client, alerts_url)
if not alerts_data:
return [types.TextContent(type="text", text="Failed to retrieve alerts data")]
features = alerts_data.get("features", [])
if not features:
return [types.TextContent(type="text", text=f"No active alerts for {state}")]
formatted_alerts = [format_alert(feature) for feature in features[:20]]
alerts_text = f"Active alerts for {state}:\n\n" + "\n".join(formatted_alerts)
return [
types.TextContent(
type="text",
text=alerts_text
)
]
elif name == "get-forecast":
try:
latitude = float(arguments.get("latitude"))
longitude = float(arguments.get("longitude"))
except (TypeError, ValueError):
return [types.TextContent(
type="text",
text="Invalid coordinates. Please provide valid numbers for latitude and longitude."
)]
if not (-90 <= latitude <= 90) or not (-180 <= longitude <= 180):
return [types.TextContent(
type="text",
text="Invalid coordinates. Latitude must be between -90 and 90, longitude between -180 and 180."
)]
async with httpx.AsyncClient() as client:
lat_str = f"{latitude}"
lon_str = f"{longitude}"
points_url = f"{NWS_API_BASE}/points/{lat_str},{lon_str}"
points_data = await make_nws_request(client, points_url)
if not points_data:
return [types.TextContent(type="text", text=f"Failed to retrieve grid point data for coordinates: {latitude}, {longitude}. This location may not be supported by the NWS API (only US locations are supported).")]
properties = points_data.get("properties", {})
forecast_url = properties.get("forecast")
if not forecast_url:
return [types.TextContent(type="text", text="Failed to get forecast URL from grid point data")]
forecast_data = await make_nws_request(client, forecast_url)
if not forecast_data:
return [types.TextContent(type="text", text="Failed to retrieve forecast data")]
periods = forecast_data.get("properties", {}).get("periods", [])
if not periods:
return [types.TextContent(type="text", text="No forecast periods available")]
formatted_forecast = []
for period in periods:
forecast_text = (
f"{period.get('name', 'Unknown')}:\n"
f"Temperature: {period.get('temperature', 'Unknown')}°{period.get('temperatureUnit', 'F')}\n"
f"Wind: {period.get('windSpeed', 'Unknown')} {period.get('windDirection', '')}\n"
f"{period.get('shortForecast', 'No forecast available')}\n"
"---"
)
formatted_forecast.append(forecast_text)
forecast_text = f"Forecast for {latitude}, {longitude}:\n\n" + "\n".join(formatted_forecast)
return [types.TextContent(
type="text",
text=forecast_text
)]
else:
raise ValueError(f"Unknown tool: {name}")
async def main():
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
InitializationOptions(
server_name="weather",
server_version="0.1.0",
capabilities=server.get_capabilities(
notification_options=NotificationOptions(),
experimental_capabilities={},
),
),
)
if __name__ == "__main__":
asyncio.run(main())
核心在于 @server.list_tools() 注册可用工具处理器,以及 @server.call_tool() 注册执行工具调用的处理器。逻辑为匹配工具名称,抽取参数,发起 API 请求并处理结果。
服务端与客户端交互
测试服务器与 Claude for Desktop。构建 MCP 客户端的核心逻辑如下:
async def process_query(self, query: str) -> str:
"""Process a query using Claude and available tools"""
messages = [
{ "role": "user", "content": query }
]
response = await self.session.list_tools()
available_tools = [{
"name": tool.name,
"description": tool.description,
"input_schema": tool.inputSchema
} for tool in response.tools]
response = self.anthropic.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
messages=messages,
tools=available_tools
)
final_text = []
assistant_message_content = []
for content in response.content:
if content.type == 'text':
final_text.append(content.text)
assistant_message_content.append(content)
elif content.type == 'tool_use':
tool_name = content.name
tool_args = content.input
result = await self.session.call_tool(tool_name, tool_args)
final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
assistant_message_content.append(content)
messages.append({ "role": "assistant", "content": assistant_message_content })
messages.append({ "role": "user", "content": [
{ : , : content., : result.content }
] })
response = .anthropic.messages.create(
model=,
max_tokens=,
messages=messages,
tools=available_tools
)
final_text.append(response.content[].text)
.join(final_text)
启动客户端需打开 Claude for Desktop 应用配置文件:~/Library/Application Support/Claude/claude_desktop_config.json。若不存在则创建,并配置以下信息:
{
"mcpServers": {
"weather": {
"command": "uv",
"args": [
"--directory",
"/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
"run",
"server.py"
]
}
}
}
保存文件并重新启动 Claude for Desktop,即可识别天气服务器中暴露的工具。
MCP 解决的问题
工具是智能体框架的重要组成部分,允许大模型与外界互动。即使没有 MCP 协议也能实现 LLM 智能体,但存在弊端:当有许多不同的 API 时,启用工具使用很麻烦,因为任何工具都需要手动构建 prompt,且每当其 API 发生变化时需手动更新。
MCP 解决了当存在大量工具时,能够自动发现,并自动构建 prompt 的问题。
整体流程示例:
- MCP 主机(如 Claude Desktop)将首先调用 MCP 服务器,询问有哪些工具可用。
- MCP 客户端接收到所列出的可用工具后,发给 LLM。LLM 收到信息后,可能会选择使用某个工具。它通过主机向 MCP 服务器发送请求,然后接收结果。
- LLM 收到工具处理结果后,向用户输出最终的答案。
总结起来,MCP 协议让智能体更容易管理、发现、使用工具。


