MCP 模型上下文协议
Model Context Protocol:AI工具生态的USB标准
"2024年的冬天,Anthropic发布了MCP。那时候没人想到,这个看似简单的协议会改变整个AI工具生态。就像当年USB统一了外设接口,MCP让AI和工具之间终于说上了同一种语言。"
🔌 一句话理解
MCP = AI工具的USB接口标准。在MCP之前,每个AI平台都有自己的工具接入方式;有了MCP,工具开发者写一次代码,所有支持MCP的AI都能用。
💡 周星驰式吐槽理解
想象你买了一个超酷的机械键盘。在USB出现前,你得看它是给Windows的、Mac的还是Linux的,每个接口都不一样。MCP就像USB——一次开发,到处运行。你写了个查天气的MCP Server,Claude能用、OpenClaw能用、Cursor也能用。这感觉就像买了万能充电器,走到哪充到哪。
🏗️ 核心架构
MCP采用客户端-服务器架构:
┌─────────────────────────────────────┐
│ AI 应用 (Host) │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ MCP Client │ │ MCP Client │ │
│ │ (搜索) │ │ (文件) │ │
│ └──────┬──────┘ └──────┬──────┘ │
└─────────┼────────────────┼──────────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐
│ MCP Server │ │ MCP Server │
│ (Search Service)│ │ (File System) │
└─────────────────┘ └─────────────────┘
核心组件
- Host:运行AI的应用程序(如Claude Desktop、OpenClaw)
- MCP Client:Host中的客户端,负责与Server通信
- MCP Server:提供具体能力的工具服务
通信方式
- Stdio:本地进程通信,适合本地工具
- SSE:服务器推送,适合远程服务
- HTTP:标准HTTP API调用
🧠 协议规范
MCP定义了三类核心能力:
1. Tools(工具)
AI可调用的函数,如搜索、计算、API调用。
{
"name": "search_web",
"description": "搜索网页内容",
"inputSchema": {
"type": "object",
"properties": {
"query": { "type": "string" }
},
"required": ["query"]
}
}
2. Resources(资源)
可被AI读取的数据源,如文件、数据库、API端点。
{
"uri": "file:///data/config.json",
"name": "配置文件",
"mimeType": "application/json"
}
3. Prompts(提示词)
预定义的提示词模板,帮助AI更好地使用工具。
⚡ OpenClaw中的MCP集成
OpenClaw完整支持MCP协议,配置方式:
配置MCP Servers
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/data"]
},
"fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "your-token"
}
}
}
}
使用MCP工具
配置后,OpenClaw Agent会自动发现并使用MCP工具:
用户: 读取我的笔记文件
AI: → 发现 filesystem MCP Server
→ 调用 read_file 工具
→ 返回文件内容
混合使用Skills和MCP
OpenClaw可以同时使用原生Skills和MCP Servers:
{
"agents": {
"defaults": {
"skills": ["web_search", "exec"],
"mcpServers": ["filesystem", "github"]
}
}
}
🛠️ 开发一个MCP Server
使用官方SDK快速创建MCP Server:
Python示例
# server.py
from mcp.server import Server
from mcp.types import TextContent
app = Server("my-weather-server")
@app.tool()
async def get_weather(city: str) -> str:
"""获取指定城市的天气"""
# 实际调用天气API
return f"{city}今天晴朗,25°C"
if __name__ == "__main__":
app.run()
TypeScript示例
// server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
const server = new Server({
name: "my-weather-server",
version: "1.0.0"
});
server.setToolHandler("get_weather", async (args) => {
const { city } = args;
return {
content: [{ type: "text", text: `${city}今天晴朗,25°C` }]
};
});
server.listen();
🔥 热门MCP Servers
- @modelcontextprotocol/server-filesystem:文件系统操作
- @modelcontextprotocol/server-github:GitHub集成
- @modelcontextprotocol/server-postgres:PostgreSQL数据库
- @modelcontextprotocol/server-puppeteer:浏览器自动化
- mcp-server-fetch:HTTP请求
- mcp-server-sqlite:SQLite数据库