Skip to main content
Glama

Clean-Context

Node.js MCP Clients License: MIT

Sistema unificado multi-agente de control de contexto, herencia (handoff), modo Solo / Orquestador y gestión de workers con herdr para Antigravity (agy), Claude Code y Codex, construido sobre un único Servidor MCP Local (Stdio) en Node.js + TypeScript.


Arquitectura

Antigravity (Plugin)  ──┐
Claude Code           ──┤
Codex (config.toml)   ──┼──▶ MCP Stdio Local (dist/index.js)
OpenCode              ──┘       ├── Telemetría: ~/.clean-context/telemetry/*.json
                                ├── OpenCode:   API local en vivo (~/.local/state/opencode/service.json)
                                ├── Codex:      SQLite (~/.codex/state_5.sqlite)
                                ├── Config:     ~/.clean-context/config.json (+ .agents/clean-context.json)
                                ├── Workers:    herdr CLI + ~/.clean-context/workers.json
                                └── Handoff:    .agents/handoff/handoff-*.md + LATEST.md

Herramientas MCP expuestas

Herramienta

Propósito

get_context_status

Lee el statusline de la sesión actual (o SQLite en Codex) y compara % usado vs límite por rol (orchestrator/solo vs worker).

get_config / update_config

Lee o actualiza umbrales (maxContextPercent), modelos y handoffDir de forma global o por proyecto.

herdr_spawn

Divide un pane en herdr e inicia un worker con worker.model y worker.kind, inyectando CLEAN_CONTEXT_ROLE=worker.

herdr_status

Lista panes, agentes vivos en herdr y workers rastreados.

herdr_stop

Cierra limpiamente un worker por nombre o paneId.

herdr_cleanup

Detecta y cierra terminales huérfanas, colgadas o terminadas (done/unknown) con soporte dryRun.

create_handoff / read_handoff

Genera y lee los .md de herencia en .agents/handoff/ con puntero LATEST.md.


Related MCP server: herdr-mcp-server

Configuración por defecto (config.default.json)

{
  "orchestrator": {
    "maxContextPercent": 50,
    "model": "claude-opus-4-5"
  },
  "worker": {
    "maxContextPercent": 25,
    "kind": "opencode",
    "model": "opencode-go/deepseek-v4.1-flash#max",
    "modelFlag": "-m"
  },
  "handoffDir": ".agents/handoff/",
  "telemetryDir": "~/.clean-context/telemetry/"
}
  • Modo Solo: aplica orchestrator.maxContextPercent (50%), higiene de terminales y create_handoff al llegar al umbral sin forzar workers.

  • Modo Orquestador: delega subtareas exclusivamente con herdr_spawn usando worker.model y vigila que ni el orquestador (50%) ni los workers (25%) superen su límite.


Instalación rápida

Requiere pnpm 10+ (corepack enable pnpm si no lo tienes).

pnpm install
pnpm run build
pnpm run install-global

pnpm run install-global (scripts/install.mjs) realiza backups con timestamp antes de modificar archivos y configura automáticamente:

  1. Antigravity: instala el plugin en ~/.gemini/config/plugins/clean-context/ (plugin.json, mcp_config.json, rules/AGENTS.md) y conecta ~/.gemini/antigravity-cli/statusline.js.

  2. Claude Code: registra clean-context en ~/.claude.json, añade las reglas en ~/.claude/CLAUDE.md y conecta ~/.claude/statusline.js.

  3. Codex: registra [mcp_servers.clean-context] en ~/.codex/config.toml y añade las reglas en ~/.codex/AGENTS.md.

También puedes usar el plugin o .mcp.json directamente por proyecto copiando plugins/clean-context/, AGENTS.md, CLAUDE.md y .mcp.json.

OpenCode (bridge en vivo)

install-global no configura OpenCode, porque su MCP vive en ~/.config/opencode/opencode.jsonc y no hay statusline. Dos pasos manuales:

// ~/.config/opencode/opencode.jsonc
"mcp": {
  "servers": {
    "clean-context": {
      "type": "local",
      "command": ["node", "<repo>/dist/index.js"],
      "protocol": "legacy"
    }
  }
}

Y la telemetría: OpenCode no escribe un archivo de statusline, pero src/opencode.ts lee su API local en vivo. get_context_status descubre el servicio en ~/.local/state/opencode/service.json (url + password), resuelve la sesión por cwd y calcula el mismo número que muestra la TUI:

contexto usado = tokens.input + tokens.cache.read   (último mensaje assistant cerrado)
           %   = usado / model.limit.context * 100

Verificado contra la barra de OpenCode: 182.7K (18%) → 182.7K / 1,000,000. Si OpenCode no está corriendo o no hay sesión para ese cwd, cae a las fuentes por archivo (Antigravity, Codex) como siempre.


Pruebas

pnpm test

Ejecuta la suite end-to-end (tests/run-tests.mjs):

  • Generación de telemetría desde statusline.js

  • Conexión MCP stdio real (@modelcontextprotocol/sdk)

  • Validación de umbrales orchestrator vs worker

  • Creación y lectura de handoff en .agents/handoff/

  • Consultas y ciclo real split + herdr_stop contra el servidor herdr activo

Available Tools

9 tools
create_handoffB

Generates a structured Markdown handoff file in handoffDir (plus LATEST.md) capturing summary, decisions, files touched, active workers, and the exact next step.

Inputs: summary (required), nextStep (required), cwd, role, +5 more.

get_configB

Returns the active Context-Clean configuration (merged global + optional project override) and config file paths.

Inputs: cwd.

get_context_statusB

Reads the current agent/session statusline telemetry and compares used context % against the configured limit for the agent's role (orchestrator/solo vs worker).

Inputs: cwd, role, client, sessionId.

herdr_cleanupC

Detects and closes orphaned, dead, or completed worker panes in Herdr, and prunes stale worker records.

Inputs: force, dryRun, includeIdle.

herdr_spawnC

Spawns a worker in a split Herdr pane using the configured worker.model and worker.kind, injecting CONTEXT_CLEAN_ROLE=worker.

Inputs: name (required), cwd, kind, wait, +5 more.

herdr_statusC

Lists live Herdr panes, agents, and tracked Context-Clean workers.

Inputs: name, workspaceId.

herdr_stopC

Cleanly stops a worker by closing its Herdr pane and removing it from tracked workers.

Inputs: name, paneId.

read_handoffC

Reads the latest handoff Markdown file (or a specific handoff file) from handoffDir.

Inputs: cwd, fileName.

update_configC

Updates Context-Clean configuration (maxContextPercent, models, handoffDir) globally or for the current project.

Inputs: cwd, scope, handoffDir, workerKind, +5 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.2/5.0

    Scored across 9 tools

    Disambiguation4/5

    Each tool maps to a recognizable action within one of three clear sub-domains (config, Herdr workers, handoffs/status). The only mild overlap is between herdr_status (pane/worker inventory) and get_context_status (statusline telemetry vs. context limit), but the descriptions make the distinction reasonably clear.

    Naming Consistency4/5

    Most tools follow a predictable verb_noun pattern (get_config, update_config, create_handoff, read_handoff, get_context_status). The Herdr group uses a namespace prefix plus verb (herdr_spawn, herdr_stop, herdr_status, herdr_cleanup), which is a minor but coherent deviation that actually aids grouping.

    Tool Count5/5

    Nine tools is well within the ideal 3-15 range and each one covers a distinct operation: two config, four worker lifecycle, one status check, two handoff operations. No tool feels redundant or superfluous for the stated purpose.

    Completeness4/5

    Worker lifecycle (spawn/status/stop/cleanup) and handoff persistence (create/read) are well covered, and config has read/update. Minor gaps exist: no list_handoffs or handoff pruning, and no config reset/delete, but read_handoff accepts a specific file so agents can work around the listing gap.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables a chat or voice assistant to drive coding agents running in herdr: it can start an agent on a task, list and watch sessions started anywhere, send follow-ups, answer an agent's questions and approve or refuse its permission prompts. Long-running work is reported back through webhook callbacks so the conversation can continue without blocking.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables coordinating local coding agents across Antigravity, DeepSeek Harness, Claude Code, and OpenCode with persistent tasks, live public events, file-change artifacts, session follow-ups, process-tree cancellation, and configurable execution permissions.
      MIT