MCP笔记01: 快速创建一个MCP Server
📅 2025-03-30 | 🖱️
目前许多大型语言模型(LLMs)还不具备获取天气预报和灾害天气预警的能力。让我们使用MCP来解决这个问题!
在本文中,我们将构建一个MCP Server,暴露两个工具(tools):get-alerts
(获取预警)和get-forecast
(获取天气预报)。
MCP核心概念 #
MCP服务器可以提供三种主要类型的能力:
- 资源(Resources):类似文件的数据,可被客户端读取(如API响应或文件内容)
- 工具(Tools):可被大语言模型调用的函数(需要用户批准)
- 提示词(Prompts):预先编写的模板,帮助用户完成特定任务
创建项目 #
这里将使用MCP的Python SDK来创建一个名称为weather的MCP Server。首先创建项目:
1uv init -p 3.12 weather
2
3cd weather
创建Python虚拟机环境:
1uv venv
2source .venv/bin/activate
安装依赖:
1uv add "mcp[cli]" httpx
mcp
是MCP的Python SDK库,使用uv引入依赖时使用uv add "mcp[cli]"
httpx
是Python的一个现代化HTTP客户端库,它提供了同步和异步API来发送HTTP请求。它是一个很受欢迎的requests
库的替代品,但具有更多现代化的功能。
开发MCP Server #
创建weather.py
文件:
1from typing import Any
2import httpx
3from mcp.server.fastmcp import FastMCP
4
5
6mcp = FastMCP("weather")
7
8# Constants
9NWS_API_BASE = "https://api.weather.gov"
10USER_AGENT = "weather-app/1.0"
FastMCP类使用Python类型提示和文档字符串来自动生成工具(tool)定义,使得创建和维护MCP tool变得更加简单。
接下来,让我们在weather.py
中添加辅助函数,用于查询和格式化来自美国国家气象服务(NWS_) API的数据:
1async def make_nws_request(url: str) -> dict[str, Any] | None:
2 """Make a request to the NWS API with proper error handling."""
3 headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
4 async with httpx.AsyncClient() as client:
5 try:
6 response = await client.get(url, headers=headers, timeout=30.0)
7 response.raise_for_status()
8 return response.json()
9 except Exception:
10 return None
11
12
13def format_alert(feature: dict) -> str:
14 """Format an alert feature into a readable string."""
15 props = feature["properties"]
16 return f"""
17Event: {props.get('event', 'Unknown')}
18Area: {props.get('areaDesc', 'Unknown')}
19Severity: {props.get('severity', 'Unknown')}
20Description: {props.get('description', 'No description available')}
21Instructions: {props.get('instruction', 'No specific instructions provided')}
22"""
实现工具执行,工具执行处理器负责实际执行每个工具的逻辑。让我们添加它:
1@mcp.tool()
2async def get_alerts(state: str) -> str:
3 """Get weather alerts for a US state.
4
5 Args:
6 state: Two-letter US state code (e.g. CA, NY)
7 """
8 url = f"{NWS_API_BASE}/alerts/active/area/{state}"
9 data = await make_nws_request(url)
10
11 if not data or "features" not in data:
12 return "Unable to fetch alerts or no alerts found."
13
14 if not data["features"]:
15 return "No active alerts for this state."
16
17 alerts = [format_alert(feature) for feature in data["features"]]
18 return "\n---\n".join(alerts)
19
20
21@mcp.tool()
22async def get_forecast(latitude: float, longitude: float) -> str:
23 """Get weather forecast for a location.
24
25 Args:
26 latitude: Latitude of the location
27 longitude: Longitude of the location
28 """
29 # First get the forecast grid endpoint
30 points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
31 points_data = await make_nws_request(points_url)
32
33 if not points_data:
34 return "Unable to fetch forecast data for this location."
35
36 # Get the forecast URL from the points response
37 forecast_url = points_data["properties"]["forecast"]
38 forecast_data = await make_nws_request(forecast_url)
39
40 if not forecast_data:
41 return "Unable to fetch detailed forecast."
42
43 # Format the periods into a readable forecast
44 periods = forecast_data["properties"]["periods"]
45 forecasts = []
46 for period in periods[:5]: # Only show next 5 periods
47 forecast = f"""
48{period['name']}:
49Temperature: {period['temperature']}°{period['temperatureUnit']}
50Wind: {period['windSpeed']} {period['windDirection']}
51Forecast: {period['detailedForecast']}
52"""
53 forecasts.append(forecast)
54
55 return "\n---\n".join(forecasts)
最后加上启动mcp server的代码:
1if __name__ == "__main__":
2 # Initialize and run the server
3 mcp.run(transport="stdio")
使用MCP Server #
如上图所示,我将在Cherry Studio中使用刚刚开发的MCP Server。Cherry Studio是一款功能强大的桌面客户端,支持多种大语言模型(LLM)服务商,完美兼容Windows、macOS和Linux操作系统。由于Cherry Studio已经内置了MCP Client,我们只需在Cherry Studio中配置并启动我们刚刚开发的MCP Server,即可无缝集成这些功能。
1{
2 "mcpServers": {
3 "aPS_XksxKP-paDOrI1zqP": {
4 "name": "weather",
5 "type": "stdio",
6 "description": "",
7 "isActive": true,
8 "registryUrl": "",
9 "command": "uv",
10 "args": [
11 "--directory",
12 "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
13 "run",
14 "weather.py"
15 ]
16 }
17 }
18}
注意
上述配置是Cherry Studio在添加MCP Server时自动生成的专用配置格式。其他集成了MCP Client的ChatBot、IDE(如Cursor编辑器)可能使用不同的配置文件格式,请参考相应工具的官方文档进行配置。
在Cherry Studio中需要选择支持Tool Calling的模型,这里使用的是gpt-4o
,具体效果如下图所示: