Context Mode: Keep Tool Output Out of Your Agent's Context
Context Mode: A Deep Dive into Context Saving, Session Continuity, and Code-First AI Sandboxing
Introduction
In today’s AI-assisted workflows, the cost of context is real. Every tool call, file read, or log message can balloon the context window, leaving your model without the critical pieces it needs to continue where you left off. Context Mode introduces a deliberate, code-first approach to protect context, preserve session continuity, and compress output without losing technical substance. It treats the LLM as a code generator and orchestrator of a sandboxed analysis rather than a blunt data processor. The result is significant context savings, reliable session restoration, and a cleaner, faster, more predictable interaction with your AI tooling.
Watch a quick demo
If you want to see Context Mode in action, check out the introductory demo. It distills the four pillars of Context Mode into a compact demonstration and provides a crisp sense of how the approach works in practice.
Watch Demo on YouTube
Watch Demo Preview
The Problem: Why Context Mode Exists
A typical MCP (Model Context Protocol) workflow dumps large bursts of raw data into the context window. A Playwright snapshot can be tens of kilobytes; dozens of GitHub issues and access logs accumulate quickly. After minutes or hours, the model’s context is crowded, and crucial items—files being edited, tasks in progress, or last user requests—can be forgotten when the conversation is compacted or restarted.
Context Mode identifies four layered challenges:
- Context Saving: Raw data leaks into the prompt, bloating the context window.
- Session Continuity: Important state about files, edits, tasks, and decisions risks loss after compaction.
- Think in Code: The LLM should generate code to perform analysis rather than perform heavy in-context computation, saving tokens and reducing context size.
- Output Compression: The model should be terse and precise, shedding filler while preserving technical substance.
The four-part solution is designed to minimize context usage by orders of magnitude while preserving fidelity and continuity.
How Context Mode Solves It: The Four Pillars
1) Context Saving Through Sandbox Tools
- The core idea: raw data stays out of the chat window. Sandbox tools operate in isolation, processing large inputs privately and returning only essential results.
- The sandbox captures and processes data in a sandboxed subprocess, so nothing leaks from the tool into the model’s visible context.
- This approach yields dramatic reductions in how much data ends up in the conversation. In practical terms, a snapshot or a multi-file analysis can be reduced from hundreds of kilobytes to a few kilobytes in the model’s view, keeping the critical signals intact.
2) Session Continuity with Per-Session Tracking
- Every file edit, git operation, task, error, and user decision is tracked in SQLite. When the conversation compacts, Context Mode does not dump all history back into the context window.
- Instead, events are indexed with full-text search (FTS5) and retrieved selectively via BM25-based relevance. The model resumes right where you left off, with exact references to your prior actions.
- If you opt for a fresh session (no continuation), previous session data is deleted. If you choose to continue, you retain continuity and context across sessions.
3) Think in Code: The Power of Code-Generated Analysis
- The LLM is encouraged to generate code to perform heavy analysis. Instead of reading dozens of files into the context to count lines or compute metrics, Context Mode prompts the model to write a script that does the work and only outputs the final result.
- One script replaces many tool calls and drastically reduces the amount of context that must be carried forward.
- This “think in code” paradigm is a mandatory pattern across supported platforms, reducing the cognitive load on the model and the token cost for the user.
4) Output Compression: Short, Precise, and Safe
- The idiom is “Drop the fluff.” The output is compressed without sacrificing the technical substance.
- Patterns like [thing] [action] [reason] ensure that every statement remains actionable and scannable.
- The system also expands for security warnings and irreversible actions when necessary, but otherwise remains terse and direct.
Install and Platform Coverage
Context Mode is designed to work across a broad ecosystem of platforms and tooling environments. It exposes a set of sandbox tools and meta-tools, with routing and hook integration tailored to each platform. Below are the broad categories and some representative examples of how it’s implemented.
Sandbox Tools (core actions)
ctxbatchexecute: run multiple commands and queries in one call; dramatically reduces context size.
ctx_execute: run code in multiple languages; only stdout enters the context.
ctxexecutefile: sandboxed file processing; raw content never leaves the sandbox.
ctx_index: chunk markdown and index into SQLite FTS5.
ctx_search: perform targeted search on indexed content.
ctxfetchand_index: fetch a URL, convert to markdown, and index; a short TTL cache ensures repeated fetches don’t waste tokens.
Knowledge Base and Search
The index uses SQLite FTS5 with BM25 ranking, weighted headings, and Porter stemming for robust retrieval.
Proximity reranking and trigram matching improve relevance for multi-term queries.
A TTL-based cache system saves content for 24 hours; older content is pruned after a 14-day cycle.
Session Continuity: Handshake Between Hooks
PreToolUse: enforces sandbox routing before tool execution.
PostToolUse: captures events after each tool call.
SessionStart: restores state after compaction or resume (where supported by the platform).
PreCompact: builds a compacted snapshot before session compaction.
Platform-Specific Install and Routing (Summary)
Note: Platforms with hook support can route automatically; others require one-time routing instructions via an instruction file. The following is a concise guide to what’s required for popular platforms.
Claude Code
Prerequisites: Claude Code v1.0.33+.
Install: plugin marketplace path; restart; verify with a diagnostic.
Routing: automatic via hooks; instruction files provide detailed prompts to the model.
Gemini CLI
Prerequisites: Node.js, Gemini CLI.
Install: global npm package; edit Gemini settings to register the MCP server.
Routing: automatic via SessionStart; file-based instructions also available.
VS Code Copilot
Prerequisites: Node.js 18+, Copilot Chat.
Install: global npm install; define MCP server in .vscode/mcp.json; create a context-mode hooks file.
Routing: automatic via SessionStart; optional copy of a MD file with routing guidance.
JetBrains Copilot
Prerequisites: Node.js 18+, JetBrains IDE with Copilot.
Install: npm install -g context-mode; MCP server entry in settings; create context-mode.json hooks file.
Routing: automatic via SessionStart; optional MA routing instructions file.
Cursor
Prerequisites: Node.js 18+, Cursor tool.
Install: npm install -g context-mode; place mcp.json and hooks.json in project or global.
Routing: via preToolUse/postToolUse; sessionStart routing provided through a rules file rather than a hook.
OpenCode
Prerequisites: OpenCode environment.
Install: npm install -g context-mode; enable the OpenCode adapter and plugin.
Routing: automatic via hooks; a routing MD file is provided for reference.
KiloCode
Prerequisites: Node.js 18+.
Install: npm install -g context-mode; adapter follows OpenCode-like architecture.
Routing: similar to OpenCode; sessionStart availability depends on KiloCode’s implementation.
OpenClaw / Pi Agent
Prerequisites: OpenClaw gateway (Pi Agent sessions).
Install: context-mode as a native gateway plugin; restore and restart the gateway as needed.
Routing: automatic for full session continuity via the gateway plugin hooks.
Codex CLI
Prerequisites: Codex CLI.
Install: MCP-enabled; install hooks in ~/.codex/hooks.json.
Routing: MCP tools work; hook-based routing is active. PreToolUse supports modern deny-and-route semantics; input rewriting depends on upstream support.
Antigravity
Prerequisites: Antigravity with MCP.
Install: copy Gemini’s routing MD as a fallback routing guide.
Routing: manual; no programmatic hook support.
Kiro
Prerequisites: Kiro with MCP enabled.
Install: add context-mode MCP server; copy KIRO.md as routing guidance.
Routing: pre/post-tool hooks are available; agentSpawn (SessionStart) is not yet wired in some setups.
Zed
Prerequisites: Zed.
Install: copy AGENTS.md for routing guidance.
Routing: manual; no automatic hook routing.
Pi
Prerequisites: Pi Coding Agent.
Install: context-mode as an extension; MCP server included.
Routing: automatic via extension hooks; high session continuity.
OpenClaw
Prerequisites: OpenClaw gateway with Pi Agent sessions.
Install: as a native gateway plugin; 8 hooks register through the gateway’s API.
Routing: automatic across the platform.
Utility Commands and How to Use Them
Inside any AI session
- ctx stats: Show context savings, call counts, and session statistics.
- ctx doctor: Diagnose runtimes, hooks, FTS5, and versions.
- ctx upgrade: Pull the latest version and rebuild the hooks, if available.
- ctx purge: Permanently delete all indexed content from the knowledge base.
- ctx insight: Open a local analytics dashboard with detailed metrics and insights.
From your terminal
- context-mode doctor
- context-mode upgrade
- context-mode insight
- A small debugging script context-mode includes can generate a full diagnostic markdown report for bug reports.
Privacy, Security, and Architecture
Context Mode is designed to operate at the MCP protocol layer, with data staying within sandboxed subprocesses. Nothing leaves your machine by default. Web pages, API responses, logs, and other data are processed in isolation, with per-project SQLite databases storing session data locally. This design minimizes telemetry and cloud dependencies and reinforces privacy-first principles.
Security policies are enforced within the sandbox. If you block certain commands at the root permission level (for example, denying sudo within the policy), those blocks propagate inside the sandbox as well. The security policy format is expressed in Claude Code-style settings and shared across platforms, so you have a consistent policy language across environments.
Session continuity is resilient but platform-dependent. On Claude Code, Gemini CLI, VS Code Copilot, JetBrains Copilot, and OpenClaw, you get broad, feature-complete session continuity with PostToolUse and SessionStart hooks. Some environments—Antigravity, Zed—rely on routing instruction files and do not provide full automated session recovery. Cursor and Kiro have partial coverage and rely on routing files to guide model behavior.
Practical Benchmarks and Try-It-Now Prompts
Benchmarks show dramatic improvements in data savings and session longevity. A typical 315 KB of raw data can be compressed to roughly 5.4 KB of indexed context over a session, extending session duration from about 30 minutes to several hours without losing the ability to resume tasks or recall the last request.
To try Context Mode now, you can run prompts like:
- Deep repo research: “Analyze the architecture of the repository modelcontextprotocol/servers; summarize top contributors and major milestones, then run ctx-stats.”
- Git history analysis: “Clone a target repo and summarize the last 500 commits: top contributors, commit frequency, and most changed files; then run ctx-stats.”
- Web scraping: “Fetch the Hacker News front page, extract post titles, scores, and domains; group by domain; then run ctx-stats.”
- Large JSON API: “Create a local server returning a large JSON with 20,000 records; fetch, index, and locate a secret at a given index; then run ctx-stats.”
- Documentation search: “Fetch the React useEffect docs, index them, and find the cleanup pattern with code examples; then run ctx-stats.”
- Session continuity test: Start a long task sequence, complete 20+ tool calls, then compact; type ctx stats to verify that the session state is preserved and restored after compaction.
The pluggable command surface (ctx-stats, ctx-doctor, ctx-upgrade, ctx-purge, ctx-insight) is designed to be easy to use across the ecosystem, so you can keep your workflows tight and predictable.
Platform Compatibility at a Glance
- Claude Code: Full MCP server with in-process hook support; high session continuity; strong security tracing.
- Gemini CLI: Comprehensive, automatic routing; good cross-platform support; robust session continuity.
- VS Code Copilot and JetBrains Copilot: High coverage with in-editor experience; similar routing semantics as desktop assistants.
- Cursor: Strong tool-event capture; sessionStart support varies by validator; routing instructions via MCP server startup.
- OpenCode and KiloCode: OpenCode-style plugin architecture; routing via hooks when available; some limitations due to sessionStart availability.
- OpenClaw / Pi Agent: Native gateway plugin; full lifecycle hook support; high continuity.
- Codex CLI: Stable MCP and hooks; some upstream limitations exist around input rewriting and the PreToolUse flow.
- Antigravity and Zed: No hooks in this release; rely on manual routing files for enforcement.
- Kiro and Pi: Partial coverage and full extension-driven routing, respectively.
A Short Note on How the Sandbox Works
Each ctx_execute call spawns an isolated subprocess with strict boundaries. The code runs inside its own process, and only stdout is captured and shown in the conversation. No log files or sensitive outputs leak into the chat. The knowledge base is populated by indexing key content in a targeted, token-efficient manner, with BM25 ranking and Porter stemming to ensure relevant results surface quickly. When you search, Context Mode uses smart snippets and proximity-based reranking to pull the exact context you need, not a random excerpt.
Session Recap: What Gets Captured and How It Helps
- Files, Tasks, Plans, Rules, and User Prompts: These are captured as structured events to enable precise reconstruction after a compaction.
- Environment and Ground Truth: Context about working directories, environment, and dependencies is recorded where relevant.
- Subagent and Tool Data: The model’s tool calls, results, and decisions are logged, enabling a detailed replay and analysis if needed.
- Session Guide After Compaction: The system generates a compact, structured narrative that includes the Last Request, Tasks, Plans, Key Decisions, Files Modified, Open Blockers, Git Activity, and MCP Tools Used. This provides a reliable and actionable bridge from old prompts to new.
Contributing and Licensing
Context Mode is released under Elastic License 2.0. The project welcomes contributions and collaboration to extend platform coverage, improve routing, and refine the sandbox architecture. If you want to contribute, you’ll typically start with a local clone, install dependencies, and run the included tests:
- git clone https://github.com/mksglu/context-mode.git
- cd context-mode
- npm install
- npm test
License: Elastic License 2.0 (source-available)
Images and Visuals
- A row of platform badges demonstrates the breadth of tools in use (Microsoft, Google, Meta, Amazon, IBM, NVIDIA, ByteDance, Stripe, Datadog, Salesforce, GitHub, Red Hat, Supabase, Canva, Notion, Hasura, Framer, Cursor). These badges illustrate industry support and ecosystem breadth.
- The YouTube watch thumbnail provides a quick visual cue for the demo.
- A “Watch on YouTube” badge demonstrates the ecosystem’s multimedia resources.
Conclusion: Why Context Mode Matters
Context Mode reframes how we engineer AI-assisted workflows. It couples a robust, privacy-centric sandbox with a powerful, search-driven knowledge base and a code-first mindset that minimizes token usage and maximizes session continuity. The four pillars—Context Saving, Session Continuity, Think in Code, and Output Compression—work in concert to deliver a reliable, scalable, and secure approach to using AI across platforms. For teams that run complex experiments, large codebases, or multi-tool pipelines, Context Mode offers a pragmatic path to keep your model sharp, focused, and aligned with your ongoing work.
If you’re exploring a future where AI agents stay with you, remember: the best partner isn’t just smart; it’s mindful about context. Context Mode makes that mindfulness concrete—preserving what matters, discarding the noise, and letting you and your AI partner build, iterate, and deliver with confidence.
Enjoying this project?
Discover more amazing open-source projects on TechLogHub. We curate the best developer tools and projects.
Repository:https://github.com/mksglu/context-mode
GitHub - mksglu/context-mode: Context Mode: Keep Tool Output Out of Your Agent's Context
Context Mode is a free, local plugin that keeps tool output out of a coding agent's context window, using a sandbox and SQLite FTS5 search. It works with Claude...
github - mksglu/context-mode
Maintain Context Mode: Keep Tool Output Out of Your Agent's Context? Add the badge to your README
Show that the project is featured on TechLogHub and send readers to this write-up.
[](https://techloghub.com/open-source/context-mode?utm_source=techloghub_badge&utm_medium=referral&utm_campaign=readme)