🔌 MCP 协议完全指南

Model Context Protocol | 让 AI Agent 与工具无缝连接

37天

距离 MCP 无状态化 RC 截止还有 37 天(2026年7月28日)

📌 什么是 MCP?

MCP(Model Context Protocol)是一个开放的协议标准,用于AI Agent 与外部工具之间的通信。它定义了 Agent 如何发现、调用和管理工具,使得不同的 AI 模型可以共享同一套工具生态。

🔧 工具发现

Agent 可以自动发现可用的工具,无需硬编码。

📡 统一通信

所有工具使用统一的协议进行通信,简化集成。

🛡️ 安全控制

内置权限管理和安全验证机制。

🔄 状态管理

支持有状态和无状态两种模式,灵活适应不同场景。

🚀 快速开始

1. 安装 MCP SDK

# 使用 npm 安装
npm install @modelcontextprotocol/sdk

# 或使用 pnpm
pnpm add @modelcontextprotocol/sdk

2. 创建 MCP 服务器

// server.js
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new McpServer({
    name: 'my-mcp-server',
    version: '1.0.0'
});

// 定义工具
server.tool('calculator', {
    description: '执行数学计算',
    parameters: {
        type: 'object',
        properties: {
            expression: { type: 'string', description: '数学表达式' }
        },
        required: ['expression']
    }
}, async ({ expression }) => {
    const result = eval(expression);
    return { content: [{ type: 'text', text: String(result) }] };
});

// 启动服务器
const transport = new StdioServerTransport();
await server.connect(transport);

3. 连接 MCP 服务器

# 在 OpenClaw 配置中添加 MCP 服务器
# ~/.openclaw/config.yaml
mcp:
  servers:
    - name: my-mcp-server
      command: node
      args: [server.js]
      transport: stdio

📋 核心概念

工具(Tools)

工具是 MCP 的核心概念,它代表 Agent 可以调用的一个功能。每个工具都有:

资源(Resources)

资源是 Agent 可以读取的数据源,例如文件、数据库记录等。

// 定义资源
server.resource('config', 'config://app', async () => {
    return {
        contents: [{
            uri: 'config://app',
            text: JSON.stringify({ theme: 'dark', language: 'zh' })
        }]
    };
});

提示(Prompts)

提示是预定义的对话模板,用于引导 Agent 的行为。

// 定义提示
server.prompt('code-review', {
    description: '代码审查提示',
    parameters: {
        code: { type: 'string', description: '要审查的代码' }
    }
}, async ({ code }) => {
    return {
        messages: [{
            role: 'user',
            content: { type: 'text', text: `请审查以下代码:\n${code}` }
        }]
    };
});

⚡ 无状态化迁移

⚠️ 重要:MCP 无状态化 RC 截止日期为 2026年7月28日,剩余 37 天。所有 MCP 服务器需要在此之前完成无状态化迁移。

无状态化意味着 MCP 服务器不再依赖本地状态,所有状态都由客户端管理。这带来了以下好处:

# 迁移检查清单
openclaw mcp migrate-check my-server

# 输出
[✓] 工具定义无状态化
[✓] 资源访问无状态化
[✓] 会话管理客户端化
[!] 发现本地状态依赖: ./data/cache.json
[建议] 将缓存迁移到客户端或外部存储

🔒 工具安全

MCP 协议内置了多重安全机制:

# 验证工具签名
openclaw mcp verify my-server --tool calculator

# 查看调用记录
openclaw mcp audit my-server --last 50

🎯 最佳实践

1. 工具设计原则

2. 性能优化

3. 安全建议

🔗 相关资源

🔌 开始使用 MCP 协议

访问 MCP 官网 了解更多,或在 ClawHub 上找到支持 MCP 的工具。

MCP 官网 → | GitHub 仓库 →