首页 /
工具指南 / OpenClaw MCP 集成完全指南
🔌 OpenClaw MCP 集成完全指南
Model Context Protocol — 让AI Agent连接万物的标准协议
TL;DR:MCP(Model Context Protocol)是Anthropic推出的开放标准,让AI Agent可以安全地连接外部数据源和工具。OpenClaw原生支持MCP,你可以通过配置文件轻松集成任何MCP服务器,也可以自己开发MCP服务器扩展Agent能力。
📋 目录
🤔 什么是MCP?
MCP(Model Context Protocol)是一个开放标准协议,定义了AI Agent如何与外部系统通信。你可以把它理解为"AI Agent的USB接口"——任何支持MCP的系统都可以即插即用地连接到任何支持MCP的Agent。
┌──────────────────────────────────────────────┐
│ AI Agent (OpenClaw) │
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ 工具A │ │ 工具B │ │ 工具C │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
│ │ │ │ │
│ ═════╪════════════╪════════════╪═══════ │
│ │ MCP Protocol │ │
│ ═════╪════════════╪════════════╪═══════ │
│ │ │ │ │
│ ┌────┴────┐ ┌────┴────┐ ┌────┴────┐ │
│ │MCP服务器│ │MCP服务器│ │MCP服务器│ │
│ │ (数据库) │ │ (API) │ │ (文件) │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└──────────────────────────────────────────────┘
MCP vs 传统API集成
| 特性 | 传统API | MCP |
| 标准化 | 每个API不同 | 统一协议 |
| 发现机制 | 手动文档 | 自动发现 |
| 安全性 | 各自实现 | 统一安全模型 |
| 可组合性 | 困难 | 即插即用 |
| 双向通信 | 通常不支持 | 原生支持 |
🏗️ MCP架构
核心组件
MCP三大能力
- 🔧 Tools(工具) — Agent可以调用的函数/操作
- 📚 Resources(资源) — Agent可以读取的数据源
- 💬 Prompts(提示) — 预定义的提示词模板
通信方式
| 方式 | 说明 | 适用场景 |
| stdio | 标准输入/输出 | 本地进程通信 |
| SSE | Server-Sent Events | 远程HTTP通信 |
| Streamable HTTP | HTTP流式通信 | 远程高性能通信 |
⚙️ OpenClaw MCP配置
基本配置
# openclaw.yaml 中的MCP配置
mcp:
servers:
# 本地MCP服务器(stdio方式)
filesystem:
command: "npx"
args: ["-y", "@modelcontextprotocol/server-filesystem", "/data"]
# 远程MCP服务器(SSE方式)
database:
url: "http://localhost:3001/sse"
# 带认证的远程服务器
github:
url: "https://mcp.github.com/sse"
headers:
Authorization: "Bearer ${GITHUB_TOKEN}"
高级配置
# 更详细的MCP服务器配置
mcp:
servers:
my-server:
command: "node"
args: ["./mcp-server.js"]
env:
API_KEY: "${MY_API_KEY}"
DEBUG: "true"
# 超时配置
timeout: 30000
# 重启策略
restart: true
maxRestarts: 3
使用wecom_mcp工具调用
// 列出MCP服务器提供的工具
wecom_mcp({
action: "list",
category: "doc" // 文档类工具
})
// 调用MCP工具
wecom_mcp({
action: "call",
category: "doc",
method: "getDoc",
args: { doc_id: "doxcnxxxxxxxx" }
})
🔥 热门MCP服务器
| MCP服务器 | 功能 | 安装方式 |
@modelcontextprotocol/server-filesystem | 文件系统访问 | npx -y @modelcontextprotocol/server-filesystem |
@modelcontextprotocol/server-github | GitHub API | npx -y @modelcontextprotocol/server-github |
@modelcontextprotocol/server-postgres | PostgreSQL | npx -y @modelcontextprotocol/server-postgres |
@modelcontextprotocol/server-slack | Slack API | npx -y @modelcontextprotocol/server-slack |
@anthropic-ai/mcp-server-brave-search | Brave搜索 | npx -y @anthropic-ai/mcp-server-brave-search |
mcp-server-weather | 天气查询 | npx -y mcp-server-weather |
🛠️ 开发自己的MCP服务器
Node.js示例
// my-mcp-server.js
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const server = new Server(
{ name: "my-mcp-server", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
// 注册工具
server.setRequestHandler('tools/list', async () => ({
tools: [
{
name: "get_weather",
description: "获取指定城市的天气信息",
inputSchema: {
type: "object",
properties: {
city: { type: "string", description: "城市名称" }
},
required: ["city"]
}
}
]
}));
// 处理工具调用
server.setRequestHandler('tools/call', async (request) => {
if (request.params.name === "get_weather") {
const city = request.params.arguments.city;
// 调用天气API
const weather = await fetchWeather(city);
return {
content: [{ type: "text", text: JSON.stringify(weather) }]
};
}
});
// 启动服务器
const transport = new StdioServerTransport();
server.connect(transport);
Python示例
# my_mcp_server.py
from mcp.server import Server
from mcp.server.stdio import stdio_server
server = Server("my-mcp-server")
@server.tool()
async def search_database(query: str, limit: int = 10) -> str:
"""搜索数据库中的记录"""
results = await db.search(query, limit)
return json.dumps(results)
@server.resource("data://records/{id}")
async def get_record(id: str) -> str:
"""获取指定ID的记录"""
record = await db.get(id)
return json.dumps(record)
if __name__ == "__main__":
stdio_server(server)
🛡️ MCP安全最佳实践
安全清单
- ✅ MCP服务器使用最小权限原则
- ✅ 所有输入参数进行验证和清洗
- ✅ 敏感操作需要二次确认
- ✅ 使用HTTPS进行远程通信
- ✅ API密钥通过环境变量传递,不硬编码
- ✅ 记录所有工具调用的审计日志
- ✅ 设置合理的超时和速率限制
- ✅ 定期更新MCP服务器依赖
# MCP安全配置示例
mcp:
servers:
my-server:
command: "node"
args: ["./mcp-server.js"]
# 安全配置
security:
allowedTools: ["get_weather", "search"] # 白名单
deniedTools: ["delete_all"] # 黑名单
maxCallDuration: 30000 # 最大调用时间
requireConfirmation: ["write", "delete"] # 需要确认的操作
🔥 实战案例
案例:自定义SEO数据MCP服务器
// mcp-seo-server.js - 为OpenClaw提供SEO数据
const server = new Server(
{ name: "seo-mcp-server", version: "1.0.0" },
{ capabilities: { tools: {}, resources: {} } }
);
// 工具:分析页面SEO
server.setRequestHandler('tools/list', async () => ({
tools: [{
name: "analyze_seo",
description: "分析目标URL的SEO指标",
inputSchema: {
type: "object",
properties: {
url: { type: "string", description: "目标URL" }
},
required: ["url"]
}
}]
}));
// 资源:SEO报告
server.setRequestHandler('resources/list', async () => ({
resources: [{
uri: "seo://reports/latest",
name: "最新SEO报告",
mimeType: "application/json"
}]
}));
// 在openclaw.yaml中配置
// mcp:
// servers:
// seo:
// command: "node"
// args: ["./mcp-seo-server.js"]
🎯 MCP的价值:通过MCP,你可以把任何外部系统变成Agent的"能力"。数据库、API、文件系统、甚至硬件设备——只要实现MCP协议,Agent就能使用。这就是AI Agent生态的"标准化时刻"。