AI Agent 学习笔记(六):MCP 模型上下文协议,AI 世界的通用插头

AI Agent 学习笔记(六):MCP 模型上下文协议,AI 世界的通用插头

前几篇我们手动给 Agent 写工具。这篇学一个让工具“即插即用”的标准——MCP(Model Context Protocol,模型上下文协议)

一. 先看问题:为什么需要 MCP

假设你要做一个超级 Agent,需要连:文件系统、GitHub、数据库、日历、Slack、浏览器……

如果每个系统都单独写一套接入代码:

1
2
3
4
5
Agent A ──► 文件系统(专属实现)
Agent A ──► GitHub(另一套实现)
Agent B ──► 文件系统(又要重写一遍)
Agent B ──► GitHub(又双叒重写)
......

这就是 N × M 问题:N 个 Agent 客户端 × M 个外部系统,要写 N×M 套对接代码。

MCP 的做法是定一个统一协议:系统提供方只要实现一次“MCP Server”,任何支持 MCP 的 Agent(Host)都能直接用:

1
2
3
4
5
Agent A ─┐
Agent B ─┼──► MCP 协议(统一标准)──► 文件系统 Server
Agent C ─┘ ├──► GitHub Server
├──► 数据库 Server
└──► 浏览器 Server

一句话:MCP 是 AI 应用连接外部世界的“USB-C 接口”。它由 Anthropic 于 2024 年 11 月开源,现在 OpenAI、Google、微软等都在跟进。

二. MCP 的核心架构

MCP 有三层角色:

角色 英文 是什么 例子
宿主 Host 运行 Agent 的程序,用户直接面对 Claude Desktop、Cursor、自研 Agent
客户端 Client Host 内部负责连接 Server 的组件 Host 里的 MCP Client(一个 Host 可以连多个)
服务端 Server 暴露工具/资源/提示词的“插件” filesystem-server、github-server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
┌──────────────────────────────────────────────┐
│ Host(宿主程序,如 Claude Desktop) │
│ ┌──────────┐ ┌──────────┐ │
│ │ LLM │ │ MCP │ │
│ │ (大脑) │◄──►│ Client │ │
│ └──────────┘ └────┬─────┘ │
└───────────────────────┼──────────────────────┘
│ JSON-RPC 2.0 消息
┌───────────────┼────────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ MCP │ │ MCP │ │ MCP │
│ Server │ │ Server │ │ Server │
│ 文件系统 │ │ GitHub │ │ 数据库 │
└──────────┘ └──────────┘ └──────────┘

通信基于 JSON-RPC 2.0(一种 JSON 格式的远程调用协议),消息在 stdio(本地子进程管道)或 HTTP(远程服务)上传输。

三. MCP 的三大原语

一个 MCP Server 可以暴露三类能力:

原语 作用 类比 例子
Tools 工具 可执行的函数(有副作用) 读文件、建仓库、发消息
Resources 资源 只读的数据内容 书架 项目文档、配置文件
Prompts 提示词 可复用的提示模板 话术手册 “总结这份 PR”模板
1
2
3
4
5
6
7
Agent 调用流程(以 Tools 为例):
1. Client 连上 Server,Server 上报能力列表:list_tools / list_resources / list_prompts
2. Host 把工具列表转成 Function Calling 的 tools 参数给 LLM
3. LLM 决定调用某工具
4. Client 通过 JSON-RPC 通知 Server:tools/call
5. Server 执行真实操作,返回结果
6. 结果作为 tool 消息回传给 LLM

所以 MCP 和第三篇学的 Function Calling 不冲突:Function Calling 是模型侧的能力,MCP 是工具侧的标准。MCP Server 的工具最终会被翻译成 Function Calling 能识别的 tools 定义。

四. 十分钟上手:跑一个现成的 MCP Server

4.1 文件系统 Server(体验用)

需要先安装 Node.js。然后启动一个“文件系统工具”Server:

1
npx -y @modelcontextprotocol/server-filesystem /tmp/mcp-demo

这条命令会启动一个本地进程,通过 stdio 等待 MCP 消息。但裸跑它没有界面,一般要配进某个 Host 里用。

4.2 配置进 Claude Desktop

编辑 claude_desktop_config.json(在 ~/Library/Application Support/Claude/ 或 %APPDATA%/Claude/):

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp/mcp-demo"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_你的令牌" }
}
}
}

重启 Claude Desktop,聊天框里会出现“锤子”图标(工具),Agent 就能操作你指定的目录了。

其他支持 MCP 的客户端(Cursor、Cherry Studio、Windsurf、自研程序)配置方式大同小异,核心都是 mcpServers 里声明 command + args。

五. 自己写一个 MCP Server(FastMCP)

用官方 Python SDK 的 FastMCP,写一个“天气查询”Server 只需要十几行:

1
pip install "mcp[cli]"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# weather_server.py
from mcp.server.fastmcp import FastMCP

# 1. 创建 Server(名字会显示在客户端里)
mcp = FastMCP("weather-demo")

# 2. 用装饰器把普通函数变成 MCP 工具
@mcp.tool()
def get_weather(city: str) -> str:
"""查询指定城市的天气(演示用,返回模拟数据)"""
# 真实场景在这里调用天气 API
return f"{city}:晴,26°C,湿度 40%"

@mcp.tool()
def celsius_to_fahrenheit(celsius: float) -> float:
"""摄氏温度转华氏温度"""
return celsius * 9 / 5 + 32

# 3. 注册一个只读资源(Resource):客户端可以读取的内容
@mcp.resource("config://cities")
def get_cities() -> str:
"""支持查询的城市列表"""
return "北京, 上海, 广州, 深圳"

# 4. 注册一个提示词模板(Prompt)
@mcp.prompt()
def weather_question(city: str) -> str:
return f"请帮我查询{city}今天的天气,并给出穿衣建议。"

# 5. 运行(默认 stdio 传输)
if __name__ == "__main__":
mcp.run()

5.1 测试你的 Server

用官方调试工具 MCP Inspector(一个网页调试台):

1
2
mcp dev weather_server.py
# 或 npx @modelcontextprotocol/inspector python weather_server.py

浏览器打开调试台,就能看到工具列表、手动调用工具、查看返回结果。

5.2 在 Python 程序里当 Client 连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
# 1. 以子进程方式启动 Server
params = StdioServerParameters(command="python", args=["weather_server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
# 2. 握手并列出能力
await session.initialize()
tools = await session.list_tools()
print("可用工具:", [t.name for t in tools.tools])

# 3. 调用工具
result = await session.call_tool("get_weather", {"city": "北京"})
print("结果:", result.content)

asyncio.run(main())

六. 传输方式:stdio 与 HTTP

传输 适用 特点
stdio 本地 Server(和 Host 同机) 简单安全,子进程通信;配置里写 command+args
Streamable HTTP / SSE 远程 Server 跨机器,需要鉴权;配置里写 url

远程 Server 配置示例:

1
2
3
4
5
6
7
{
"mcpServers": {
"my-remote-api": {
"url": "https://api.example.com/mcp"
}
}
}

七. MCP 和之前学的东西怎么串起来

1
2
3
4
5
6
7
8
9
10
┌──────────────────────────────────────────────────┐
│ 你的 Agent │
│ │
│ Prompt(话术) Skill(SOP,含提示词与流程) │
│ Memory(记忆) RAG(知识库) │
│ │
│ 工具层: │
│ ├─ 手写函数(第三篇) │
│ └─ MCP Server(本篇)→ 文件/数据库/GitHub 等 │
└──────────────────────────────────────────────────┘
  • MCP Server 里的 Tool → 变成 Agent 的 Function Calling 工具;
  • MCP 的 Resource → 类似 RAG 的静态资料(可直接注入);
  • MCP 的 Prompt → 类似 Skill 的提示模板(可组合成技能)。

八. MCP 安全须知

  1. Server 拥有你机器的权限:文件系统 Server 能读写你指定的目录,别乱装来路不明的 Server;
  2. 第三方 Server 的代码要审查,它可能窃取数据或注入恶意指令;
  3. 敏感操作(删除、转账)仍然需要 Host 层的人工确认;
  4. 远程 Server 必须用 HTTPS + 令牌鉴权;
  5. 只给 Server 最小权限:文件系统 Server 只授权需要的目录。

九. 生态速览

| 资源 | 说明 |
| — | — | — |
| modelcontextprotocol/servers | 官方参考 Server(文件、Git、数据库、浏览器等) |
| modelcontextprotocol/inspector | 官方调试工具 |
| FastMCP / mcp SDK | Python/TypeScript 官方 SDK |
| mcp.so / Smithery 等 | 社区 Server 市场,可搜索现成 Server |

十. 小结与作业

小结

  1. MCP 解决 Agent 与外部系统 N×M 的对接问题,是“AI 的 USB-C”;
  2. 架构:Host(宿主)→ Client → Server,通信用 JSON-RPC 2.0;
  3. 三大原语:Tools(干活)、Resources(读资料)、Prompts(话术模板);
  4. 传输:本地用 stdio,远程用 HTTP;
  5. MCP 与 Function Calling 互补,与 Skill/RAG 配合使用;
  6. 安全第一:审查 Server、最小权限、人工确认。

作业

  1. 用 FastMCP 写一个“备忘录”Server,提供 add_note、list_notes 两个工具,用 Inspector 调试;
  2. 在支持 MCP 的客户端(如 Cherry Studio / Cursor)里配置你的 Server 并实际调用;
  3. 思考:为什么说 MCP 是“协议”而不是“框架”?协议和框架有什么区别?

下一篇(终章):综合实战——把 Prompt、Memory、Tool、RAG、Skill、MCP 全部整合成一个完整的 Agent 项目。