TL;DR

Context Mode (mksglu/context-mode) is an MCP server plus a set of editor hooks that keeps raw tool output out of your coding agent’s context window. Instead of letting a Playwright snapshot (56 KB) or twenty GitHub issues (59 KB) land in the conversation, it runs the work in a sandboxed subprocess, returns only stdout, and indexes the full output into a local SQLite FTS5 database the model can search later. The headline claim is a 98% reduction in context consumption — 315 KB of raw output over a session becomes 5.4 KB — and sessions that used to compact at ~30 minutes run for ~3 hours.

It hit #1 on Hacker News with 570+ points in February 2026, sits at 22,477 GitHub stars (1,936 added this week) as of 13 September 2026, and ships adapters for 17 platforms including Claude Code, Codex CLI, Cursor, Gemini CLI, VS Code/JetBrains Copilot, GitHub Copilot CLI, OpenCode, Kiro, Zed, Pi, and OpenClaw.

Key facts:

  • 22,477 stars / 1,617 forks, 238 open issues, created 23 Feb 2026, last push 13 Sep 2026
  • License: Elastic License 2.0 (source-available) — it launched as MIT and switched; more on that below
  • npm context-mode v1.0.169 (29 Jun 2026) is the latest tagged release; main is well ahead of it
  • 11 MCP tools: 6 sandbox tools (ctx_execute, ctx_batch_execute, ctx_execute_file, ctx_index, ctx_search, ctx_fetch_and_index) + 5 meta (ctx_stats, ctx_doctor, ctx_upgrade, ctx_purge, ctx_insight)
  • 12 sandbox runtimes: JavaScript, TypeScript, Python, Shell, Ruby, Go, Rust, PHP, Perl, R, Elixir, C#
  • No LLM calls, no telemetry — retrieval is pure BM25 + Porter stemming + trigram search in local SQLite
  • Author: Mert Köseoğlu (mksglu), who also runs an MCP directory

The problem it actually solves

There are two ways MCP eats your context window. Tool definitions fill it on the way in — with 81+ tools loaded, 143K tokens (72% of a 200K window) are gone before your first message. Tool output fills it on the way out: every gh issue list, every log file, every browser snapshot lands in the transcript verbatim and gets carried forward turn after turn.

Cloudflare’s Code Mode attacked the input side. Context Mode’s pitch is “the other half of the context problem.” The fix is a paradigm the README calls Think in Code: the LLM should program the analysis, not perform it. Instead of reading 50 files into context to count functions, the agent writes a script that does the counting and prints only the number.

// Before: 47 × Read() = 700 KB in context.
// 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')
  );
`);

If you’ve used codebase-memory-mcp or Caveman, the goal is familiar — fewer tokens per task. The mechanism is different: Caveman compresses the model’s output style, codebase-memory-mcp replaces file reads with a code graph. Context Mode doesn’t care what the tool is — anything with big stdout goes through the sandbox.

How it works

1. The sandbox

Each ctx_execute call spawns an isolated subprocess. The script runs, stdout is captured, and only stdout enters the conversation. Bun is auto-detected for JS/TS (3-5× faster); otherwise Node ≥ 22.5 is required. Authenticated CLIs (gh, aws, gcloud, kubectl, docker) inherit env vars and config paths, so ctx_execute("shell", "gh issue list --json title,labels | jq ...") works without a token ever appearing in the transcript.

When output exceeds 5 KB and you pass an intent, the full output is indexed into the knowledge base and only sections matching the intent come back, plus a vocabulary of searchable terms for follow-ups. Nothing is thrown away; it’s parked.

2. The knowledge base

ctx_index chunks markdown by headings (code blocks kept intact) into a SQLite FTS5 virtual table. Search combines two strategies merged with Reciprocal Rank Fusion:

  • Porter-stemmed FTS5 MATCH — “caching” matches “cached” and “caches”; titles and headings weighted 5×
  • Trigram substring match — “useEff” finds useEffect, “authenticat” finds “authentication”

Plus proximity reranking, Levenshtein typo correction (“kuberntes” → “kubernetes”), and snippets windowed around the matched terms. ctx_fetch_and_index does the same for URLs with a 24-hour TTL cache, so re-fetching React docs costs ~0.3 KB instead of 48 KB. Progressive throttling on ctx_search — normal results for calls 1-3, reduced for 4-8, blocked at 9+ with a redirect to ctx_batch_execute — actively pushes the model toward batching over chatty retrieval.

3. Hooks and routing enforcement

This is what separates Context Mode from “just use a subagent” workarounds. On hook-capable platforms it registers PreToolUse, PostToolUse, UserPromptSubmit, PreCompact, SessionStart, and Stop hooks. PreToolUse intercepts raw Bash/Read/WebFetch calls that would produce large output and redirects them to the sandbox before execution:

Without hooks, one unrouted curl or Playwright snapshot can dump 56 KB into context — wiping out an entire session’s worth of savings.

The project’s own numbers: ~98% saved with hooks, ~60% saved with instruction files alone (Zed and the Antigravity IDE, which lack hooks, get the instruction-file tier).

4. Session continuity

Every file edit, git operation, task, error, and user decision is logged to a per-project SQLite database. When the agent compacts — or you --continue / --resume — the events are indexed into FTS5 and only what’s relevant to the current prompt is retrieved. If you don’t resume, the previous session’s data is deleted immediately.

Install (Claude Code, 60 seconds)

Requires Claude Code v1.0.33+ for the plugin marketplace:

/plugin marketplace add mksglu/context-mode
/plugin install context-mode@context-mode
# restart Claude Code or /reload-plugins
/context-mode:ctx-doctor

ctx-doctor validates runtimes, hooks, FTS5, and plugin registration — every line should be [x]. If you just want the tools without automatic routing:

claude mcp add context-mode -- npx -y context-mode

Optional status line, so you can watch savings accumulate (one manual edit to ~/.claude/settings.json, because plugin manifests can’t declare a status line):

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

Gemini CLI is npm install -g context-mode plus one ~/.gemini/settings.json block (MCP server + four hooks). GitHub Copilot CLI is a one-liner: copilot plugin install mksglu/context-mode:configs/copilot-cli. Cursor’s Marketplace plugin is still awaiting Cursor’s review (issue #485), so today you symlink a clone into ~/.cursor/plugins/local/. Codex CLI needs [features].hooks = true and can only deny in PreToolUse, not rewrite input, until openai/codex#18491 lands.

You don’t call the tools by hand — type ctx stats or ctx doctor in chat and the model invokes them. From a terminal:

context-mode index . --source project:my-app
context-mode search "authentication middleware" --source project:my-app
context-mode doctor

Security model

Context Mode reads Claude Code’s permissions block from .claude/settings.json — even when you’re running it under Gemini CLI or OpenCode — and applies it inside the sandbox:

{
  "permissions": {
    "deny": ["Bash(sudo *)", "Bash(rm -rf /*)", "Read(.env)", "Read(**/.env*)"],
    "allow": ["Bash(git:*)", "Bash(npm:*)"]
  }
}

Chained commands are split on &&, ;, and | and checked part-by-part; deny beats allow. ctx_execute_file is confined to the project root (closing issue #852, where an agent denied an out-of-project read by the host retried it through the MCP sandbox). ctx_fetch_and_index blocks file://, javascript:, and cloud-metadata IPs; CTX_FETCH_STRICT=1 also blocks loopback and RFC1918 for CI. Tool inputs are regex-redacted (token, bearer, api_key, cookie, …) before hitting the session DB.

The README’s own caveat: ctx_execute and ctx_batch_execute “run arbitrary code and still inherit the process’s filesystem access.” The boundary guard is defense-in-depth for the file-read tool, not an OS sandbox.

Benchmarks

The project’s own numbers, from BENCHMARK.md (21 scenarios):

ScenarioRawIn contextSaved
Playwright snapshot56.2 KB299 B99%
GitHub issues (20)58.9 KB1.1 KB98%
Access log (500 requests)45.1 KB155 B100%
Analytics CSV (500 rows)85.5 KB222 B100%
Git log (153 commits)11.6 KB107 B99%
Test output (30 suites)6.0 KB337 B95%
Repo research (subagent)986 KB62 KB94% (5 calls vs 37)

These measure bytes kept out of context, not task quality. When an HN commenter asked whether any benchmark shows the model getting smarter from a cleaner context, Köseoğlu was honest: “We haven’t run formal benchmarks on answer quality yet, mostly focused on measuring token savings.” The anecdotal claim is fewer mistakes because sessions reach compaction less often.

What the community says

The February HN launch (570+ points, #1) was largely positive with sharp pushback in the details:

  • “Isn’t this just pre-compaction?” Köseoğlu agreed, with one distinction: “nothing gets thrown away. The full output sits in a searchable FTS5 index, so if the model realizes it needs some detail it missed in the summary, it can search for it.”
  • “Claude Code already truncates MCP output at 25K tokens.” True — but “three or four Playwright snapshots or a batch of GitHub issues and you’ve burned 100k tokens on raw data you only needed a few lines from.”
  • “Does this break prompt caching?” One commenter warned that if so it’s “penny wise, pound foolish.” The thread never got a definitive answer.
  • “Why not just use subagents?” Ideal, Köseoğlu said, but “most people don’t hand-curate their MCP server list per task.”
  • vs rtk (which trims CLI stdout): Context Mode “is less about trimming and more about replacing a raw dump with a summary plus on-demand retrieval.”
  • One user: “I am a happy user of this and have recommended my team also install it. It’s made a sizable reduction in my token use.”

The most-requested idea in the thread — backtracking, pruning failed attempts once the right fix lands — is something Köseoğlu called “very doable.” It isn’t shipped yet.

Honest limitations

The license changed. The launch post (26 Feb 2026) says “Open source. MIT.” The repo today is Elastic License 2.0 — use, fork, modify, redistribute, but no hosted/managed service. Fine for individuals, no longer OSI open source, and the README now points teams at a hosted “Insight” dashboard. Check ELv2 against your company’s policy.

Open bugs on the hot path. Issue #947 (10 Jul 2026, v1.0.169): ctx_batch_execute calls with timeout: 120000 stayed in flight for over four hours on Windows, because the timeout bounds the command phase but not indexing/search against a bloated content DB. Issue #959: a hung ctx_execute on the Pi adapter that Esc/Ctrl+C can’t abort. Issue #982: on Windows the MCP child can orphan and spin CPU at session end (the parent-death guard is Linux/Bun-only). Windows users should read the tracker first.

It trips Claude Code’s auto-mode classifier. Issue #911 (3 Jul 2026): the injected <context_window_protection> routing block — specifically the clause “a past phrase does not bind you” — got flagged as an “Auto-Mode Bypass” prompt-injection payload, blocking subagent dispatches and ctx_upgrade. Issue #946 asks for an opt-out.

ctx_stats overstates itself. Issue #950 shows a per-chat “kept out” figure (2.7 MB) exceeding the all-projects total (868 KB), and 100% savings for a session with zero ctx_execute calls. v1.0.167-169 were mostly savings-accounting fixes, so it’s being worked on — but the “98%” in your status line is a self-reported estimate, not an audit.

Version drift. npm’s latest is v1.0.169 from June; main has moved a lot since (Copilot CLI plugin, Antigravity CLI, Hermes in PRs #981/#1010). ctx_upgrade pulls from GitHub, not npm, so the two paths diverge.

It doesn’t fix tool-definition bloat. With 80 tools loaded, Context Mode does nothing about the 143K tokens they cost up front. Pair it with a curated MCP list or a skills approach like Superpowers.

Who should use it

Use it if: you run long Claude Code / Codex / Gemini CLI sessions that hit compaction; your workflow involves browser automation, big JSON APIs, log triage, or repo research; you work on macOS or Linux; you’re fine with ELv2.

Skip it if: your sessions are short and code-only (the savings on plain Read/Edit loops are modest); you’re on Windows and can’t tolerate the orphan/hang bugs yet; you use Claude Code’s auto mode heavily; or you already run a disciplined subagent-per-task setup and don’t need enforcement.

Compared to the alternatives: claude-mem and agentmemory solve cross-session memory; Context Mode’s continuity is narrower (compaction recovery) but its sandbox is the unique piece. Claude Context does semantic code search with embeddings; Context Mode does lexical search over tool output with no model calls. Complementary, not substitutes.

FAQ

Does Context Mode work with Codex CLI and Cursor?

Yes, with caveats. Codex CLI needs [features].hooks = true in its config; PreToolUse can deny but not rewrite tool input, so routing is enforced by blocking rather than redirecting. Cursor works via a local plugin symlink today; the Marketplace listing is pending Cursor’s review (issue #485).

Does it send my code anywhere?

No. There’s no telemetry, no account, and no cloud sync in the core tool. All SQLite databases live locally (default ~/.claude/context-mode or ~/.codex/context-mode, overridable with CONTEXT_MODE_DIR). The optional ctx_insight command opens a hosted team dashboard at context-mode.com; that’s opt-in.

Is Context Mode open source?

It’s source-available under Elastic License 2.0, not OSI-approved open source. You can read, fork, modify, and redistribute it; you can’t sell it as a managed service. It launched as MIT in February 2026 and changed later.

How is this different from Cloudflare’s Code Mode?

Cloudflare’s Code Mode compresses tool definitions (the input side) by exposing one execute tool that runs code against a typed API instead of loading dozens of tool schemas. Context Mode compresses tool outputs (the output side) by running work in a sandbox and returning only stdout. Köseoğlu cites Code Mode as the direct inspiration.

Bottom line

Context Mode is the most complete answer I’ve seen to the output half of the MCP context problem: sandbox execution, lexical retrieval over what got sandboxed, and hooks that enforce the routing instead of hoping the model remembers. The architecture — no LLM in the loop, everything in local SQLite — is exactly right for a tool that sits between you and your agent.

The caveats are real too: ELv2 instead of MIT, an open four-hour-hang bug on Windows, friction with Claude Code’s auto mode, stats that overstate themselves. On macOS or Linux in a normal Claude Code or Gemini CLI session, none of those will bite you, and the install is two slash commands. Run /context-mode:ctx-stats after a day of real work and decide with your own numbers.

Install: /plugin marketplace add mksglu/context-mode/plugin install context-mode@context-mode. Repo: github.com/mksglu/context-mode.

Sources