Skip to content
Snow leopard edited this page Jul 16, 2026 · 1 revision

Extensions

Extending CogitoAgent with Plugins, MCP, and More

使用插件、MCP 等扩展 CogitoAgent


CogitoAgent provides multiple extension mechanisms to customize and enhance its capabilities. This page covers the Plugin System, MCP Protocol, Tracing, Retry & Circuit Breaker, and Multi-Model Support.

CogitoAgent 提供了多种扩展机制来定制和增强其能力。本页涵盖了插件系统、MCP 协议、追踪、重试与熔断以及多模型支持。


Extension Architecture | 扩展架构

flowchart TB
    subgraph CORE["Core Agent | 核心"]
        AGENT["Agent.ts<br/>Think Cycle"]
        REGISTRY["registry.ts<br/>Tool Registry"]
    end

    subgraph EXT["Extension Layer | 扩展层"]
        PLUGIN["plugin.ts<br/>Plugin System"]
        MCP["mcp.ts<br/>MCP Server :3001"]
        WECHAT["wechat-manager.ts<br/>WeChat Channel"]
        CLUSTER["orchestrator.ts<br/>Agent Cluster"]
        RETRY["retry.ts<br/>Circuit Breaker"]
        TRACING["tracing.ts<br/>Observability"]
    end

    subgraph EXTERNAL["External | 外部"]
        PLUGIN_DIR["plugins/<br/>Custom Plugins"]
        MCP_CLIENT["MCP Clients<br/>JSON-RPC"]
        WECHAT_API["WeChat iLink<br/>微信"]
        TOOLS["Tool Modules<br/>28 Categories"]
    end

    AGENT --> PLUGIN
    AGENT --> MCP
    AGENT --> WECHAT
    AGENT --> CLUSTER
    AGENT --> RETRY
    AGENT --> TRACING

    PLUGIN --> PLUGIN_DIR
    MCP --> MCP_CLIENT
    WECHAT --> WECHAT_API
    CLUSTER --> TOOLS
    RETRY --> TOOLS

    classDef core fill:#1a2332,stroke:#5eead4,color:#5eead4
    classDef ext fill:#1a2332,stroke:#a78bfa,color:#a78bfa
    classDef external fill:#1a2332,stroke:#94a3b8,color:#94a3b8

    class AGENT,REGISTRY core
    class PLUGIN,MCP,WECHAT,CLUSTER,RETRY,TRACING ext
    class PLUGIN_DIR,MCP_CLIENT,WECHAT_API,TOOLS external
Loading

1. Plugin System | 插件系统

The plugin system allows you to add custom tools without modifying the core codebase. Plugins are loaded dynamically from the plugins/ directory.

插件系统允许您在不修改核心代码的情况下添加自定义工具。插件从 plugins/ 目录动态加载。

Plugin Directory Structure | 插件目录结构

plugins/
├── my-plugin/
│   ├── index.js          # Plugin entry | 插件入口
│   └── package.json      # Plugin metadata | 插件元数据(可选)
└── another-plugin/
    └── index.js

Plugin Format | 插件格式

/**
 * my-plugin/index.js
 * Custom plugin for CogitoAgent
 */

export default [
  {
    name: 'weather',
    description: 'Get weather information for a city',
    category: 'web',
    fn: async (city) => {
      // Implementation | 实现逻辑
      return { success: true, data: `Weather in ${city}: Sunny, 25°C` };
    }
  },
  {
    name: 'translate',
    description: 'Translate text between languages',
    category: 'custom',
    fn: async (text, from, to) => {
      // Implementation | 实现逻辑
      return { success: true, data: `Translated: ${text}` };
    }
  }
];

export const metadata = {
  name: 'my-plugin',
  version: '1.0.0',
  author: 'Your Name',
  description: 'A custom plugin for CogitoAgent'
};

Plugin Registration Flow | 插件注册流程

flowchart LR
    START["Startup | 启动"] --> SCAN["Scan plugins/<br/>扫描插件目录"]
    SCAN --> LOAD["Load index.js<br/>加载入口文件"]

    LOAD --> VALIDATE["Validate format<br/>验证格式"]
    VALIDATE --> REGISTER["Register tools<br/>注册工具到 TOOL_REGISTRY"]
    REGISTER --> READY["Ready for use<br/>准备就绪"]

    subgraph USER["User Usage | 用户使用"]
        CALL["[TOOL] weather('Beijing') [/TOOL]"]
        EXEC["Execute plugin tool<br/>执行插件工具"]
    end

    READY --> CALL
    CALL --> EXEC

    classDef load fill:#1a2332,stroke:#fbbf24,color:#fbbf24
    classDef reg fill:#1a2332,stroke:#5eead4,color:#5eead4
    classDef use fill:#1a2332,stroke:#38bdf8,color:#38bdf8

    class START,SCAN,LOAD,VALIDATE load
    class REGISTER,READY reg
    class CALL,EXEC use
Loading

Plugin Management | 插件管理

Function Description 说明
loadAll() Load all plugins from plugins/ directory 从 plugins/ 目录加载所有插件
loadPlugin(name) Load a specific plugin 加载指定插件
unloadPlugin(name) Unload a plugin 卸载插件
listPlugins() List all loaded plugins 列出所有已加载插件
listCustomTools() List all custom tools 列出所有自定义工具

Creating a Plugin | 创建插件

  1. Create a directory in plugins/ with your plugin name

  2. Create index.js with the format shown above

  3. Restart CogitoAgent or use /tools to verify

  4. Use your custom tool with [TOOL] yourTool(args) [/TOOL]

  5. 在 plugins/ 中创建一个以插件名称命名的目录

  6. 创建 index.js,格式如上所示

  7. 重启 CogitoAgent 或使用 /tools 验证

  8. 使用 [TOOL] yourTool(args) [/TOOL] 调用您的自定义工具


2. MCP Protocol | MCP 协议

MCP (Model Context Protocol) exposes CogitoAgent's tools as a JSON-RPC 2.0 service, allowing other AI clients to discover and call tools.

MCP(Model Context Protocol)将 CogitoAgent 的工具暴露为 JSON-RPC 2.0 服务,允许其他 AI 客户端发现和调用工具。

MCP Server | MCP 服务器

The MCP server runs on port 3001 by default and supports the following methods:

MCP 服务器默认运行在端口 3001,支持以下方法:

Method Description 说明
initialize Initialize connection 初始化连接
tools/list List all available tools 列出所有可用工具
tools/call Call a specific tool 调用指定工具
resources/list List available resources 列出可用资源
resources/read Read resource content 读取资源内容
prompts/list List available prompts 列出可用提示词
shutdown Shutdown server 关闭服务器

MCP Architecture | MCP 架构

flowchart LR
    subgraph COGITO["CogitoAgent"]
        REGISTRY["TOOL_REGISTRY<br/>160+ Tools"]
        MCP_SERVER["mcp.ts<br/>JSON-RPC 2.0"]
    end

    subgraph CLIENTS["MCP Clients"]
        CLAUDE["Claude Desktop"]
        CONTINUE["Continue.dev"]
        CUSTOM["Custom Clients"]
        VSCODE["VS Code<br/>(via MCP plugin)"]
    end

    REGISTRY --> MCP_SERVER
    MCP_SERVER -->|"JSON-RPC"| CLIENTS

    classDef cogito fill:#1a2332,stroke:#5eead4,color:#5eead4
    classDef clients fill:#1a2332,stroke:#a78bfa,color:#a78bfa

    class REGISTRY,MCP_SERVER cogito
    class CLAUDE,CONTINUE,CUSTOM,VSCODE clients
Loading

Example: Calling a Tool via MCP | 示例:通过 MCP 调用工具

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "ls",
    "arguments": {
      "args": ["."]
    }
  }
}

MCP Response | MCP 响应

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "[\n  { \"name\": \"src\", \"type\": \"dir\" },\n  { \"name\": \"README.md\", \"type\": \"file\" }\n]"
      }
    ],
    "isError": false
  }
}

Enabling MCP | 启用 MCP

The MCP server starts automatically with CogitoAgent. To disable it:

MCP 服务器随 CogitoAgent 自动启动。要禁用它:

# In .env
DISABLE_MCP=true

3. Tracing & Observability | 追踪与可观测性

The tracing module provides lightweight observability for tool executions, LLM calls, and state transitions.

追踪模块为工具执行、LLM 调用和状态转换提供轻量级可观测性。

Trace Events | 追踪事件

flowchart LR
    subgraph EVENTS["Trace Events | 追踪事件"]
        TOOL["tool_exec<br/>工具执行"]
        LLM["llm_call<br/>LLM 调用"]
        STATE["state_change<br/>状态转换"]
        SESSION["session_start/end<br/>会话开始/结束"]
        ERROR["error<br/>错误"]
    end

    subgraph OUTPUT["Output | 输出"]
        CONSOLE["Console | 控制台"]
        FILE["File | 文件<br/>data/logs/"]
    end

    EVENTS --> CONSOLE
    EVENTS --> FILE

    classDef events fill:#1a2332,stroke:#fbbf24,color:#fbbf24
    classDef output fill:#1a2332,stroke:#5eead4,color:#5eead4

    class TOOL,LLM,STATE,SESSION,ERROR events
    class CONSOLE,FILE output
Loading

Trace Functions | 追踪函数

Function Description 说明
traceToolExec(toolName, args, result, duration, success) Record tool execution 记录工具执行
traceLLMCall(model, inputLength, outputLength, duration, tokens) Record LLM call 记录 LLM 调用
traceStateChange(from, to, reason) Record state change 记录状态转换
traceError(error, context) Record error 记录错误
getStats() Get trace statistics 获取追踪统计
saveTraces() Save traces to file 保存追踪到文件

Trace Output Example | 追踪输出示例

[TRACE:tool_exec] ls (12ms)
[TRACE:tool_exec] read (3ms)
[TRACE:llm_call] gpt-4o (156ms, tokens: 245/320)
[TRACE:state_change] AWAITING_INPUT → THINKING

Configuration | 配置

# Enable/disable tracing
ENABLE_TRACING=true

# Trace level: debug, info, warn, error
LOG_LEVEL=info

4. Retry & Circuit Breaker | 重试与熔断

The retry module provides reliable network requests with exponential backoff and circuit breaker protection.

重试模块提供可靠的网络请求,带有指数退避和熔断器保护。

Retry Mechanism | 重试机制

flowchart TD
    START["Request | 请求"] --> ATTEMPT["Attempt N<br/>第 N 次尝试"]

    ATTEMPT --> SUCCESS{"Success?<br/>成功?"}

    SUCCESS -->|"Yes | 是"| DONE["Done | 完成"]

    SUCCESS -->|"No | 否"| RETRYABLE{"Retryable error?<br/>可重试错误?"}

    RETRYABLE -->|"No | 否"| FAIL["Fail | 失败"]

    RETRYABLE -->|"Yes | 是"| MAX{"Max retries?<br/>达到最大重试次数?"}

    MAX -->|"Yes | 是"| FAIL
    MAX -->|"No | 否"| DELAY["Delay: 2^n * base<br/>延迟: 2^n × 基础"]

    DELAY --> ATTEMPT

    classDef start fill:#1a2332,stroke:#5eead4,color:#5eead4
    classDef process fill:#1a2332,stroke:#fbbf24,color:#fbbf24
    classDef decision fill:#1a2332,stroke:#f87171,color:#f87171

    class START,ATTEMPT,DELAY process
    class SUCCESS,MAX,RETRYABLE decision
    class DONE,FAIL start
Loading

Retry Configuration | 重试配置

Parameter Default Description
maxRetries 3 Maximum number of retry attempts
initialDelay 1000ms Initial delay between retries
maxDelay 10000ms Maximum delay cap
backoffMultiplier 2 Exponential backoff factor
retryableErrors Network errors Errors that trigger retry
参数 默认值 说明
maxRetries 3 最大重试次数
initialDelay 1000ms 重试之间的初始延迟
maxDelay 10000ms 最大延迟上限
backoffMultiplier 2 指数退避因子
retryableErrors 网络错误 触发重试的错误类型

Circuit Breaker | 熔断器

The circuit breaker prevents cascading failures by stopping requests to a failing service.

熔断器通过停止对故障服务的请求来防止级联故障。

State Description 说明
CLOSED Normal operation — requests allowed 正常——允许请求
OPEN Circuit open — requests blocked 熔断开启——请求被阻止
HALF_OPEN Testing recovery — limited requests allowed 半开——允许有限请求

Circuit Breaker Flow | 熔断器流程

stateDiagram-v2
    [*] --> CLOSED

    CLOSED --> OPEN: Failure threshold reached<br/>达到失败阈值
    OPEN --> HALF_OPEN: Timeout elapsed<br/>超时时间到
    HALF_OPEN --> CLOSED: Success<br/>成功
    HALF_OPEN --> OPEN: Failure<br/>失败

    classDef closed fill:#5eead4,color:#0b0e14
    classDef open fill:#f87171,color:#0b0e14
    classDef half fill:#fbbf24,color:#0b0e14

    class CLOSED closed
    class OPEN open
    class HALF_OPEN half
Loading

5. Multi-Model Support | 多模型支持

CogitoAgent supports multiple LLM providers through a unified API client.

CogitoAgent 通过统一的 API 客户端支持多个 LLM 提供商。

Supported Providers | 支持的提供商

Provider Base URL Models
OpenAI https://api.openai.com/v1 gpt-4o, gpt-4o-mini, gpt-4-turbo
Moark https://api.moark.com/v1 DeepSeek-V4-Flash, DeepSeek-V4
Anthropic https://api.anthropic.com/v1 claude-3-opus, claude-3-sonnet, claude-3-haiku
Google https://generativelanguage.googleapis.com/v1beta gemini-1.5-pro, gemini-1.5-flash
Custom Any OpenAI-compatible endpoint Any model

Configuration | 配置

# Primary model
COGITO_API_PROVIDER=openai
COGITO_API_BASE_URL=https://api.openai.com/v1
COGITO_API_KEY=your-key
COGITO_MODEL=gpt-4o

# Multi-model keys (optional)
COGITO_OPENAI_API_KEY=your-openai-key
COGITO_MOARK_API_KEY=your-moark-key
COGITO_ANTHROPIC_API_KEY=your-anthropic-key
COGITO_GOOGLE_API_KEY=your-google-key

Switching Models | 切换模型

Model switching can be done via command line or environment variables.

可以通过命令行或环境变量切换模型。

# CLI mode
npm run cli -- --model claude-3-sonnet --provider anthropic

# Or via environment
COGITO_API_PROVIDER=anthropic
COGITO_MODEL=claude-3-sonnet

6. Web Search | 联网搜索

CogitoAgent includes built-in web search capabilities through the search tool.

CogitoAgent 通过 search 工具包含内置的联网搜索能力。

Search Configuration | 搜索配置

{
  "search": {
    "enabled": true,
    "baseURL": "https://api.moark.com/v1/web-search-v2",
    "recencyFilter": "",
    "siteFilter": ""
  }
}
# Environment variables
COGITO_SEARCH_ENABLED=true
COGITO_SEARCH_BASE_URL=https://api.moark.com/v1/web-search-v2

Search Usage | 搜索使用

[TOOL] search("latest TypeScript features") [/TOOL]

Extension Summary | 扩展总结

Extension Purpose Key Feature
Plugin System Add custom tools Dynamic loading from plugins/
MCP Protocol External tool access JSON-RPC 2.0 on port 3001
Tracing Observability Tool/LLM execution tracking
Retry & Circuit Breaker Reliability Exponential backoff, failure isolation
Multi-Model Flexibility Multiple LLM providers
Web Search Information Internet search capability
扩展 用途 关键特性
插件系统 添加自定义工具 从 plugins/ 动态加载
MCP 协议 外部工具访问 端口 3001 的 JSON-RPC 2.0
追踪 可观测性 工具/LLM 执行追踪
重试与熔断 可靠性 指数退避、故障隔离
多模型 灵活性 多个 LLM 提供商
联网搜索 信息获取 互联网搜索能力

Next Steps | 下一步


Previous: Tools →

Next: Agent Cluster →

上一篇: 工具列表 →

下一篇: 智能体集群 →

Clone this wiki locally