06. MCP 协议
一句话定义
MCP (Model Context Protocol) 是 Claude 与外部工具/数据源对话的标准协议。 它让 Claude 能调用 GitHub、数据库、文件系统、自定义 API 等等——而不需要为每个工具单独写集成。
类比:USB-C 让各种设备用同一个口连接,MCP 让各种工具用同一个协议被 AI 调用。
MCP 解决什么问题
没有 MCP 时:
Claude ──[GitHub 集成]──> GitHub
Claude ──[数据库集成]──> PostgreSQL
Claude ──[Notion 集成]──> Notion
(每接一个工具都得写一套)
有了 MCP:
Claude ──[MCP 协议]──> GitHub MCP Server
──> Postgres MCP Server
──> Notion MCP Server
(所有工具都用同一个协议)
MCP 的三个角色
| 角色 | 说明 |
|---|---|
| Host | Claude Code(或其他 AI 客户端) |
| Client | Host 内置的协议处理层 |
| Server | 提供工具/资源的服务进程 |
配置 MCP Server
编辑 ~/.claude/mcp.json 或项目级 .mcp.json:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "YOUR_TOKEN"
}
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/you/Documents"]
}
}
}
重启 Claude Code 后生效。
常用 MCP Server
| 用途 | 包名 |
|---|---|
| GitHub | @modelcontextprotocol/server-github |
| PostgreSQL | @modelcontextprotocol/server-postgres |
| SQLite | @modelcontextprotocol/server-sqlite |
| Filesystem | @modelcontextprotocol/server-filesystem |
| Puppeteer(浏览器) | @modelcontextprotocol/server-puppeteer |
| Slack | @modelcontextprotocol/server-slack |
| Google Drive | @modelcontextprotocol/server-gdrive |
完整列表见 MCP 官方仓库
在对话中使用 MCP 工具
配置好后,Claude 会自动看到这些工具。直接说:
> 帮我看一下 GitHub 上 anthropics/claude-code 仓库最新 5 个 issue
> 把这个 CSV 读进来,统计每个用户的订单总数
Claude 会自动调用对应的 MCP 工具。
自己写一个 MCP Server(进阶)
最简单的方式是用 Python SDK:
# weather_server.py
from mcp.server import Server
from mcp.types import Tool, TextContent
import mcp.server.stdio
app = Server("weather")
@app.list_tools()
async def list_tools():
return [
Tool(
name="get_weather",
description="Get current weather for a city",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
)
]
@app.call_tool()
async def call_tool(name, arguments):
if name == "get_weather":
city = arguments["city"]
# 这里调用真实天气 API
return [TextContent(
type="text",
text=f"{city} 的天气是晴天,温度 25°C"
)]
if __name__ == "__main__":
mcp.server.stdio.run(app)
在 .mcp.json 中配置:
{
"mcpServers": {
"weather": {
"command": "python",
"args": ["/path/to/weather_server.py"]
}
}
}
给教师的实用 MCP 场景
| 场景 | MCP Server |
|---|---|
| 批改学生作业(读提交记录) | GitHub MCP |
| 查询学生成绩数据库 | PostgreSQL/SQLite MCP |
| 检索学校图书馆资源 | 自定义图书馆 MCP |
| 抓学术网页内容 | Puppeteer/Fetch MCP |
| 在 Notion 写讲义 | Notion MCP |
| 监控服务器作业运行 | SSH/Shell MCP |
安全提醒
- 永远不要把包含真实 token 的
.mcp.json提交到 Git - 用
.gitignore排除,或用环境变量占位符 - 自定义 MCP Server 要校验输入,避免 prompt injection
下一步
- 想让多个 Claude 协作干大活 → 07. Agent 使用
- 想编排自动化工作流 → 08. Workflow 编排