Skip to content

MCP 系统

MCP (Model Context Protocol) 是 Anthropic 提出的标准化协议,用于定义 AI 模型与外部工具的交互方式。

核心组件

组件文件职责
McpManagersrc/mcp/McpManager.js统一管理所有工具来源
McpClientsrc/mcp/McpClient.jsMCP 客户端,支持多种传输
BuiltinMcpServersrc/mcp/BuiltinMcpServer.js内置工具服务器

McpManager

McpManager 是工具系统的核心,负责:

  • 工具注册与发现
  • 服务器连接管理
  • 工具调用路由
  • 结果缓存
javascript
class McpManager {
  // 工具注册表
  tools = new Map()      // name -> tool definition
  servers = new Map()    // name -> server info
  
  // 初始化
  async init() {
    await this.initBuiltinServer()     // 内置工具
    await this.initCustomToolsServer() // JS 工具
    await this.loadServers()           // 外部服务器
  }
  
  // 统一调用接口
  async callTool(name, args, options) {
    // 1. 查找工具
    const tool = this.tools.get(name)
    if (!tool) throw new Error(`Tool not found: ${name}`)
    
    // 2. 权限检查
    this.checkPermission(tool, options)
    
    // 3. 调用执行
    const result = await this.executeTool(tool, args)
    
    // 4. 记录日志
    this.logExecution(name, args, result)
    
    return result
  }
}

McpClient

McpClient 实现 MCP 协议的客户端,支持四种传输类型。

stdio - 标准输入输出

用于本地进程通信:

javascript
// 配置
{
  type: 'stdio',
  command: 'node',
  args: ['server.js'],
  env: { DEBUG: 'true' }
}

工作流程:

  1. 启动子进程
  2. 通过 stdin/stdout 通信
  3. 使用 JSON-RPC 协议

npm - npm 包

自动安装并运行 npm 包形式的 MCP 服务器:

javascript
// 配置
{
  type: 'npm',
  package: '@anthropic/mcp-server-filesystem',
  args: ['/home/user/documents']
}

支持的热门 npm 包:

  • @anthropic/mcp-server-filesystem - 文件系统访问
  • @modelcontextprotocol/server-memory - 知识图谱
  • @anthropic/mcp-server-brave-search - Brave 搜索

SSE - Server-Sent Events

用于远程服务的实时连接:

javascript
// 配置
{
  type: 'sse',
  url: 'https://mcp.example.com/sse',
  headers: {
    'Authorization': 'Bearer xxx'
  }
}

工作流程:

  1. 连接 SSE 端点
  2. 接收 endpoint 事件获取消息端点
  3. POST 请求发送到消息端点
  4. 通过 SSE 流接收响应

HTTP - Streamable HTTP

用于无状态的 HTTP API:

javascript
// 配置
{
  type: 'http',
  url: 'https://api.example.com/mcp',
  headers: {
    'Authorization': 'Bearer xxx'
  }
}

BuiltinMcpServer

管理内置工具和自定义 JS 工具。25 个内置工具类别由 src/mcp/tools/index.jstoolModules 表统一组织(类别键 → 模块文件/导出名), categoryMeta 提供面板显示元信息:

javascript
// src/mcp/tools/index.js 的核心结构
const toolModules = {
    basic: { file: './basic.js', export: 'basicTools' },
    user: { file: './user.js', export: 'userTools' },
    // ...共 25 类(basic/user/group/message/admin/groupStats/file/web/
    // memory/context/media/search/utils/bot/voice/extra/shell/schedule/
    // bltools/reminder/imageGen/qzone/emoji/skills/knowledgeGraph),
    // schedule 类别映射到 ./nlSchedule.js,message 合并两个导出。
    knowledgeGraph: { file: './knowledgeGraph.js', export: 'knowledgeGraphTools' }
}

// 动态导入 + 秒级缓存(loadToolModules);forceReload 才加时间戳破坏缓存
// getAllTools({ enabledCategories, disabledTools }) 组装最终工具列表

BuiltinMcpServer 侧通过 getCategoryInfo() / getAllTools() 消费这些类别, 负责注册、启用/禁用过滤与热重载。具体类别与工具清单见 内置工具

工具定义格式

javascript
{
  name: 'get_current_time',
  description: '获取当前时间',
  category: 'basic',
  
  parameters: {
    type: 'object',
    properties: {
      timezone: {
        type: 'string',
        description: '时区,如 Asia/Shanghai'
      }
    },
    required: []
  },
  
  async execute(args, context) {
    const tz = args.timezone || 'Asia/Shanghai'
    return new Date().toLocaleString('zh-CN', { timeZone: tz })
  }
}

连接生命周期

工具执行流程

下一步

基于 MIT 许可发布