DEV Community

Terminal Chai
Terminal Chai

Posted on

Context Mode: Cut AI Coding Agent Context Bloat by 98% with Sandboxed MCP & SQLite FTS5

Developers relying on autonomous coding agents—such as Claude Code, Cursor, Gemini CLI, VS Code Copilot, and OpenCode—routinely encounter a hidden bottleneck: context window pollution from raw tool outputs.

While frontier models boast 200K to 1M+ token context windows, everyday Model Context Protocol (MCP) and shell tool calls exhaust that capacity at an alarming rate:

  • A single Playwright snapshot consumes 56 KB.
  • Fetching 20 GitHub issues consumes 59 KB.
  • Inspecting one server access log consumes 45 KB.

Within 30 minutes of active debugging, over 40% of the context window is filled with raw JSON payloads, log lines, and file dumps. When the coding agent triggers conversation compaction to free up space, it suffers from compaction amnesia—losing track of which files were edited, which edge cases were already ruled out, and what the user originally requested.

Context Mode (mksglu/context-mode) is an open-source MCP server and lifecycle hook engine engineered to solve this exact problem. By sandboxing heavy tool outputs, enforcing programmatic analysis, and indexing session history into SQLite FTS5, Context Mode shrinks 315 KB tool payloads down to 5.4 KB—a 98% reduction in context consumption.


The Four Pillars of Context Mode

Context Mode addresses context degradation across four distinct architectural layers:

┌─────────────────────────────────────────────────────────────────┐
│                   AI Coding Agent Session                       │
│   (Claude Code · Cursor · Gemini CLI · Copilot · OpenCode)      │
└───────────────┬─────────────────────────────────┬───────────────┘
                │ PreToolUse / BeforeTool Hook    │ PreCompact Hook
                ▼                                 ▼
┌───────────────────────────────┐ ┌───────────────────────────────┐
│   1. Sandboxed Execution      │ │  2. SQLite + FTS5 Memory      │
│   • ctx_execute / batch       │ │  • Tracks edits, git, tasks   │
│   • 315 KB raw → 5.4 KB       │ │  • BM25 relevance retrieval   │
│   • "Think in Code" paradigm  │ │  • Zero-amnesia compaction    │
└───────────────────────────────┘ └───────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

1. Context Saving via Sandboxed Tools (98% Reduction)

Standard MCP servers return complete raw responses directly into the conversation transcript. Context Mode provides six specialized sandbox tools (ctx_batch_execute, ctx_execute, ctx_execute_file, ctx_index, ctx_search, and ctx_fetch_and_index) that process heavy outputs outside the prompt buffer, returning only high-signal summaries.

2. Session Continuity with SQLite & FTS5 BM25 Search

Every file modification, git operation, task transition, error trace, and user decision is captured in a local SQLite database. When the host IDE or CLI compacts the conversation:

  • Context Mode does not dump raw history back into the system prompt.
  • Instead, it indexes session events into SQLite FTS5 and retrieves only the most relevant context on demand using BM25 ranking.
  • If you start a fresh session without --continue, prior session data is immediately purged so new tasks begin with a clean slate.

3. The "Think in Code" Paradigm

One of the most wasteful anti-patterns in agentic coding is using the LLM as a manual data processor—such as calling Read() 47 times to count lines or search for exports across a codebase (consuming ~700 KB of context).

Context Mode enforces a Think in Code paradigm across all 17 supported platforms: the LLM writes a compact script to perform the analysis in a sandbox and console.log()s only the result:

// Before: 47 × Read() = 700 KB in context window
// After:  1 × ctx_execute() = 3.6 KB in context window
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')
  );
`);
Enter fullscreen mode Exit fullscreen mode

One sandboxed script replaces dozens of sequential tool calls and reduces token usage by over 100x.

4. Routing Enforcement Without Prose Restrictions

Research from frontier model teams has shown that aggressive "be concise / no explanations" system prompts degrade coding and reasoning benchmarks. Context Mode's runtime routing block focuses strictly on where data goes (intercepting heavy Bash, Read, Grep, and WebFetch calls), leaving response style, completeness, and formatting entirely up to your model and your project's CLAUDE.md or AGENTS.md.


Complete Tooling & Diagnostics Suite

Context Mode registers 11 MCP tools out of the box—six sandbox execution/indexing tools and five operational meta-tools:

Command / Tool Purpose
ctx_execute / ctx_batch_execute Execute analysis scripts in a sandbox and return compact output
ctx_index / ctx_fetch_and_index Index local files, directories, or remote docs into the FTS5 store
ctx_search Query indexed documentation and session events via BM25
ctx_stats View per-tool token savings, consumption breakdown, and efficiency ratio
ctx_doctor Diagnose runtimes, hook registrations, FTS5 status, and plugin health
ctx_upgrade Pull latest updates, rebuild, migrate caches, and repair hooks
ctx_purge Permanently clear all indexed content from the local knowledge base

Quick Start & Installation

Context Mode supports 17 coding platforms, including Claude Code, Gemini CLI, Cursor, VS Code Copilot, JetBrains Copilot, GitHub Copilot CLI, OpenCode, and KiloCode.

Option 1: Claude Code (Plugin Marketplace — Fully Automatic)

/plugin marketplace add mksglu/context-mode
/plugin install context-mode@context-mode
Enter fullscreen mode Exit fullscreen mode

Restart Claude Code and verify your installation:

/context-mode:ctx-doctor
Enter fullscreen mode Exit fullscreen mode

All lifecycle hooks (SessionStart, PreToolUse, PostToolUse, UserPromptSubmit, PreCompact, Stop) and all 11 MCP tools are registered automatically.

Option 2: Global CLI Install (Gemini CLI, Copilot, Cursor, OpenCode)

npm install -g context-mode
Enter fullscreen mode Exit fullscreen mode

For OpenCode (opencode.json) or KiloCode (kilo.json), register the in-process TypeScript plugin with a single line:

{
  "$schema": "https://opencode.ai/config.json",
  "plugin": ["context-mode"]
}
Enter fullscreen mode Exit fullscreen mode

For GitHub Copilot CLI, install the full bundle (MCP + hooks + routing skill) in one command:

copilot plugin install mksglu/context-mode:configs/copilot-cli
Enter fullscreen mode Exit fullscreen mode

Conclusion

As AI coding agents take on longer, multi-file engineering tasks, raw context window size is no longer enough—context hygiene determines whether an agent stays sharp after an hour of debugging or collapses under tool output bloat.

By combining sandboxed code execution, automatic hook interception, and FTS5 BM25 session memory, Context Mode gives developers a drop-in upgrade that cuts token burn by up to 98% while keeping long-running coding sessions rock-solid.

Top comments (0)