RepoDepot
MCP Server

context-mode

by mksglu
MCP server for AI agent context optimization — sandboxes tool output, indexes session events, and retrieves relevant data

Context Mode is an MCP server that optimizes AI agent context windows by sandboxing verbose tool outputs and intelligently managing session data. It reduces context usage by up to 98% by indexing all file edits, git operations, and task events into an FTS5 database. The server retrieves only relevant information via BM25 search, ensuring session continuity and enabling agents to "think in code" by generating scripts instead of processing raw data.

View on GitHub ↗
Key features
  • Sandboxes tool output, reducing context window usage by up to 98%
  • Indexes all session events (edits, tasks, errors) into FTS5
  • Retrieves relevant session data using BM25 search during compaction
  • Promotes 'think in code' paradigm for efficient agent analysis
  • Offers diagnostic and utility slash commands for Claude Code
Languages
TypeScript53%JavaScript44%Shell2%HTML1%CSS0%
Top contributors
Topics
antigravityclaudeclaude-codeclaude-code-hooksclaude-code-pluginsclaude-code-skillcodexcodex-clicontext-modecopilotcursor-pluginkiromcpmcp-servermcp-toolsopenclawopencodepi-agentskillszed-extension

Context Mode

The other half of the context problem.

users npm marketplace GitHub stars GitHub forks Last commit License: ELv2 Discord Hacker News #1

Used across teams at

Microsoft Google Meta Amazon IBM NVIDIA ByteDance Stripe Datadog Salesforce GitHub Red Hat Supabase Canva Notion Hasura Framer Cursor

The Problem

Every MCP tool call dumps raw data into your context window. A Playwright snapshot costs 56 KB. Twenty GitHub issues cost 59 KB. One access log — 45 KB. After 30 minutes, 40% of your context is gone. And when the agent compacts the conversation to free space, it forgets which files it was editing, what tasks are in progress, and what you last asked for.

Context Mode is an MCP server that solves all three sides of this problem:

  1. Context Saving — Sandbox tools keep raw data out of the context window. 315 KB becomes 5.4 KB. 98% reduction.
  2. Session Continuity — Every file edit, git operation, task, error, and user decision is tracked in SQLite. When the conversation compacts, context-mode doesn't dump this data back into context — it indexes events into FTS5 and retrieves only what's relevant via BM25 search. The model picks up exactly where you left off. If you don't --continue, previous session data is deleted immediately — a fresh session means a clean slate.
  3. Think in Code — The LLM should program the analysis, not compute it. Instead of reading 50 files into context to count functions, the agent writes a script that does the counting and console.log()s only the result. One script replaces ten tool calls and saves 100x context. This is a mandatory paradigm across all 12 platforms: stop treating the LLM as a data processor, treat it as a code generator.
Watch context-mode demo on YouTube

Watch on YouTube

Install

Platforms are grouped by install complexity. Hook-capable platforms get automatic routing enforcement. Non-hook platforms need a one-time routing file copy.

Claude Code — plugin marketplace, fully automatic

Prerequisites: Claude Code v1.0.33+ (claude --version). If /plugin is not recognized, update first: brew upgrade claude-code or npm update -g @anthropic-ai/claude-code.

Install:

/plugin marketplace add mksglu/context-mode
/plugin install context-mode@context-mode

Restart Claude Code (or run /reload-plugins).

Verify:

/context-mode:ctx-doctor

All checks should show [x]. The doctor validates runtimes, hooks, FTS5, and plugin registration.

Routing: Automatic. The SessionStart hook injects routing instructions at runtime — no file is written to your project. The plugin registers all hooks (PreToolUse, PostToolUse, PreCompact, SessionStart) and 6 sandbox tools (ctx_batch_execute, ctx_execute, ctx_execute_file, ctx_index, ctx_search, ctx_fetch_and_index) plus meta-tools (ctx_stats, ctx_doctor, ctx_upgrade, ctx_purge, ctx_insight).

Slash Command What it does
/context-mode:ctx-stats Context savings — per-tool breakdown, tokens consumed, savings ratio.
/context-mode:ctx-doctor Diagnostics — runtimes, hooks, FTS5, plugin registration, versions.
/context-mode:ctx-upgrade Pull latest, rebuild, migrate cache, fix hooks.
/context-mode:ctx-purge Permanently delete all indexed content from the knowledge base.
/context-mode:ctx-insight Personal analytics dashboard — 15+ metrics on tool usage, session activity, error rate, parallel work patterns, and mastery curve. Opens a local web UI.

Note: Slash commands are a Claude Code plugin feature. On other platforms, type ctx stats, ctx doctor, ctx upgrade, or ctx insight in the chat — the model calls the MCP tool automatically. See Utility Commands.

Alternative — MCP-only install (no hooks or slash commands)
claude mcp add context-mode -- npx -y context-mode

This gives you the 6 sandbox tools without automatic routing. The model can still use them — it just won't be nudged to prefer them over raw Bash/Read/WebFetch. Good for trying it out before committing to the full plugin.

Gemini CLI — one config file, hooks included

Prerequisites: Node.js 18+, Gemini CLI installed.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Add the following to ~/.gemini/settings.json. This single file registers the MCP server and all four hooks:

    {
      "mcpServers": {
        "context-mode": {
          "command": "context-mode"
        }
      },
      "hooks": {
        "BeforeTool": [
          {
            "matcher": "run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode",
            "hooks": [{ "type": "command", "command": "context-mode hook gemini-cli beforetool" }]
          }
        ],
        "AfterTool": [
          {
            "matcher": "",
            "hooks": [{ "type": "command", "command": "context-mode hook gemini-cli aftertool" }]
          }
        ],
        "PreCompress": [
          {
            "matcher": "",
            "hooks": [{ "type": "command", "command": "context-mode hook gemini-cli precompress" }]
          }
        ],
        "SessionStart": [
          {
            "matcher": "",
            "hooks": [{ "type": "command", "command": "context-mode hook gemini-cli sessionstart" }]
          }
        ]
      }
    }
    
  3. Restart Gemini CLI.

Verify:

/mcp list

You should see context-mode: ... - Connected.

Routing: Automatic. The SessionStart hook injects routing instructions at runtime — no GEMINI.md file is written to your project. All four hooks (BeforeTool, AfterTool, PreCompress, SessionStart) handle enforcement programmatically.

Why the BeforeTool matcher? It targets only tools that produce large output (run_shell_command, read_file, read_many_files, grep_search, search_file_content, web_fetch, activate_skill) plus context-mode's own tools (mcp__plugin_context-mode). This avoids unnecessary hook overhead on lightweight tools while intercepting every tool that could flood your context window.

Full config reference: configs/gemini-cli/settings.json

VS Code Copilot — hooks with SessionStart

Prerequisites: Node.js 18+, VS Code with Copilot Chat v0.32+.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Create .vscode/mcp.json in your project root:

    {
      "servers": {
        "context-mode": {
          "command": "context-mode"
        }
      }
    }
    
  3. Create .github/hooks/context-mode.json:

    {
      "hooks": {
        "PreToolUse": [
          { "type": "command", "command": "context-mode hook vscode-copilot pretooluse" }
        ],
        "PostToolUse": [
          { "type": "command", "command": "context-mode hook vscode-copilot posttooluse" }
        ],
        "SessionStart": [
          { "type": "command", "command": "context-mode hook vscode-copilot sessionstart" }
        ]
      }
    }
    
  4. Restart VS Code.

Verify: Open Copilot Chat and type ctx stats. Context-mode tools should appear and respond.

Routing: Automatic. The SessionStart hook injects routing instructions at runtime — no copilot-instructions.md file is written to your project.

Full hook config including PreCompact: configs/vscode-copilot/hooks.json

Cursor — hooks with stop support

Prerequisites: Node.js 18+, Cursor with agent mode.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Create .cursor/mcp.json in your project root (or ~/.cursor/mcp.json for global):

    {
      "mcpServers": {
        "context-mode": {
          "command": "context-mode"
        }
      }
    }
    
  3. Create .cursor/hooks.json (or ~/.cursor/hooks.json for global):

    {
      "version": 1,
      "hooks": {
        "preToolUse": [
          {
            "command": "context-mode hook cursor pretooluse",
            "matcher": "Shell|Read|Grep|WebFetch|Task|MCP:ctx_execute|MCP:ctx_execute_file|MCP:ctx_batch_execute"
          }
        ],
        "postToolUse": [
          {
            "command": "context-mode hook cursor posttooluse"
          }
        ],
        "stop": [
          {
            "command": "context-mode hook cursor stop"
          }
        ]
      }
    }
    

    The preToolUse matcher is optional — without it, the hook fires on all tools. The stop hook fires when the agent turn ends and can send a followup message to continue the loop. afterAgentResponse is also available (fire-and-forget, receives full response text).

  4. Copy the routing rules file. Cursor lacks a SessionStart hook, so the model needs a rules file for routing awareness:

    mkdir -p .cursor/rules
    cp node_modules/context-mode/configs/cursor/context-mode.mdc .cursor/rules/context-mode.mdc
    
  5. Restart Cursor or open a new agent session.

Verify: Open Cursor Settings > MCP and confirm "context-mode" shows as connected. In agent chat, type ctx stats.

Routing: Hooks enforce routing programmatically via preToolUse/postToolUse/stop. The .cursor/rules/context-mode.mdc file provides routing instructions at session start since Cursor's sessionStart hook is currently rejected by their validator (forum report). Project .cursor/hooks.json overrides ~/.cursor/hooks.json.

Known limitation: Cursor accepts additional_context in hook responses but does not surface it to the model (forum #155689). Routing relies on the .mdc rules file instead of hook context injection.

Full configs: configs/cursor/hooks.json | configs/cursor/mcp.json | configs/cursor/context-mode.mdc

OpenCode — TypeScript plugin with hooks

Prerequisites: Node.js 18+, OpenCode installed.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Add to opencode.json in your project root (or ~/.config/opencode/opencode.json for global):

    {
      "$schema": "https://opencode.ai/config.json",
      "mcp": {
        "context-mode": {
          "type": "local",
          "command": ["context-mode"]
        }
      },
      "plugin": ["context-mode"]
    }
    

    The mcp entry registers the 6 sandbox tools. The plugin entry enables hooks — OpenCode calls the plugin's TypeScript functions directly before and after each tool execution, blocking dangerous commands and enforcing sandbox routing.

  3. (Optional) Copy the routing rules file. OpenCode lacks a SessionStart hook, so the model needs an AGENTS.md file for routing awareness:

    cp node_modules/context-mode/configs/opencode/AGENTS.md AGENTS.md
    

    This tells the model which tools to use and which commands are blocked. Without it, hooks still enforce routing — but the model won't know why a command was denied.

  4. Restart OpenCode.

Verify: In the OpenCode session, type ctx stats. Context-mode tools should appear and respond.

Routing: Hooks enforce routing programmatically via tool.execute.before and tool.execute.after. The optional AGENTS.md file provides routing instructions for model awareness. The experimental.session.compacting hook builds resume snapshots when the conversation compacts.

Note: OpenCode's SessionStart hook is not yet available (#14808), so startup/resume session restore is not supported. Compaction recovery works fully via the plugin.

Full configs: configs/opencode/opencode.json | configs/opencode/AGENTS.md

KiloCode — TypeScript plugin with hooks

Prerequisites: Node.js 18+, KiloCode installed.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Add to kilo.json in your project root (or ~/.config/kilo/kilo.json for global):

    {
      "$schema": "https://app.kilo.ai/config.json",
      "mcp": {
        "context-mode": {
          "type": "local",
          "command": ["context-mode"]
        }
      },
      "plugin": ["context-mode"]
    }
    

    The mcp entry registers the 6 sandbox tools. The plugin entry enables hooks — KiloCode calls the plugin's TypeScript functions directly before and after each tool execution, blocking dangerous commands and enforcing sandbox routing.

  3. (Optional) Copy the routing rules file. KiloCode shares the OpenCode plugin architecture and lacks SessionStart, so the model needs an AGENTS.md file for routing awareness:

    cp node_modules/context-mode/configs/opencode/AGENTS.md AGENTS.md
    
  4. Restart KiloCode.

Verify: In the KiloCode session, type ctx stats. Context-mode tools should appear and respond.

Routing: Hooks enforce routing programmatically via tool.execute.before and tool.execute.after. The optional AGENTS.md file provides routing instructions for model awareness. The experimental.session.compacting hook builds resume snapshots when the conversation compacts.

Note: KiloCode shares the same plugin architecture as OpenCode, using the OpenCodeAdapter with platform-specific configuration paths (kilo.json instead of opencode.json, ~/.config/kilo/ instead of ~/.config/opencode/). SessionStart hook availability depends on KiloCode's implementation.

OpenClaw / Pi Agent — native gateway plugin

Prerequisites: OpenClaw gateway running (>2026.1.29), Node.js 22+.

context-mode runs as a native OpenClaw gateway plugin, targeting Pi Agent sessions (Read/Write/Edit/Bash tools). Unlike other platforms, there's no separate MCP server — the plugin registers directly into the gateway runtime via OpenClaw's plugin API.

Install:

  1. Clone and install:

    git clone https://github.com/mksglu/context-mode.git
    cd context-mode
    npm run install:openclaw
    

    The installer uses $OPENCLAW_STATE_DIR from your environment (default: /openclaw). To specify a custom path:

    npm run install:openclaw -- /path/to/openclaw-state
    

    Common locations: Docker/openclaw (the default). Local~/.openclaw or wherever you set OPENCLAW_STATE_DIR.

    The installer handles everything: npm install, npm run build, better-sqlite3 native rebuild, extension registration in runtime.json, and gateway restart via SIGUSR1.

  2. Open a Pi Agent session.

Verify: The plugin registers 8 hooks via api.on() (lifecycle) and api.registerHook() (commands). Type ctx stats to confirm tools are loaded.

Routing: Automatic. All tool interception, session tracking, and compaction recovery hooks activate automatically — no manual hook configuration or routing file needed.

Minimum version: OpenClaw >2026.1.29 — this includes the api.on() lifecycle fix from PR #9761. On older versions, lifecycle hooks silently fail. The adapter falls back to DB snapshot reconstruction (less precise but preserves critical state).

Full documentation: docs/adapters/openclaw.md

Codex CLI — MCP + hooks (waiting for upstream dispatch)

Prerequisites: Node.js 18+, Codex CLI installed.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Add to ~/.codex/config.toml:

    [mcp_servers.context-mode]
    command = "context-mode"
    
  3. (Waiting for upstream) Enable the hooks feature flag. Add to ~/.codex/config.toml:

    [features]
    codex_hooks = true
    

    Status: Codex CLI's hook system is implemented in source (codex-rs/hooks/) but hook dispatch is not yet wired into the tool execution pipeline (Stage::UnderDevelopment). The feature flag is accepted but hooks don't fire during sessions as of v0.118.0. Our hook scripts are ready — they'll work immediately once Codex enables dispatch. Track progress: openai/codex#16685.

  4. (Prepare for when dispatch is enabled) Add hooks for routing enforcement and session tracking. Create ~/.codex/hooks.json:

    {
      "hooks": {
        "PreToolUse": [{ "hooks": [{ "type": "command", "command": "context-mode hook codex pretooluse" }] }],
        "PostToolUse": [{ "hooks": [{ "type": "command", "command": "context-mode hook codex posttooluse" }] }],
        "SessionStart": [{ "hooks": [{ "type": "command", "command": "context-mode hook codex sessionstart" }] }]
      }
    }
    

    PreToolUse enforces sandbox routing (blocks dangerous commands, redirects to MCP tools). PostToolUse captures session events. SessionStart restores state after compaction.

    Note: PreToolUse routing supports deny rules only (blocks dangerous commands). Context injection (additionalContext) is not supported in Codex PreToolUse — it works via PostToolUse and SessionStart instead. This is handled automatically.

  5. Copy routing instructions (recommended even with hooks for full routing awareness):

    cp node_modules/context-mode/configs/codex/AGENTS.md ./AGENTS.md
    

    For global use: cp node_modules/context-mode/configs/codex/AGENTS.md ~/.codex/AGENTS.md. Global applies to all projects. If both exist, Codex CLI merges them.

  6. Restart Codex CLI.

Verify: Start a session and type ctx stats. Context-mode tools should appear and respond.

Routing: MCP tools work. Hook-based routing is ready but waiting for Codex to enable hook dispatch. The AGENTS.md file provides routing instructions for model awareness in the meantime.

Exec mode regression (v0.118.0): codex exec cancels all MCP tool calls with "user cancelled MCP tool call". The tool_call_mcp_elicitation flag went stable in 0.118.0, adding an approval prompt that exec-mode can't handle. Pin to Codex ≤0.116.0 for exec-mode MCP. Confirmed by upstream: openai/codex#16685. Interactive mode (codex / codex --full-auto) is not affected.

Antigravity — MCP-only, no hooks

Prerequisites: Node.js 18+, Antigravity installed.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Add to ~/.gemini/antigravity/mcp_config.json:

    {
      "mcpServers": {
        "context-mode": {
          "command": "context-mode"
        }
      }
    }
    
  3. Copy routing instructions (Antigravity has no hook support):

    cp node_modules/context-mode/configs/antigravity/GEMINI.md ./GEMINI.md
    
  4. Restart Antigravity.

Verify: In an Antigravity session, type ctx stats. Context-mode tools should appear and respond.

Routing: Manual. The GEMINI.md file is the only enforcement method (~60% compliance). There is no programmatic interception. Auto-detected via MCP protocol handshake (clientInfo.name) — no manual platform configuration needed.

Full configs: configs/antigravity/mcp_config.json | configs/antigravity/GEMINI.md

Kiro — hooks with steering file

Prerequisites: Node.js 18+, Kiro with MCP enabled (Settings > search "MCP").

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Add to .kiro/settings/mcp.json in your project (or ~/.kiro/settings/mcp.json for global):

    {
      "mcpServers": {
        "context-mode": {
          "command": "context-mode"
        }
      }
    }
    
  3. Create .kiro/hooks/context-mode.json:

    {
      "name": "context-mode",
      "description": "Context-mode hooks for context window protection",
      "hooks": {
        "preToolUse": [
          { "matcher": "*", "command": "context-mode hook kiro pretooluse" }
        ],
        "postToolUse": [
          { "matcher": "*", "command": "context-mode hook kiro posttooluse" }
        ]
      }
    }
    
  4. Copy routing instructions. Kiro's agentSpawn (SessionStart) is not yet implemented, so the model needs a routing file at session start:

    cp node_modules/context-mode/configs/kiro/KIRO.md ./KIRO.md
    
  5. Restart Kiro.

Verify: Open the Kiro panel > MCP Servers tab and confirm "context-mode" shows a green status indicator. In chat, type ctx stats.

Routing: Hooks enforce routing programmatically via preToolUse/postToolUse. The KIRO.md file provides routing instructions since agentSpawn (SessionStart equivalent) is not yet wired. Tool names appear as @context-mode/ctx_batch_execute, @context-mode/ctx_search, etc. Auto-detected via MCP protocol handshake.

Full configs: configs/kiro/mcp.json | configs/kiro/agent.json | configs/kiro/KIRO.md

Zed — MCP-only, no hooks

Prerequisites: Node.js 18+, Zed installed.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Add to ~/.config/zed/settings.json (Windows: %APPDATA%\Zed\settings.json):

    {
      "context_servers": {
        "context-mode": {
          "command": {
            "path": "context-mode"
          }
        }
      }
    }
    

    Note: Zed uses "context_servers" and "command": { "path": "..." } syntax, not "mcpServers" or "command": "..." like other platforms.

  3. Copy routing instructions (Zed has no hook support):

    cp node_modules/context-mode/configs/zed/AGENTS.md ./AGENTS.md
    
  4. Restart Zed (or save settings.json — Zed auto-restarts context servers on config change).

Verify: Open the Agent Panel (Cmd+Shift+A), go to settings, and check the indicator dot next to "context-mode" — green means active. Type ctx stats in the agent chat.

Routing: Manual. The AGENTS.md file is the only enforcement method (~60% compliance). There is no programmatic interception. Tool names appear as mcp:context-mode:ctx_batch_execute, mcp:context-mode:ctx_search, etc. Auto-detected via MCP protocol handshake.

Pi Coding Agent — extension with full hook support

Prerequisites: Node.js 18+, Pi Coding Agent installed.

Install:

  1. Clone the extension:

    git clone https://github.com/mksglu/context-mode.git ~/.pi/extensions/context-mode
    cd ~/.pi/extensions/context-mode
    npm install
    npm run build
    
  2. Add to ~/.pi/agent/mcp.json (or .pi/mcp.json for project-level):

    {
      "mcpServers": {
        "context-mode": {
          "command": "node",
          "args": ["/home/youruser/.pi/extensions/context-mode/node_modules/context-mode/start.mjs"]
        }
      }
    }
    

    Note: JSON does not expand ~. Replace /home/youruser with your actual home directory (run echo $HOME to find it).

  3. Restart Pi.

Verify: In a Pi session, type ctx stats. Context-mode tools should appear and respond.

Routing: Automatic. The extension registers all key lifecycle events (tool_call, tool_result, session_start, session_before_compact), providing full session continuity and routing enforcement.

Build Prerequisites (CentOS, RHEL, Alpine)

Context Mode uses better-sqlite3 on Node.js, which ships prebuilt native binaries for most platforms. On glibc >= 2.31 systems (Ubuntu 20.04+, Debian 11+, Fedora 34+, macOS, Windows), npm install works without any build tools.

Linux + Node.js >= 22.13: Context Mode automatically uses the built-in node:sqlite module instead of better-sqlite3. This eliminates the native addon entirely, avoiding sporadic SIGSEGV crashes caused by V8's madvise(MADV_DONTNEED) corrupting the addon's .got.plt section on Linux. No configuration needed — detection is automatic. Falls back to better-sqlite3 on older Node.js versions.

Bun users: No native compilation needed. Context Mode automatically detects Bun and uses the built-in bun:sqlite module via a compatibility adapter. better-sqlite3 and all its build dependencies are skipped entirely.

On older glibc systems (CentOS 7/8, RHEL 8, Debian 10), prebuilt binaries don't load and better-sqlite3 automatically falls back to compiling from source via prebuild-install || node-gyp rebuild --release. This requires a C++20 compiler (GCC 10+), Make, and Python with setuptools.

CentOS 8 / RHEL 8 (glibc 2.28):

dnf install -y gcc-toolset-10-gcc gcc-toolset-10-gcc-c++ make python3 python3-setuptools
scl enable

Similar mcp servers