模型上下文协议(Model Context Protocol)是Anthropic推出的开放标准,让AI Agent像插U盘一样轻松连接任何外部工具。本文将带你完整掌握OpenClaw MCP连接器的配置与实战。
想象这样一个场景:你的AI助手需要查询数据库、调用API、读取本地文件。传统方式是每种工具写一套集成代码,换个模型又要重写。
| 特性 | 传统Function Calling | MCP协议 |
|---|---|---|
| 标准化程度 | 各厂商标准不一 | 统一JSON-RPC 2.0接口 |
| 工具生态 | 需单独开发 | 200+现成服务器 |
| 切换成本 | 换模型需重写 | 无缝切换 |
| 安全隔离 | 依赖实现 | 进程级隔离 |
MCP采用客户端-服务器架构:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ OpenClaw │────▶│ MCP客户端 │────▶│ MCP服务器 │
│ (AI Agent) │◀────│ (内置) │◀────│ (外部工具) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ JSON-RPC 2.0 │
│ 标准协议 │
└─────────────────┘
编辑 openclaw.json 添加mcpServers配置:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"],
"env": {
"NODE_ENV": "production"
}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
},
"sqlite": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sqlite", "/path/to/database.db"]
}
}
}
# 检查MCPorter状态
openclaw mcp status
# 列出已连接的MCP服务器
openclaw mcp list
# 测试特定服务器连接
openclaw mcp test filesystem
{
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/workspace"]
}
}
可用工具:read_file, write_file, list_directory, search_files
{
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx"
}
}
}
可用工具:create_issue, search_code, create_pull_request, list_commits
{
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres",
"postgresql://user:pass@localhost/dbname"]
}
}
{
"fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
}
}
| 服务器 | 用途 | 安装命令 |
|---|---|---|
| @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-sqlite | SQLite数据库 | npx -y @modelcontextprotocol/server-sqlite |
| server-puppeteer | 浏览器自动化 | npx -y @modelcontextprotocol/server-puppeteer |
| server-slack | Slack集成 | npx -y @modelcontextprotocol/server-slack |
// 使用连接池
{
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres",
"postgresql://user:pass@localhost/dbname?pool_size=10"]
}
}
// 在Skill中优雅处理MCP错误
async function queryWithFallback(mcpTool, fallbackFn) {
try {
return await mcpTool.execute();
} catch (error) {
if (error.code === 'MCP_CONNECTION_ERROR') {
console.warn('MCP服务不可用,使用备用方案');
return await fallbackFn();
}
throw error;
}
}
| 问题 | 原因 | 解决方案 |
|---|---|---|
| "MCP server not found" | 服务器未安装或路径错误 | 检查npx命令是否可执行,尝试全局安装 |
| "Connection refused" | 端口冲突或服务未启动 | 检查端口占用,重启OpenClaw Gateway |
| "Permission denied" | 文件系统权限不足 | 调整目录权限或使用sudo |
| "Tool not available" | 能力协商失败 | 检查MCP服务器版本兼容性 |
# 启用详细日志
DEBUG=mcp* openclaw start
# 测试特定工具
openclaw mcp test github --tool search_code
# 查看MCP协议通信
openclaw mcp inspect filesystem
// 使用MCP连接数据库并生成报告
async function generateSalesReport() {
// 1. 查询数据库
const salesData = await mcpTools.postgres.query({
sql: `SELECT * FROM sales WHERE date >= DATE('now', '-30 days')`
});
// 2. 写入分析报告
await mcpTools.filesystem.writeFile({
path: '/reports/sales_30d.md',
content: generateMarkdownReport(salesData)
});
// 3. 创建GitHub Issue追踪
await mcpTools.github.createIssue({
repo: 'company/reports',
title: `销售报告 - ${new Date().toISOString().split('T')[0]}`,
body: '报告已生成,详见附件'
});
}
// 结合GitHub MCP和文件系统MCP
async function codeReviewAssistant(prNumber) {
// 获取PR代码变更
const diff = await mcpTools.github.getPullRequestDiff({
repo: 'org/project',
pull_number: prNumber
});
// 保存到本地分析
await mcpTools.filesystem.writeFile({
path: `/tmp/pr_${prNumber}.diff`,
content: diff
});
// 返回审查建议...
}
// 同时查询多个数据库
async function aggregateData() {
const [postgresData, sqliteData, apiData] = await Promise.all([
mcpTools.postgres.query({ sql: 'SELECT * FROM users' }),
mcpTools.sqlite.query({ sql: 'SELECT * FROM orders' }),
mcpTools.fetch.get({ url: 'https://api.example.com/stats' })
]);
return mergeData(postgresData, sqliteData, apiData);
}
MCP连接器让OpenClaw具备了"万物互联"的能力。通过标准化协议,你可以: