🔌 OpenClaw MCP 集成教程

用Model Context Protocol扩展AI能力边界

MCP协议 工具集成 Server开发

妙趣导读:2026年3月15日晚上11点58分,我第一次看到MCP协议文档,那一刻突然明白——原来让AI用上任何工具,只需要一个标准协议。就像USB接口,插上就能用。MCP就是AI工具界的USB。

📋 MCP协议简介

🎯 什么是MCP?

Model Context Protocol (MCP) 是Anthropic推出的开放协议,用于标准化AI模型与外部工具/数据源之间的通信。它让AI能够:

  • 统一接口 - 不同工具使用相同的协议接入
  • 即插即用 - 新工具无需修改Agent核心代码
  • 生态共享 - 社区开发的MCP Server可以被任何人使用

🚀 OpenClaw中的MCP配置

1. mcp.json配置文件

OpenClaw使用mcp.json管理MCP Server:

// ~/.openclaw/mcp.json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/var/www/miaoquai"],
      "description": "文件系统访问"
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

2. 使用MCP工具

配置完成后,OpenClaw会自动发现并使用MCP工具:

# Agent会自动识别何时使用MCP工具
openclaw agent --message "列出/var/www/miaoquai/tools/目录下的所有HTML文件"

# Agent会调用filesystem MCP Server执行
# 返回结果类似:
# - openclaw-computer-use-tutorial.html
# - agent-skills-guide.html
# - ... (共455个文件)

🛠️ 开发自己的MCP Server

简单MCP Server示例(Node.js)

创建一个提供天气查询的MCP Server:

// weather-mcp-server.js
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');

const server = new Server({
  name: 'weather-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;
    return {
      content: [{ type: 'text', text: `${city}的天气:晴,25°C` }]
    };
  }
});

// 启动Server
const transport = new StdioServerTransport();
server.connect(transport);

💡 实战案例:Feishu MCP集成

OpenClaw已经集成了Feishu MCP,可以直接使用:

# 通过MCP调用飞书文档API
openclaw agent --message "读取飞书文档 XXX,总结前3个章节"

# Agent会自动:
# 1. 识别需要使用feishu_doc工具
# 2. 通过MCP协议调用Feishu MCP Server
# 3. 获取文档内容并总结
✅ MCP最佳实践
  • 每个MCP Server只做一件事(单一职责)
  • 在description中清晰描述Server的用途
  • 使用环境变量管理敏感配置(如API Key)
  • 为工具编写清晰的inputSchema,方便Agent理解
  • 处理错误情况,返回友好的错误信息

🔗 相关链接

🎭 妙趣小结

MCP协议就像AI的"应用商店"——有人开发了天气查询的Server,有人开发了数据库操作的Server,你只需要安装配置,就能让你的Agent获得这些能力。这才是真正的生态玩法。😎