$ ssh clawdbot.space --loading...
$ ssh clawdbot.space --loading...
创建自定义 MCP 服务器,赋予代理超能力 — API、数据库、IoT 等。
MCP(模型上下文协议)服务器让 OpenClaw 代理通过标准化工具与外部服务交互。你构建一个干净的服务器,暴露类型化工具供代理可靠调用。本指南从零开始教你构建第一个 MCP 服务器。
MCP 定义了 LLM 与工具通信的 JSON-RPC 协议。代理发现可用工具、理解参数、类型安全地调用。
用 Python (FastMCP)、TypeScript (MCP SDK) 或任何支持 JSON-RPC 的语言构建。
每个 MCP 服务器处理一个领域。组合多个服务器:邮件、日历、智能家居各一个。
安装 FastMCP 框架
pip install fastmcp
创建最小 MCP 服务器
# server.py
from fastmcp import FastMCP
mcp = FastMCP("weather")
@mcp.tool()
def get_weather(city: str) -> str:
"""获取城市当前天气。"""
return f"{city}天气: 22°C, 晴"
if __name__ == "__main__":
mcp.run()在 OpenClaw 配置中注册
# openclaw.config.yaml
mcp_servers:
weather:
command: python
args: [server.py]测试工具
openclaw mcp list weather get_weather --city 东京
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "weather", version: "1.0.0" });
server.tool("get_weather",
{ city: z.string().describe("城市名") },
async ({ city }) => ({
content: [{ type: "text", text: `${city}天气: 22°C` }]
})
);
await server.connect(new StdioServerTransport());包装 REST API(GitHub、Jira、Slack)。处理认证、分页、限速。
get_issues, create_pr, send_message暴露只读 SQL 查询。始终使用参数化查询。写入需审批。
query_customers, get_order_status通过 MQTT 或 HTTP 控制智能家居。包含安全约束。
set_thermostat, toggle_lightsPDF 解析、图像分析、数据转换。返回结构化结果。
parse_invoice, extract_table