手把手教程:10分钟搭建你的第一个MCP服务器,让AI开口调用你的工具

## MCP是什么?为什么你需要它

MCP(Model Context Protocol)是由Anthropic推出的开放协议,2026年已成为AI Agent调用外部工具的事实标准。简单说:**MCP就是AI的USB接口**——它定义了一套统一的方式,让任何AI模型都能调用你写的工具。

### 一个类比帮你理解

| 传统方式 | MCP方式 |
|———|——–|
| 每个AI工具要单独写集成代码 | 写一次MCP Server,所有AI都能用 |
| 换一个AI助手就要重写工具 | AI助手换了你工具还在 |
| 工具和AI强耦合 | 工具和AI解耦,插拔即用 |

## 第一步:环境准备

本教程使用Python。确保你有Python 3.10+:

“`bash
python –version # 应该 ≥ 3.10
“`

安装MCP Python SDK:

“`bash
pip install mcp
“`

创建一个项目目录:

“`bash
mkdir my-first-mcp-server
cd my-first-mcp-server
touch server.py
“`

## 第二步:编写你的第一个MCP工具

我们将创建一个「天气查询」工具(用模拟数据,方便测试)。打开 `server.py`:

“`python
from mcp.server import Server, NotificationOptions
from mcp.server.models import InitializationCapabilities
import mcp.server.stdio
import mcp.types as types
import asyncio

# 创建MCP服务器实例
server = Server(“weather-server”)

# 注册一个工具:查询天气
@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
return [
types.Tool(
name=”get_weather”,
description=”获取指定城市的天气信息”,
inputSchema={
“type”: “object”,
“properties”: {
“city”: {
“type”: “string”,
“description”: “城市名称,如’北京’、’上海'”,
}
},
“required”: [“city”],
},
)
]

# 实现工具逻辑
@server.call_tool()
async def handle_call_tool(
name: str, arguments: dict
) -> list[types.TextContent]:
if name == “get_weather”:
city = arguments.get(“city”, “北京”)
# 模拟天气数据(实际项目中替换为真实API调用)
weather_data = {
“北京”: “晴,25°C,湿度45%,适合户外活动”,
“上海”: “多云,28°C,湿度70%,可能有阵雨”,
“深圳”: “雷阵雨,30°C,湿度85%,记得带伞”,
}
result = weather_data.get(city, f”{city}: 晴,22°C”)
return [types.TextContent(type=”text”, text=result)]

raise ValueError(f”未知工具: {name}”)

# 启动服务器
async def main():
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
InitializationCapabilities(
sampling={},
experimental={},
),
)

if __name__ == “__main__”:
asyncio.run(main())
“`

## 第三步:测试你的MCP服务器

MCP官方提供了一个测试工具 `mcp dev`:

“`bash
# 在你的项目目录下运行
mcp dev server.py
“`

这会启动一个交互式测试界面:

“`text
Connected to weather-server
Available tools: get_weather

> 调用 get_weather 查询北京天气
Result: 晴,25°C,湿度45%,适合户外活动

> 查询上海
Result: 多云,28°C,湿度70%,可能有阵雨
“`

## 第四步:在Claude Code中使用

配置Claude Code的MCP设置文件 `~/.claude/mcp.json`:

“`json
{
“mcpServers”: {
“weather”: {
“command”: “python”,
“args”: [“/你的路径/my-first-mcp-server/server.py”]
}
}
}
“`

重启Claude Code后,你的AI编程助手就能调用天气工具了:

“`text
你:帮我查一下深圳今天天气怎么样

Claude Code:[调用 get_weather(“深圳”)]
深圳今天雷阵雨,30°C,湿度85%,记得带伞。看起来不太适合户外活动!
“`

## 进阶玩法

学会了基础,你可以接入真实API让工具真正有用:

“`python
# 接入真实天气API
import httpx

@server.call_tool()
async def handle_call_tool(name: str, arguments: dict):
if name == “get_weather”:
city = arguments[“city”]
async with httpx.AsyncClient() as client:
resp = await client.get(
f”https://api.weather.com/v1/{city}”,
params={“key”: “YOUR_API_KEY”}
)
data = resp.json()
return [types.TextContent(
type=”text”,
text=f”{city}: {data[‘condition’]}, {data[‘temp’]}°C”
)]
“`

此外你还可以创建更多工具:
– 数据库查询工具(让AI直接查你的业务数据库)
– 文件操作工具(AI帮你整理文件夹)
– API调用工具(AI帮你调任何REST API)
– 邮件发送工具(AI帮你发邮件)

> MCP的核心理念是:**任何你能写出API的功能,AI就能调用。** 限制你的只有想象力。

## 第五步:进阶——让MCP工具调用真实API

把模拟数据换成真实数据,你的工具就真正有用了。以下是一个完整的真实天气API接入示例:

“`python
# 安装HTTP客户端
# pip install httpx

import httpx

@server.call_tool()
async def handle_call_tool(name: str, arguments: dict):
if name == “get_weather”:
city = arguments[“city”]
# 使用免费的Open-Meteo天气API(无需注册)
async with httpx.AsyncClient() as client:
# 先获取城市坐标
geo_resp = await client.get(
“https://geocoding-api.open-meteo.com/v1/search”,
params={“name”: city, “count”: 1}
)
geo_data = geo_resp.json()
if not geo_data.get(“results”):
return [types.TextContent(
type=”text”,
text=f”未找到城市: {city}”
)]

loc = geo_data[“results”][0]
lat, lon = loc[“latitude”], loc[“longitude”]

# 获取天气
weather_resp = await client.get(
“https://api.open-meteo.com/v1/forecast”,
params={
“latitude”: lat, “longitude”: lon,
“current”: “temperature_2m,relative_humidity_2m,weather_code”
}
)
w = weather_resp.json()[“current”]

# 天气代码转中文
weather_map = {0: “晴”, 1: “多云”, 2: “阴”, 3: “小雨”, 61: “中雨”}
condition = weather_map.get(w[“weather_code”], “未知”)

return [types.TextContent(
type=”text”,
text=f”{loc[‘name’]}: {condition}, {w[‘temperature_2m’]}°C, ”
f”湿度{w[‘relative_humidity_2m’]}%”
)]

raise ValueError(f”未知工具: {name}”)
“`

现在你可以问AI「米兰今天天气怎么样」,它会真实查询意大利米兰的天气数据——完全免费,无需任何API注册。

## 实际应用场景

MCP不只是天气查询。以下是已经有人在用的MCP工具:

– **数据库查询**:AI直接写SQL查你的业务数据
– **Git操作**:AI帮你管理分支、创建PR
– **飞书/钉钉集成**:AI帮你发消息、建日程
– **浏览器控制**:AI帮你操作网页(结合上一期Browser Use)

### 常见问题

**Q:MCP只能用Python吗?** A:不,MCP支持Python、TypeScript、Kotlin等多种语言。Python是入门最简单的。

**Q:我的MCP工具会被别人访问吗?** A:不会。MCP运行在本地,只有你的AI客户端能访问。

**Q:安全吗?** A:取决于你写的工具做什么。建议给敏感操作(删除文件、发送消息等)加确认步骤。MCP官方也提供了权限声明机制。

🔥 关注LC智趣厅,每周一个实战教程,从入门到精通

👇 你打算用MCP写什么工具?评论区分享你的创意

滚动至顶部
微信公众号:LC智趣厅

扫码关注微信公众号
LC智趣厅