🌉 OpenClaw MCP连接器完全指南

模型上下文协议(Model Context Protocol)是Anthropic推出的开放标准,让AI Agent像插U盘一样轻松连接任何外部工具。本文将带你完整掌握OpenClaw MCP连接器的配置与实战。

📋 目录

🤔 MCP是什么?为什么需要它?

想象这样一个场景:你的AI助手需要查询数据库、调用API、读取本地文件。传统方式是每种工具写一套集成代码,换个模型又要重写。

MCP的核心价值:统一接口标准,一次配置,到处使用。目前已有200+社区MCP服务器可供选择。

MCP vs 传统方案

特性 传统Function Calling MCP协议
标准化程度 各厂商标准不一 统一JSON-RPC 2.0接口
工具生态 需单独开发 200+现成服务器
切换成本 换模型需重写 无缝切换
安全隔离 依赖实现 进程级隔离

🏗️ MCP架构原理

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"]
    }
  }
}
安全提示:始终使用环境变量存储敏感信息(如API密钥),不要在配置文件中硬编码!

验证安装

# 检查MCPorter状态
openclaw mcp status

# 列出已连接的MCP服务器
openclaw mcp list

# 测试特定服务器连接
openclaw mcp test filesystem

🔗 连接常用MCP服务器

1. 文件系统访问

{
  "filesystem": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/workspace"]
  }
}

可用工具:read_file, write_file, list_directory, search_files

2. GitHub集成

{
  "github": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-github"],
    "env": {
      "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx"
    }
  }
}

可用工具:create_issue, search_code, create_pull_request, list_commits

3. PostgreSQL数据库

{
  "postgres": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-postgres", 
               "postgresql://user:pass@localhost/dbname"]
  }
}

4. 网页获取与搜索

{
  "fetch": {
    "command": "uvx",
    "args": ["mcp-server-fetch"]
  }
}

热门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-sqlite SQLite数据库 npx -y @modelcontextprotocol/server-sqlite
server-puppeteer 浏览器自动化 npx -y @modelcontextprotocol/server-puppeteer
server-slack Slack集成 npx -y @modelcontextprotocol/server-slack

✨ 最佳实践

1. 安全配置

2. 性能优化

// 使用连接池
{
  "postgres": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-postgres", 
               "postgresql://user:pass@localhost/dbname?pool_size=10"]
  }
}

3. 错误处理

// 在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

💻 实战代码示例

示例1:自动化数据分析流程

// 使用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: '报告已生成,详见附件'
  });
}

示例2:智能代码审查

// 结合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
  });
  
  // 返回审查建议...
}

示例3:多数据源聚合

// 同时查询多个数据库
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具备了"万物互联"的能力。通过标准化协议,你可以:

下一步:访问Skills开发教程,学习如何封装MCP工具为可复用的OpenClaw Skills。