Skip to main content
Glama
OpenCode Context Optimizer (OCCE)

OpenCode Context Optimizer (OCCE)

by SammySN-car

OpenCode Context Optimizer (OCCE)

Tests Coverage Python Protocol License: MIT

Context optimization & token-saving MCP server for OpenCode CLI, Claude Code, and Cursor.
Cut prompt token burn by 75% to 90% on free-tier models (Big Pickle, MiMo, Qwen, DeepSeek) to prevent sliding-window rate limit lockouts and eliminate "lost-in-the-middle" attention degradation.


The Problem: The Agent Loop Multiplier

When using OpenCode CLI with free models routed through the OpenCode Zen gateway (big-pickle, mimo-v2.6-flash-free), models are governed by:

  1. Sliding-Window Rate Limits: Server-side quotas tracking in-flight and rolling prompt token volume. Crossing the threshold triggers sudden Rate limit exceeded lockouts lasting hours to 24–48 hours.

  2. Attention Degradation ("Lost in the Middle"): Beyond 32,000–50,000 tokens, free open-weight models begin hallucinating line offsets, repeating tool calls, and dropping system prompt guidelines.

  3. The Agent Loop Multiplier: In an autonomous coding agent, every intermediate tool execution (read_file $\to$ bash $\to$ edit $\to$ pytest) re-transmits the entire cumulative session history.

Standard OpenCode 6-Turn Bug-Fix Loop:
Turn 1: Prompt + Read file (450 LOC) ──────>  5,000 prompt tokens
Turn 2: Run pytest (50 passing tests) ─────>  8,000 prompt tokens
Turn 3: Read helper module (300 LOC) ──────> 10,400 prompt tokens
Turn 4: Edit file patch ───────────────────> 11,600 prompt tokens
Turn 5: Re-run pytest ─────────────────────> 14,600 prompt tokens
Turn 6: Final answer ──────────────────────> 15,200 prompt tokens
──────────────────────────────────────────────────────────────────
CUMULATIVE TOKENS INGESTED BY ZEN GATEWAY:   51,100 TOKENS (Quota Saturated!)

With OCCE, the exact same 6-turn loop consumes ~6,800 cumulative tokens (86.7% overall reduction).


Related MCP server: mcp-context-condenser

Core Tools

OCCE exposes 6 specialized tools adhering to the Model Context Protocol (MCP):

Tool

What It Does

Token Reduction

code_skeleton

Extracts an AST outline (classes, signatures, type annotations, and first-line docstrings) with line-range anchors ([L45-88: 43 lines omitted]). Replaces bodies with stubs so agents never hallucinate omitted code.

80% – 94%

symbol_slice

Extracts the exact, un-stubbed implementation of a single requested class, function, or method. Used in tandem with code_skeleton to ensure 100% search/replace accuracy during file edits.

85% – 95%

smart_exec

Executes shell commands through a 4-stage noise-gate: ANSI escape code stripping, carriage return \r collapse, package manager progress bar & spinner suppression, and saliency-preserving head/tail truncation.

70% – 95%

test_compress

Multi-framework test reducer for Pytest, Rust (Cargo test), Go test, and Jest/Vitest. Collapses 100% passing suites into a single 1-line summary; isolates exact failure tracebacks and assertion errors when tests fail.

90% – 95%

diff_compact

Generates a zero-context (-U0) Git diff that eliminates unchanged surrounding lines and git index metadata.

75% – 85%

token_ledger

Tracks real-time session token burn, cumulative tokens saved, and warns the agent when crossing attention health zones (GREEN <25k**, **YELLOW 25k–40k**, **RED >40k).

Prevents Lockout


Quantified Benchmarks

Measured on realistic Python, Go, and TypeScript repositories:

Scenario

Raw Baseline Cost

OCCE Optimized Cost

Net Token Savings

Inspect 3 Architecture Files

~11,000 tokens

~850 tokens (code_skeleton)

92.2%

Run Pytest Suite (42 pass, 1 fail)

~2,800 tokens

~190 tokens (test_compress)

93.2%

Package Install (pip / npm)

~3,400 tokens

~120 tokens (smart_exec)

96.4%

Multi-File Git Diff Inspection

~2,200 tokens

~340 tokens (diff_compact)

84.5%

Complete 6-Turn Bug Fix & Test Loop

51,100 tokens

~6,800 tokens

86.7% Overall

Live Production 130-Turn Session

~340,000 tokens

~107,000 tokens

~232,596 Tokens Saved


Architecture: Dual-Layer Defense (MCP + Companion Plugin)

OCCE operates across two coordinated layers:

  1. Precision MCP Server (occe/server.py):

    • Zero-dependency Python server exposing 6 precision tools over stdio (code_skeleton, symbol_slice, smart_exec, test_compress, diff_compact, token_ledger).

    • Polyglot support: AST-based for Python; heuristic block slicing for TypeScript, TSX, JavaScript, JSX, Go, and Rust.

    • Resilient workspace resolution: Automatically consumes rootPath and rootUri handshakes per MCP (2024-11-05) standard.

  2. OpenCode Companion Plugin (plugins/occe-guard.js):

    • Hot-reloaded directly into OpenCode 2.x runtimes without restarting CLI sessions.

    • Pre-execution hook (execute.before): Intercepts unconstrained file dumps and guides agents toward precision AST tools.

    • Post-execution hook (execute.after): Strips ANSI sequences, collapses 100% passing test suites (pytest, cargo, jest/vitest), and applies head/tail truncation on verbose logs (>70 lines), glob dumps (>40 paths), and grep search floods (>35 matches).

    • Session context hook (context, compaction, generate): Injects high-signal steering guidelines directly into event.system before each inference turn.


Quickstart & Setup

OCCE runs on standard Python 3.10+ with zero external dependencies.

1. Installation

Clone the repository:

git clone https://github.com/SammySN-car/opencode-context-mcp.git
cd opencode-context-mcp

2. Configure OpenCode CLI (opencode.jsonc)

Add OCCE to your project's opencode.jsonc (or global ~/.config/opencode/config.json):

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "context-optimizer": {
      "command": "python",
      "args": ["-m", "occe.server"]
    }
  },
  // Optional: Restrict built-in tools to guide model toward OCCE precision tools
  "permission": {
    "read": "deny",      // Prompts agent to use code_skeleton / symbol_slice
    "bash": "ask"        // Prompts agent to use smart_exec / test_compress
  }
}

3. Configure Claude Code / Claude Desktop

Add to claude_desktop_config.json:

{
  "mcpServers": {
    "context-optimizer": {
      "command": "python",
      "args": ["-m", "occe.server"]
    }
  }
}

OpenCode Companion Plugin (occe-guard.ts)

For users who prefer 100% transparent optimization without changing prompt habits, OCCE includes a companion plugin hook.

Copy plugins/occe-guard.ts into .opencode/plugins/:

  • Automatically sanitizes native bash tool output (stripping ANSI codes and collapsing test passes).

  • Automatically monitors native read calls on files $>250$ lines and inserts a token-budget reminder.


Architecture

flowchart TD
    Client["OpenCode CLI / Claude Code / Cursor"] -- "JSON-RPC 2.0 (stdio)" --> Server["OCCE MCP Server (occe/server.py)"]

    subgraph OCCE["OpenCode Context Engine"]
        Server --> Router{"Tool Router"}
        Router --> Skeletons["AST Engine\n(ast_skeleton.py)"]
        Router --> NoiseGate["Noise-Gate Pipeline\n(noise_gate.py)"]
        Router --> TestReducers["Test Reducers\n(test_reducers.py)"]
        Router --> DiffEngine["Zero-Context Diff\n(diff_engine.py)"]

        Server --> Ledger["Token Ledger & Health Monitor\n(ledger.py)"]
        Server --> Tombstones["Tombstone Tracker\n(tombstone.py)"]
    end

    Skeletons --> Output["80-94% Token Reduction"]
    NoiseGate --> Output
    TestReducers --> Output
    DiffEngine --> Output
    Ledger --> Alerts["Attention Zone Alerts\n(GREEN / YELLOW / RED)"]

Running Tests

OCCE includes a comprehensive 57-test verification suite covering AST transformations, regex noise suppression, test parsing for 4 frameworks, and JSON-RPC wire protocol compliance:

# Install pytest if not already installed
pip install pytest

# Run all 57 tests
python -m pytest -v

License

MIT License. Built by Samar Nathani.

Available Tools

6 tools
code_skeletonA

Extract an AST outline of classes, functions, signatures, argument type hints, and docstrings from a source file, replacing bodies with '...'. Consumes 80-94% fewer tokens than raw file reading.

Inputs: path (required), depth.

diff_compactA

Generate a zero-context (-U0) git diff of uncommitted changes or specific files, eliminating unchanged surrounding context lines and git index boilerplate.

Inputs: staged, filepath.

smart_execB

Execute a shell command with real-time ANSI escape stripping, carriage-return collapse, package manager progress bar & spinner suppression, and intelligent head/tail truncation.

Inputs: command (required), max_lines.

symbol_sliceB

Extract the exact implementation of a single class or function by symbol name (e.g., 'PaymentGateway' or 'PaymentGateway.charge' or 'charge'), avoiding the need to read the entire file.

Inputs: path (required), symbol (required).

test_compressA

Run test suites (pytest, cargo test, go test, jest/vitest) and output only failing tests, assertion errors, and clean stack frames, collapsing passed tests into a 1-line summary.

Inputs: command (required).

token_ledgerB

Check current session token usage, cumulative savings achieved by OCCE, and free-model attention health zone (GREEN / YELLOW / RED alert).

Inputs: no named parameters.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 6 tools

    Disambiguation4/5

    Each tool has a distinct role: AST outline vs. single-symbol extraction vs. command execution vs. test output vs. diff vs. token accounting. The only mild overlap is code_skeleton vs. symbol_slice, where both read source code, but the outline-vs-implementation distinction in the descriptions resolves it.

    Naming Consistency4/5

    All names are snake_case two-word compounds in a modifier+noun style (code_skeleton, symbol_slice, test_compress, diff_compact, token_ledger), with smart_exec being the only slight deviation in verb-vs-noun form. Readable and predictable overall.

    Tool Count5/5

    Six tools for a context-optimization server is well-scoped: two for reading code, three for compressing execution/test/diff output, one for telemetry. No filler tools.

    Completeness4/5

    The surface covers code reading, command execution, test output, diffs, and token accounting, which are the core levers of context reduction. A small gap is the absence of a symbol/search tool to locate symbols across files before calling symbol_slice.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables Claude Code to reduce token usage by 70-90% using a local LLM for codebase indexing, tool output compression, and turn summarization.
      33 npm
      3
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables AI coding agents to reduce token usage by condensing source code into AST skeletons, extracting specific symbols, compressing logs, and estimating token budgets.
      4
      MIT