context-mode README

The project's README from github.com/mksglu/context-mode. As one markdown file: README.md.

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. On top of that, the agent wastes output tokens on filler, pleasantries, and verbose explanations — burning context from both sides.

How Context Mode Solves It

Context Mode is an MCP server that solves all four 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 17 supported clients, plus the OpenClaw gateway integration: stop treating the LLM as a data processor, treat it as a code generator.

    // Before: 47 × Read() = 700 KB.  After: 1 × ctx_execute() = 3.6 KB.
    ctx_execute("javascript", `
      const files = fs.readdirSync('src').filter(f => f.endsWith('.ts'));
      files.forEach(f => console.log(f + ': ' + fs.readFileSync('src/'+f,'utf8').split('\\n').length + ' lines'));
    `);
    
  4. No prose-style enforcement — context-mode keeps raw data out of context but never dictates how the model writes its final answer. Brevity, completeness, formatting — your model's call (or yours via your own CLAUDE.md / AGENTS.md). Aggressive brevity prompts have been shown to degrade coding/reasoning benchmarks (Moonshot AI on kimi-k2.5) — the routing block stays focused on where data goes, not on how the model talks.

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, UserPromptSubmit, PreCompact, SessionStart, Stop) and 11 MCP tools — six sandbox tools (ctx_batch_execute, ctx_execute, ctx_execute_file, ctx_index, ctx_search, ctx_fetch_and_index) plus five 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-index Index a local file or directory into the persistent FTS5 knowledge base.
/context-mode:ctx-search Search previously indexed content.
/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 Opens the hosted Insight dashboard (context-mode.com/insight) in your browser — org analytics for AI-assisted engineering teams.

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

Status line (optional): Claude Code's plugin manifest cannot declare a status line, so this is a one-time manual edit to ~/.claude/settings.json:

{
  "statusLine": {
    "type": "command",
    "command": "context-mode statusline"
  }
}

After saving, restart Claude Code. The bar shows $ saved this session · $ saved across sessions · % efficient so you can see savings accumulate in real time. The wiring is path-free — context-mode statusline resolves through the bundled CLI regardless of where the plugin cache lives.

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

This gives you all 11 MCP 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 >= 22.5 (or Bun), 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|mcp__context-mode|mcp__(?!.*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 via SessionStart hook. Optionally copy routing instructions for full model awareness:

cp node_modules/context-mode/configs/gemini-cli/GEMINI.md ./GEMINI.md

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 >= 22.5 (or Bun), 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 via SessionStart hook. Optionally copy routing instructions for full model awareness:

cp node_modules/context-mode/configs/vscode-copilot/copilot-instructions.md .github/copilot-instructions.md

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

JetBrains Copilot — hooks with SessionStart

Prerequisites: Node.js >= 22.5 (or Bun), JetBrains IDE with GitHub Copilot plugin v1.5.57+.

Install:

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Add MCP server via Settings UI: Settings > Tools > AI Assistant > Model Context Protocol (MCP) > Add Server:

    • Name: context-mode
    • Command: context-mode
  3. Create .github/hooks/context-mode.json:

    {
      "hooks": {
        "PreToolUse": [
          { "type": "command", "command": "context-mode hook jetbrains-copilot pretooluse" }
        ],
        "PostToolUse": [
          { "type": "command", "command": "context-mode hook jetbrains-copilot posttooluse" }
        ],
        "SessionStart": [
          { "type": "command", "command": "context-mode hook jetbrains-copilot sessionstart" }
        ]
      }
    }
    
  4. Restart the JetBrains IDE.

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

Routing: Automatic via SessionStart hook. Optionally copy routing instructions for full model awareness:

cp node_modules/context-mode/configs/jetbrains-copilot/copilot-instructions.md .github/copilot-instructions.md

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

Full setup guide: docs/jetbrains-copilot.md

GitHub Copilot CLI — MCP + hooks

Prerequisites: Node.js >= 22.5 (or Bun), GitHub Copilot CLI (copilot) installed. Set COPILOT_HOME first if you use an isolated Copilot home.

Install — Option A (plugin, one command — recommended):

npm install -g context-mode                                     # the plugin's MCP server runs the global binary
copilot plugin install mksglu/context-mode:configs/copilot-cli  # registers MCP + hooks + routing skill

The bundle's .mcp.json pins CONTEXT_MODE_PLATFORM=copilot-cli, so context-mode self-identifies as Copilot — ctx_upgrade and platform detection resolve copilot-cli even when Claude Code is co-installed (whose ~/.claude/ would otherwise win). No context-mode upgrade / agent call needed. To try it from a local clone before it lands on the default branch, point Copilot at the bundle directory: copilot --plugin-dir /path/to/context-mode/configs/copilot-cli.

Install — Option B (manual, no plugin):

  1. Install context-mode globally:

    npm install -g context-mode
    
  2. Register the MCP server with Copilot CLI's built-in command (writes ~/.copilot/mcp-config.json for you):

    copilot mcp add context-mode -- context-mode
    
  3. Configure hooks in ~/.copilot/hooks/context-mode.json (or $COPILOT_HOME/hooks/context-mode.json). The config uses flat { "type": "command", "command": "..." } entries; context-mode also writes a top-level "version": 1, but that field is optional — the Copilot CLI accepts hook configs that omit it (it is pinned only for self-documentation). Copilot CLI fires six events context-mode uses:

    {
      "version": 1,
      "hooks": {
       "preToolUse":          [{ "type": "command", "command": "context-mode hook copilot-cli pretooluse" }],
       "postToolUse":         [{ "type": "command", "command": "context-mode hook copilot-cli posttooluse" }],
       "preCompact":          [{ "type": "command", "command": "context-mode hook copilot-cli precompact" }],
       "sessionStart":        [{ "type": "command", "command": "context-mode hook copilot-cli sessionstart" }],
       "userPromptSubmitted": [{ "type": "command", "command": "context-mode hook copilot-cli userpromptsubmit" }],
       "agentStop":           [{ "type": "command", "command": "context-mode hook copilot-cli stop" }]
      }
    }
    

    Or let context-mode write this hooks file for you: context-mode upgrade (run from a Copilot CLI context, or with CONTEXT_MODE_PLATFORM=copilot-cli). upgrade writes the hooks file only — register the MCP server with copilot mcp add in step 2.

  4. Restart Copilot CLI.

Plugins: Option A above uses Copilot CLI's plugin system, which registers MCP servers (.mcp.json), hooks (hooks.json), and skills (skills/) together — not just skills/agents. The shipped bundle is configs/copilot-cli/; copilot plugin install owner/repo:path installs it in one command (no clone). Option B is the equivalent without a plugin.

Version note: the hook commands run the global context-mode (context-mode hook copilot-cli …), so they need a context-mode version with Copilot CLI support. On an older global the hooks are inert (no routing/capture) until you upgrade — but they do not block your tools (context-mode fails open). Upgrade with npm install -g context-mode@latest.

Verify: In a Copilot CLI session, type ctx stats. Context-mode tools should appear and respond. Run context-mode doctor to confirm hook + MCP registration.

Routing: Automatic via hooks (PreToolUse interception + SessionStart routing block). Auto-detected via MCP clientInfo.name (GitHub Copilot CLI) or, in a bare shell, a context-mode-written marker (~/.copilot/mcp-config.json or ~/.copilot/hooks/context-mode.json) — not a bare ~/.copilot/ dir, so a co-installed-but-unconfigured Copilot CLI is not mis-detected as context-mode-on-copilot.

See docs/platform-support.md for the full reference. Tracking: #775.

Cursor — hooks with stop support

Prerequisites: Node.js >= 22.5 (or Bun), Cursor with agent mode.

🚧 Work in progress — the Marketplace plugin is awaiting Cursor team review. Until it's listed, install via the local-folder path described in Option A. Tracking in #485 / #489.

After Cursor lists context-mode in the Marketplace, install with one click. The plugin auto-registers MCP, hooks (preToolUse, postToolUse, `sessionStar

context-mode (mksglu/context-mode)

Searching Database…

这是什么东西?Context Mode 是一个 MCP 服务器加钩子(hooks),能把庞大的工具输出挡在 AI 编程助手的上下文窗口之外(减少 98%),持久保存会话记忆,并在 17 个平台上强制执行工具路由。
它是一个独立的软件,还是能接入我已有的编程助手的东西?它接入你已经在用的助手:一个 MCP 服务器加钩子(hooks)。你的助手会获得 11 个 MCP 工具,钩子会在大量工具输出灌满上下文窗口之前把它们拦截下来。
我在 Claude Code 里怎么安装配置?从 Claude Code 插件市场安装该插件(需要 v1.0.33 及以上版本),重启,然后运行 doctor 命令验证。之后路由会通过 SessionStart 钩子自动完成——不会在你的项目里写入任何东西。
它支持哪些助手?我需要先装什么?支持 17 个平台,包括 Claude Code、Gemini CLI、VS Code 和 JetBrains Copilot、Copilot CLI、Cursor、Codex、OpenCode、Kiro 和 Zed。你需要 Node.js 22.5+(或 Bun);某些宿主要求最低版本,比如 Copilot Chat v0.32+。
它在每个助手上的表现都一样吗?不一样。支持钩子的平台可以自动强制执行路由;不支持的则需要手动复制一次路由文件。Cursor 的市场插件还在等待审核,所以在那里你要从本地文件夹安装。
我的会话数据会传到哪里去?数据只留在本地:文件修改、git 操作、任务、错误和决策都记录在你电脑上的 SQLite 数据库里,除非你用 --continue 恢复会话,否则会立即删除。唯一托管在云上的是可选加入的 Insight 仪表板,用于团队分析。
它到底是怎么省下 98% 上下文的?沙箱工具让原始输出不进入上下文窗口:一个 315 KB 的工具结果会变成 5.4 KB,助手按需查询已建立索引的数据,而不是把所有内容都塞进上下文。
什么是 “Think in Code”?一条核心原则:助手不再把 50 个文件读进上下文来数函数个数,而是写一个脚本来完成统计、只输出结果——一个脚本替代十次工具调用,节省 100 倍上下文。
对话被压缩之后,我的会话会怎么样?Context Mode 不会把所有内容重新倒回上下文:它把会话事件索引到 FTS5 里,通过 BM25 搜索只取回相关内容,模型因此能从上次中断的地方无缝继续。
它会让模型的回答变得更简短吗?不会——它只是把原始数据挡在上下文之外,从不干涉模型如何撰写最终回答。回答的简洁程度和格式仍由你通过自己的 CLAUDE.md 或 AGENTS.md 控制;路由模块只决定数据流向哪里。
Creator
mksglu
Size
33.9 MB
Stars
30.3K
Age
7mo
Commits · 90 Days