OpenClaw MCP集成插件
OpenClaw的模型上下文协议(MCP)集成 -连接到MCP服务器,并在OpenClaw中无缝使用其工具。
🎯 概述
此插件使OpenClaw能够连接到任何MCP(模型上下文协议)服务器,并将其工具暴露给AI代理。它实现了MCP Streamable HTTP传输规范,并为调用外部MCP工具提供了统一的接口。
✅ 实际工作示例: 看 REAL_XAMPLE_KR_LEGAL.md 使用kr-legal-search(不需要API密钥!)获得完整的、经过测试的配置。
主要特点
✅ HTTP/SSE传输 -完全支持带有服务器发送事件的MCP流式HTTP\ ✅ 动态工具发现 -自动从MCP服务器发现和注册工具\ ✅ 多服务器支持 -同时连接到多个MCP服务器\ ✅ 统一界面 -所有MCP工具均可通过单一工具访问 mcp 工具\ ✅ 错误处理 -强大的错误处理和日志记录
📋 先决条件
- 开爪:版本2026.1.0或更高版本
- Node.js:18.0.0或更高
- MCP服务器:任何具有HTTP传输的MCP兼容服务器
🚀 安装
方法1:通过OpenClaw扩展
# Clone into OpenClaw extensions directory
cd ~/.openclaw/extensions/
git clone https://github.com/yourorg/mcp-integration.git
# Install dependencies
cd mcp-integration
npm install
# Restart OpenClaw
openclaw gateway restart方法2:手动安装
# Clone repository
git clone https://github.com/yourorg/mcp-integration.git
cd mcp-integration
# Install dependencies
npm install
# Link to OpenClaw
ln -s $(pwd) ~/.openclaw/extensions/mcp-integration
# Restart OpenClaw
openclaw gateway restart⚙️ 配置
基本配置
添加到 ~/.openclaw/openclaw.json:
{
"plugins": {
"entries": {
"mcp-integration": {
"enabled": true,
"config": {
"enabled": true,
"servers": {
"example-server": {
"enabled": true,
"transport": "http",
"url": "http://localhost:3000/mcp"
}
}
}
}
}
}
}配置架构
{
enabled: boolean; // Enable/disable plugin (default: true)
servers: {
[serverName: string]: {
enabled: boolean; // Enable/disable this server (default: true)
transport: "http"; // Transport type (currently only http supported)
url: string; // Server URL (e.g., "http://localhost:3000/mcp")
}
}
}多服务器示例
{
"plugins": {
"entries": {
"mcp-integration": {
"enabled": true,
"config": {
"enabled": true,
"servers": {
"kr-legal": {
"enabled": true,
"transport": "http",
"url": "http://localhost:3000/mcp"
},
"database": {
"enabled": true,
"transport": "http",
"url": "http://localhost:3001/mcp"
},
"weather": {
"enabled": true,
"transport": "http",
"url": "http://localhost:3002/mcp"
}
}
}
}
}
}
}🛠️ 用法
这 mcp 工具
配置后,插件会注册一个 mcp 提供对所有连接的MCP服务器的访问的工具。
列出可用工具
在OpenClaw聊天中:
User: List all MCP tools
AI: I'll check what MCP tools are available.
[Uses tool: mcp with action=list]
Available MCP tools:
- kr-legal:search_statute - Search Korean statutes
- kr-legal:search_case_law - Search court decisions
- database:query - Execute database query
- weather:get_forecast - Get weather forecast工具调用:
{
"tool": "mcp",
"args": {
"action": "list"
}
}答复:
[
{
"id": "kr-legal:search_statute",
"server": "kr-legal",
"name": "search_statute",
"description": "Search Korean statutes and regulations",
"inputSchema": {
"type": "object",
"properties": {
"query": { "type": "string" },
"limit": { "type": "number" }
},
"required": ["query"]
}
},
{
"id": "database:query",
"server": "database",
"name": "query",
"description": "Execute SQL query",
"inputSchema": {
"type": "object",
"properties": {
"sql": { "type": "string" }
},
"required": ["sql"]
}
}
]调用MCP工具
在OpenClaw聊天中:
User: Search for Korean labor law
AI: I'll search Korean legal statutes for labor law.
[Uses tool: mcp with action=call, server=kr-legal, tool=search_statute]
Found 15 statutes related to labor law...工具调用:
{
"tool": "mcp",
"args": {
"action": "call",
"server": "kr-legal",
"tool": "search_statute",
"args": {
"query": "노동법",
"limit": 5
}
}
}答复:
{
"content": [
{
"type": "text",
"text": "{\"results\":[{\"title\":\"근로기준법\",\"statute_id\":\"0065\",...}]}"
}
]
}🏗️ 建筑
构件图
┌─────────────────────────────────────────────┐
│ OpenClaw Core │
│ ┌───────────────────────────────────────┐ │
│ │ Agent (main/admin/chat) │ │
│ └────────────────┬──────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────┐ │
│ │ Tool System │ │
│ │ - Calls mcp tool │ │
│ └────────────────┬──────────────────────┘ │
└───────────────────┼──────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ MCP Integration Plugin │
│ ┌───────────────────────────────────────┐ │
│ │ MCPManager │ │
│ │ - Manages connections │ │
│ │ - Routes tool calls │ │
│ │ - Lists available tools │ │
│ └────────────┬──────────────────────────┘ │
│ │ │
│ ┌────────────┴──────────────┐ │
│ │ │ │
│ ▼ ▼ │
│ Client 1 Client 2 │
│ (kr-legal) (database) │
└──┼────────────────────────────┼─────────────┘
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ MCP Server │ │ MCP Server │
│ (HTTP/SSE) │ │ (HTTP/SSE) │
└─────────────┘ └─────────────┘阶级结构
class MCPManager {
clients: Map;
tools: Map;
async connectServer(name: string, config: ServerConfig): Promise;
async callTool(serverName: string, toolName: string, args: any): Promise;
listTools(): ToolInfo[];
async disconnect(): Promise;
}
class StreamableHTTPClientTransport {
constructor(url: string, options?: TransportOptions);
async start(): Promise;
async send(message: JSONRPCRequest): Promise;
async close(): Promise;
onmessage?: (message: JSONRPCMessage) => void;
onerror?: (error: Error) => void;
onclose?: () => void;
}🔄 请求流
工具调用序列
sequenceDiagram
participant User
participant Agent
participant ToolSystem
participant MCPPlugin
participant MCPClient
participant MCPServer
User->>Agent: "Search for labor law"
Agent->>ToolSystem: mcp(action=call, server=kr-legal, tool=search_statute)
ToolSystem->>MCPPlugin: execute(params)
MCPPlugin->>MCPClient: callTool(search_statute, {query: "노동법"})
MCPClient->>MCPServer: POST /mcp {method: tools/call, params: {...}}
MCPServer-->>MCPClient: {result: {...}}
MCPClient-->>MCPPlugin: {content: [...]}
MCPPlugin-->>ToolSystem: {content: [...]}
ToolSystem-->>Agent: Tool result
Agent-->>User: "Found 15 statutes..."📊 HTTP传输实现
流式HTTP规范
此插件实现了MCP流式HTTP传输:
发布请求 (客户端到服务器):
POST /mcp HTTP/1.1
Content-Type: application/json
mcp-session-id: session-123
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "search_statute",
"arguments": {"query": "민법"}
}
}获取SSE流 (服务器到客户端,可选):
GET /mcp HTTP/1.1
Accept: text/event-stream
mcp-session-id: session-123
# Server can send:
event: message
data: {"jsonrpc":"2.0","id":1,"result":{...}}会话管理
- 会话ID在第一次连接时生成
- 通过以下方式跨请求持久化
mcp-session-id头球 - 允许服务器维护状态
🔧 发展
项目结构
mcp-integration/
├── src/
│ ├── index.js # Main plugin entry point
│ └── http-transport.js # HTTP/SSE transport implementation
├── config/
│ └── openclaw.plugin.json # Plugin metadata and config schema
├── package.json # npm dependencies
└── README.md # This file关键文件
index.js
- 导出OpenClaw插件注册功能
- 实现MCPManager类
- 注册
mcp工具 - 处理服务器连接和工具路由
http-transport.js
- 实现
StreamableHTTPClientTransport类 - 处理HTTP POST请求
- 管理服务器消息的SSE流
- 实现MCP传输接口
openclaw.plugin.json
- 插件元数据(id、名称、版本)
- 配置架构
- OpenClaw版本要求
添加调试日志记录
在传输中启用调试模式:
const transport = new StreamableHTTPClientTransport(url, { debug: true });此日志记录:
- 连接建立
- 请求/响应详细信息
- SSE流事件
- 错误条件
🧪 测试
测试连接
# Start a test MCP server
node test-server.js
# In OpenClaw chat
User: List MCP tools
AI: [Shows available tools from test server]手动工具调用
# Using OpenClaw CLI (if available)
openclaw tool call mcp '{"action":"list"}'
openclaw tool call mcp '{
"action": "call",
"server": "test",
"tool": "echo",
"args": {"message": "Hello MCP!"}
}'测试MCP服务器
// test-server.js
import express from 'express';
const app = express();
app.use(express.json());
app.post('/mcp', (req, res) => {
const { method, params } = req.body;
if (method === 'tools/list') {
res.json({
jsonrpc: '2.0',
id: req.body.id,
result: {
tools: [
{
name: 'echo',
description: 'Echo back a message',
inputSchema: {
type: 'object',
properties: {
message: { type: 'string' }
}
}
}
]
}
});
} else if (method === 'tools/call') {
res.json({
jsonrpc: '2.0',
id: req.body.id,
result: {
content: [
{ type: 'text', text: `Echo: ${params.arguments.message}` }
]
}
});
}
});
app.listen(3000, () => console.log('Test MCP server on :3000'));🐛 故障排除
插件未加载
检查:
openclaw status
# Look for plugin errors
openclaw logs | grep MCP
# Check MCP-specific logs解决方案:
# Verify plugin directory
ls -la ~/.openclaw/extensions/mcp-integration/
# Check dependencies
cd ~/.openclaw/extensions/mcp-integration/
npm install
# Restart gateway
openclaw gateway restart服务器连接失败
错误:
[MCP] Failed to connect to kr-legal: fetch failed解决:
- 检查服务器是否正在运行:
curl http://localhost:3000/mcp- 验证配置中的URL:
cat ~/.openclaw/openclaw.json | jq '.plugins.entries["mcp-integration"].config.servers'- 检查防火墙:
# Allow local connections
sudo ufw allow from 127.0.0.1未找到工具
错误:
Error: Tool not found: kr-legal:search_statute解决:
- 列出可用工具:
{"tool": "mcp", "args": {"action": "list"}}- 检查服务器连接:
openclaw logs | grep "Connected to kr-legal"- 重新连接服务器:
openclaw gateway restart📚 例子
示例1:气象服务
配置:
{
"servers": {
"weather": {
"enabled": true,
"transport": "http",
"url": "http://localhost:3000/mcp"
}
}
}用途:
User: What's the weather in Seoul?
AI: I'll check the weather forecast.
[Uses: mcp(action=call, server=weather, tool=get_forecast, args={city: "Seoul"})]
The weather in Seoul is currently 15°C, partly cloudy...示例2:数据库查询
配置:
{
"servers": {
"database": {
"enabled": true,
"transport": "http",
"url": "http://localhost:3001/mcp"
}
}
}用途:
User: Show me recent orders from the database
AI: I'll query the database for recent orders.
[Uses: mcp(action=call, server=database, tool=query, args={
sql: "SELECT * FROM orders ORDER BY created_at DESC LIMIT 10"
})]
Here are the 10 most recent orders...🔒 安全考虑
服务器验证
- 仅连接到受信任的MCP服务器
- 使用HTTPS进行生产部署
- 验证服务器证书
工具权限
考虑限制每个代理的工具访问权限:
{
"agents": {
"main": {
"tools": {
"allowlist": ["mcp"]
}
},
"chat": {
"tools": {
"denylist": ["mcp"] // Disable MCP in public chat
}
}
}
}输入验证
所有工具参数都传递给MCP服务器。确保:
- MCP服务器验证输入
- 敏感操作需要确认
- 已实施速率限制
🚀 未来的增强功能
- \[\]stdio传输支持
- \[\]资源支持(MCP资源)
- \[\]提示支持(MCP提示)
- \[\]工具缓存
- \[\]连接池
- \[\]重试逻辑
- \[\]健康检查
- \[\]指标和监测
📖 参考文献
📄 许可证
麻省理工学院
🤝 贡献
欢迎投稿!拜托:
- 克隆该仓库
- 创建要素分支
- 进行更改
- 如果适用,添加测试
- 提交拉取请求
💬 支持
- 问题:
- Discord 的中文翻译是“不和谐”或“纷争”。:OpenClaw社区#插件
- 电子邮件: support@openclaw.ai
______________________________________________________________________
版本: 0.1.0\ 最后更新时间: 2026-02-01\ 作者 龙虾🦞
