🔌 MCP 模型上下文协议

Anthropic 开源标准 2024 协议层
🆕 2024年 Anthropic 重磅开源
MCP(Model Context Protocol)是 Anthropic 推出的开放标准,旨在统一 LLM 与外部数据源、工具的连接方式。

世界上有一种语言叫MCP,它是AI和工具之间的通用翻译器。
就像USB统一了设备连接,MCP正在统一AI与世界的连接方式。

📚 什么是 MCP?

MCP(Model Context Protocol,模型上下文协议)是由 Anthropic 于 2024 年底开源的标准协议,用于标准化大型语言模型(LLM)与外部数据源、工具、服务之间的通信。

简单来说:MCP 是 AI 应用的"USB-C"接口

核心目标

  • 🔌 标准化连接 - 统一的接口规范
  • 🔒 安全通信 - 内置权限和认证机制
  • 🔄 双向传输 - 支持上下文的双向流动
  • 🧩 模块化设计 - 即插即用的组件架构

⚙️ 架构设计

MCP 核心组件

┌─────────────────────────────────────────────────────────┐
│                      MCP Host                           │
│                  (AI应用/IDE/Agent)                      │
└─────────────────────────┬───────────────────────────────┘
                          │ MCP Protocol (JSON-RPC)
                          ▼
┌─────────────────────────────────────────────────────────┐
│                     MCP Server                          │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐  │
│  │   Tools     │  │  Resources  │  │     Prompts     │  │
│  │  (function) │  │  (context)  │  │  (templates)    │  │
│  └─────────────┘  └─────────────┘  └─────────────────┘  │
└─────────────────────────────────────────────────────────┘
                          │
              ┌───────────┼───────────┐
              ▼           ▼           ▼
         [Database]  [API Service]  [File System]

三种核心能力

能力 描述 示例
Tools 执行函数,修改外部状态 发送邮件、创建文件、调用API
Resources 只读数据,提供上下文 读取文件、查询数据库、获取日志
Prompts 可复用的提示模板 代码审查模板、PR描述模板

⚖️ MCP vs Function Calling

MCP 和 Function Calling 不是竞争关系,而是互补的层次

特性 Function Calling MCP
层级 模型能力层 协议层
范围 单轮对话内的工具调用 完整的客户端-服务器协议
上下文 有限的token窗口 支持大型上下文管理
状态 无状态 支持会话状态
安全性 需自行实现 内置权限控制
生态 各平台独立 标准化,可共享
💡 一句话理解
Function Calling 是"能力",MCP 是"标准协议"。
MCP 使用 Function Calling 来实现工具调用,但提供了更完整的生态和标准。

📡 协议细节

通信流程

1. 初始化
   Host → Server: initialize (capabilities, protocolVersion)
   Server → Host: initialize (capabilities, serverInfo)

2. 能力协商
   Host 和 Server 交换支持的功能列表

3. 正常通信
   Host → Server: tools/list
   Server → Host: 返回可用工具列表
   
   Host → Server: tools/call (name, arguments)
   Server → Host: 返回执行结果

4. 资源订阅(可选)
   Host → Server: resources/subscribe (uri)
   Server → Host: 资源变更通知

消息格式(JSON-RPC)

// 请求
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "read_file",
    "arguments": {
      "path": "/tmp/example.txt"
    }
  }
}

// 响应
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "文件内容..."
      }
    ]
  }
}

🚀 OpenClaw + MCP 实战

使用 MCP Server

import { Agent } from '@openclaw/core';
import { MCPClient } from '@openclaw/mcp';

const agent = new Agent({
  name: 'mcp_enabled_agent',
  model: 'claude-3-5-sonnet'
});

// 连接 MCP Server
const mcpClient = new MCPClient({
  serverCommand: 'npx -y @modelcontextprotocol/server-filesystem',
  args: ['/home/user/projects']
});

await mcpClient.connect();

// 获取可用工具
const tools = await mcpClient.listTools();
console.log('可用工具:', tools.map(t => t.name));
// ["read_file", "write_file", "list_directory", ...]

// 在Agent中使用MCP工具
agent.addTools(mcpClient.getToolHandlers());

// 现在Agent可以使用文件系统工具了
const result = await agent.run('查看项目目录下的README文件并总结内容');

开发自定义 MCP Server

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';

// 创建 MCP Server
const server = new Server(
  {
    name: 'my-custom-server',
    version: '1.0.0',
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// 定义可用工具
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: 'query_database',
        description: '查询数据库',
        inputSchema: {
          type: 'object',
          properties: {
            sql: { type: 'string', description: 'SQL查询语句' }
          },
          required: ['sql']
        }
      }
    ]
  };
});

// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === 'query_database') {
    const { sql } = request.params.arguments;
    const result = await db.query(sql);
    
    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(result, null, 2)
        }
      ]
    };
  }
  
  throw new Error('未知工具');
});

// 启动服务器
const transport = new StdioServerTransport();
await server.connect(transport);
console.log('MCP Server running...');

MCP 配置示例

// mcp-config.json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/db"]
    }
  }
}

🌐 MCP 生态

官方 Server 列表

  • @modelcontextprotocol/server-filesystem - 文件系统操作
  • @modelcontextprotocol/server-github - GitHub API
  • @modelcontextprotocol/server-postgres - PostgreSQL 数据库
  • @modelcontextprotocol/server-sqlite - SQLite 数据库
  • @modelcontextprotocol/server-puppeteer - 浏览器自动化

使用场景

  • IDE集成 - Cursor、Claude Desktop 等工具使用 MCP 连接代码库
  • 数据分析 - 连接数据库进行自然语言查询
  • DevOps - 操作 Kubernetes、Docker、云服务
  • 内容创作 - 管理文档、图片、媒体资源