扩展AI Agent能力完全指南 — 连接一切外部服务
MCP(Model Context Protocol)是一个开放标准,由 Anthropic 提出并维护,允许 AI Agent 通过标准化接口连接外部工具和数据源。OpenClaw 原生支持 MCP,可以无缝集成任何 MCP Server。
+------------------+ MCP Protocol +------------------+
| OpenClaw Agent | <------------------> | MCP Server |
| | (stdio/SSE) | (工具/数据源) |
+------------------+ +------------------+
| 方式 | 说明 | 适用场景 |
|---|---|---|
| stdio | 标准输入输出 | 本地进程,最常用 |
| SSE | Server-Sent Events | 远程服务,HTTP 连接 |
在 OpenClaw 配置文件中添加 MCP Server:
// openclaw.config.js 或配置文件中的 mcpServers 部分
{
"mcpServers": {
// stdio 方式 - 本地进程
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
},
// stdio 方式 - Python 脚本
"my-tool": {
"command": "python",
"args": ["./mcp-server.py"],
"env": {
"API_KEY": "your-api-key"
}
},
// SSE 方式 - 远程服务
"remote-db": {
"url": "https://mcp.example.com/sse",
"headers": {
"Authorization": "Bearer token123"
}
}
}
}
{
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/docs"]
}
}
提供文件读写、目录浏览、文件搜索能力。
{
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb"
}
}
}
{
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "your-brave-api-key"
}
}
}
{
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxxxxxxxxxxx"
}
}
}
// my-mcp-server.py
import asyncio
from mcp import Server, Tool
server = Server("my-custom-tool")
@server.tool()
async def analyze_data(data: str) -> str:
"""分析数据并返回结果"""
# 你的业务逻辑
result = process(data)
return result
if __name__ == "__main__":
asyncio.run(server.run())
配置完成后,Agent 可以直接使用 MCP 工具:
// Agent 自动发现并使用 MCP 工具
// 用户:"帮我读取 /home/user/report.txt 的内容"
// Agent 会自动调用 filesystem MCP 的 readFile 工具
// 查看可用的 MCP 工具
wecom_mcp({ action: "list", category: "filesystem" })
// 调用 MCP 工具
wecom_mcp({
action: "call",
category: "filesystem",
method: "readFile",
args: { path: "/home/user/report.txt" }
})
// ❌ 授予整个文件系统权限
args: ["-y", "@modelcontextprotocol/server-filesystem", "/"]
// ✅ 只授予特定目录权限
args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/docs"]
// ✅ 使用环境变量
env: {
"API_KEY": "${MY_API_KEY}" // 从环境变量读取
}
| 问题 | 可能原因 | 解决方案 |
|---|---|---|
| MCP Server 无法启动 | 命令路径错误 | 检查 command 和 args |
| 工具不可用 | Server 未正确注册工具 | 检查 Server 日志 |
| 连接超时 | 网络问题或 Server 崩溃 | 检查 Server 状态 |
| 权限被拒绝 | 文件/目录权限不足 | 检查文件权限设置 |
可以。OpenClaw 支持同时连接多个 MCP Server,每个 Server 提供独立的工具集。
stdio 方式几乎没有额外开销。SSE 方式会有网络延迟,建议对延迟敏感的场景使用本地 Server。
# 查看 MCP 通信日志
openclaw --debug mcp
# 测试单个 MCP Server
npx @modelcontextprotocol/inspector your-server