Context Mode MCP Server

repository·main·Indexed 12 days ago

https://github.com/mksglu/context-mode

An MCP server designed to optimize LLM context usage by offloading raw data to sandboxes and indexing session history in SQLite with FTS5. It prevents context window exhaustion and maintains session continuity for agents in Claude Code, Gemini CLI, VS Code Copilot, OpenCode, and Codex CLI. Version 1.0.169 features sandboxed code execution, intent-driven search, and a 'Think in Code' paradigm to reduce context consumption.

Tokens
86.3K
Snippets
200
Records
340
Agent score
94%

What's inside Context Mode

  1. Overview of Context Mode

    main

    Context Mode is an MCP (Model Context Protocol) server designed to solve the 'context problem' in LLM-based agent workflows. It prevents context window bloat by keeping raw data (like large file snapshots, logs, or GitHub issues) out of the main conversation window and instead managing it via sandbox tools and indexed storage.

    Key capabilities include:

    • Context Saving: Reduces context usage significantly (e.g., 98% reduction) by keeping raw data in sandboxes rather than the context window.
    • Session Continuity: Uses SQLite and FTS5 indexing to track file edits, git operations, tasks, and errors. This allows the model to retrieve relevant historical data via BM25 search even after conversation compaction, ensuring it picks up exactly where it left off.
    • Code-Centric Analysis: Encourages the LLM to write and execute scripts to process data rather than reading large amounts of raw data into the context.
    • Non-Intrusive: It manages where data is stored without dictating the model's conversational style or prose length.
  2. Subagent Tool Routing

    main
    Subagents automatically receive context-mode tool routing via a PreToolUse hook. You do not need to manually include tool names in subagent prompts; the hook handles the injection. You can simply provide natural language task descriptions, and the subagent will use the appropriate context-mode tools.
  3. Explore codebases with context-mode

    main

    When exploring a repository, follow these patterns to optimize efficiency and context usage:

    1. Batch Operations: Prefer a single context-mode/ctx_batch_execute call over multiple individual calls like ListDir, Read, Grep, or shell commands.
    2. One-off Answers: Use context-mode/ctx_execute for single computed answers.
    3. Single File Analysis: Use context-mode/ctx_execute_file for deep dives into a specific file.
    4. Durable Recall: For information you need to remember across multiple follow-up questions, use context-mode/ctx_index with a descriptive source, then retrieve it later using context-mode/ctx_search.

    Output Rule: Always return concise derived answers. Avoid pasting raw command dumps, full files, large search results, or raw HTML into the conversation.

  4. Important limitations of ctx-purge

    main

    Keep the following constraints in mind when managing context-mode data:

    • No Undo: Once data is purged, it is gone. You must re-index content if it is needed again.
    • Exclusive Deletion: ctx_purge is the only way to delete session data.
    • Incompatibility with other commands: The commands /clear and /compact do NOT affect any context-mode data.
    • Read-only stats: The ctx_stats command is read-only and cannot be used to modify or delete data.
  5. Understand routing enforcement and hooks

    main

    Routing enforcement is the mechanism that prevents context bloat. While instruction files (like CLAUDE.md or AGENTS.md) guide the model via prompts, they cannot physically block tool execution.

    Hooks are programmatic interceptors that can:

    1. Block dangerous or unrouted commands (e.g., a curl command that would dump 56KB of data into the context).
    2. Redirect tools to a sandbox.
    3. Capture user prompts and tool results to maintain session continuity.

    Always enable hooks where supported to maximize context savings. Without hooks, a single unrouted tool output can wipe out the benefits of the system. Hook-capable platforms typically achieve ~98% context savings, whereas platforms relying only on instruction files achieve ~60%.

  6. How Context Mode solves context bloat with ctx_execute()

    main

    Instead of using multiple tool calls to read many files into the context window (which consumes significant tokens), Context Mode encourages a 'Think in Code' paradigm. The agent should write a script that performs the required analysis and only outputs the final result via console.log(). This approach can reduce context consumption by orders of magnitude (e.g., from 700 KB to 3.6 KB).

    // 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'));
    `);
  7. Guidelines for extending SQLiteBase

    main

    If you are implementing a new subclass of SQLiteBase, follow these architectural constraints to maintain multi-writer compatibility:

    • Do NOT apply db.pragma("locking_mode = EXCLUSIVE") within the SQLiteBase constructor or within applyWALPragmas.
    • Do NOT implement single-writer enforcement (like lockfiles) in the database layer. Process-identity invariants (ensuring only one MCP process runs per project) should be handled in the process layer (e.g., src/util/sibling-mcp.ts).
    • If you require single-writer semantics for a specific subclass, you must explicitly add the locking logic within that specific subclass's constructor and provide documentation for why it is necessary.
  8. Understand Progressive Throttling

    main

    To manage resource usage, Context Mode implements progressive throttling on tool calls:

    • Calls 1-3: Normal results (2 per query).
    • Calls 4-8: Reduced results (1 per query) and a warning is issued.
    • Calls 9+: Calls are blocked and the user is redirected to use ctx_batch_execute instead.
  9. How the Sandbox works for code execution

    main

    When using ctx_execute, each call spawns an isolated subprocess with its own process boundary. Scripts cannot access the memory or state of other scripts.

    Key behaviors:

    • Context Isolation: Only the stdout of the subprocess enters the conversation context. Raw data (log files, API responses, snapshots) remains inside the sandbox.
    • Supported Languages: JavaScript, TypeScript, Python, Shell, Ruby, Go, Rust, PHP, Perl, R, Elixir, and C#.
    • Performance: Bun is automatically detected to provide 3-5x faster JS/TS execution.
    • CLI Authentication: Authenticated CLIs like gh, aws, gcloud, kubectl, and docker work via credential passthrough. They inherit environment variables and config paths without exposing them to the conversation.
    • Intent-Driven Filtering: If output exceeds 5 KB and an intent is provided, Context Mode indexes the full output and returns only the relevant matches based on your intent.
  10. Distinguish between Routing Redirects and Security Restrictions

    main

    When implementing or modifying deny reasons in hooks/core/routing.mjs, you must distinguish between two distinct types of denials. Using the wrong vocabulary can cause LLM agents to incorrectly assume a security restriction exists when they should actually be redirecting to a more efficient tool.

    CASE A: Routing Redirect

    Use this when an action is supported but should be performed via a different, more context-efficient tool (e.g., using ctx_fetch_and_index instead of WebFetch).

    Requirements for CASE A strings:

    • Opening verb: Must start with "redirected to <ctx_tool>".
    • Affirm Capability: Must include a positive statement like <ctx_tool> has full network access to signal this is not a restriction.
    • Specify Tool: Must name the alternative tool as an imperative call (e.g., Call ctx_fetch_and_index(url, source) now).
    • Retry Hint: Must end with a positive imperative retry hint (e.g., "Retry the same call on a transient DNS error (EAI_AGAIN, ETIMEDOUT, ENETUNREACH)").
    • Prohibitions:
      • DO NOT use the word BLOCKED (case-insensitive/bare).
      • DO NOT use negations like "NOT a network restriction" or "Do NOT retry with...".
      • DO NOT include organizational rationale like "for context-window efficiency" or "for performance".

    CASE B: True Security / Policy Restriction

    Use this when an action is genuinely denied by a security gate, deny-pattern check (e.g., accessing private IPs), or unsupported sandbox capability.

    Requirements for CASE B strings:

    • Opening verb: Use "denied" or "blocked by security policy".
    • Cite Rule: Must cite the specific pattern or rule being violated.
    • Suggestion: May optionally suggest a safe alternative.
  11. How to prevent context window flooding in context-mode

    main

    To protect the context window from being flooded with large amounts of raw data (which can dump up to 56 KB per unrouted command), follow the Think in Code principle.

    Instead of reading raw data, large files, or web content directly into the context, you must program the analysis. Use the sandbox tools to process data and only return the final answer via console.log() to stdout. This ensures only the relevant result enters the context, rather than the entire dataset.

    Key Rules:

    • Analyze/Filter/Search: Use ctx_execute(language, code) with Node.js built-ins (fs, path, child_process).
    • Web Content: Never use curl or wget directly. Use ctx_fetch_and_index(url, source) or ctx_execute with fetch to ensure raw HTML stays out of the context.
    • Large Files: Use ctx_execute_file(path, language, code) for analysis/exploration instead of the read tool.
    // Instead of reading a 100KB file into context, do this:
    // ctx_execute(language: "javascript", code: "...")
    
    const fs = require('fs');
    const path = require('path');
    
    try {
      const data = fs.readFileSync(path.join(process.cwd(), 'large_data.json'), 'utf8');
      const parsed = JSON.parse(data);
      // Perform analysis logic here
      console.log(parsed.target_value); // ONLY the answer enters context
    } catch (err) {
      console.error(err.message);
    }
  12. Tool selection and execution patterns

    main

    Use the following tool hierarchy to optimize context usage and performance:

    1. MEMORY: Use ctx_search(sort: "timeline") to check prior context after resuming a session before asking the user for information.
    2. GATHER: Use ctx_batch_execute(commands, queries) to run multiple commands and auto-index results. This replaces many individual calls. Each command should follow the format: {label: "header", command: "..."}.
    3. FOLLOW-UP: Use ctx_search(queries: ["q1", "q2", ...]) to pass multiple questions as an array in a single call.
    4. PROCESSING: Use ctx_execute(language, code) or ctx_execute_file(path, language, code) for sandbox-based processing. Only stdout is returned to the context.
    5. WEB: Use ctx_fetch_and_index(url, source) followed by ctx_search(queries).
    6. INDEX: Use ctx_index(content, source) to store content in FTS5 for later retrieval.

    Parallel I/O

    For network or API-heavy batches, pass concurrency: 4-8 to ctx_batch_execute and ctx_fetch_and_index. For CPU-bound tasks (testing, building, linting), keep concurrency: 1.