OpenCode Context Optimizer (OCCE)
Summary: OCCE is a zero-dependency MCP server that slashes prompt tokens by serving AST skeletons, targeted symbol slices, and noise-filtered command/test/diff output instead of raw file dumps and logs.
code_skeleton— Extract an AST outline (classes, functions, signatures, type hints, docstrings) with bodies stubbed out; 80–94% fewer tokens than reading full files.symbol_slice— Pull the exact implementation of one class, method, or function by name, for accurate inspection and patching without reading whole files.smart_exec— Run shell commands through a noise gate: ANSI stripping,\rcollapse, progress-bar/spinner suppression, and head/tail truncation (default 60 lines).test_compress— Run pytest, cargo, go test, or jest/vitest suites and collapse passing runs into a single line while preserving failure tracebacks and assertion errors.diff_compact— Produce zero-context (-U0) git diffs of unstaged, staged, or specific files, stripping unchanged lines and index metadata.token_ledger— Report session token usage, cumulative savings, and attention health zone (GREEN/YELLOW/RED) to help avoid rate-limit lockouts.Works over MCP stdio for OpenCode CLI, Claude Code, and Cursor, with polyglot AST/heuristic parsing (Python, TS/TSX, JS/JSX, Go, Rust) and native PowerShell-on-Windows execution.
Note:
file_sliceis documented in the README as one of seven tools but is absent from the provided schema, so only the six tools above are actually exposed.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@OpenCode Context Optimizer (OCCE) show me the code skeleton for src/auth.py"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
OpenCode Context Optimizer (OCCE)
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:
Sliding-Window Rate Limits: Server-side quotas tracking in-flight and rolling prompt token volume. Crossing the threshold triggers sudden
Rate limit exceededlockouts lasting hours to 24–48 hours.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.
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: tokencut
Core Tools (MCP Specification 2024-11-05)
OCCE exposes 7 specialized tools with explicit directory hint annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint):
Tool | What It Does | Directive Trigger | Token Reduction |
| Extracts an AST outline (classes, signatures, type annotations, and first-line docstrings) with line-range anchors ( | PREFER OVER READ_FILE for code files > 80 lines | 80% – 94% |
| Extracts the exact, un-stubbed implementation of a single requested class, function, or method. Used in tandem with | PREFER OVER READ_FILE when inspecting or patching functions | 85% – 95% |
| Extracts a bounded window of lines ( | PREFER OVER READ_FILE for partial file inspections | 75% – 90% |
| Executes shell commands through a 4-stage noise-gate: ANSI escape stripping, carriage return | PREFER OVER BASH/SHELL to prevent quota lockouts | 70% – 95% |
| Multi-framework test reducer for Pytest ( | PREFER OVER BASH for running test suites and linters | 90% – 98% |
| Generates a zero-context ( | PREFER OVER RAW GIT DIFF | 75% – 85% |
| 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). | Session token monitor | Prevents Lockout |
Quantified Real-World Benchmarks & Production Telemetry
Measured on realistic Python, Go, and TypeScript repositories, and verified across live multi-thousand turn OpenCode CLI sessions:
Scenario | Raw Baseline Cost | OCCE Optimized Cost | Net Token Savings | Verified In Production |
Inspect 3 Architecture Files | ~11,000 tokens | ~850 tokens ( | 92.2% | Synthetic & Integration |
335-Test Pytest Run | ~18,500 tokens | ~42 tokens (1-line status) ( | 98.2% | Live OpenCode Session ( |
Inspect | ~7,500 tokens (raw file dumps) | ~1,398 tokens ( | 81.4% | Live OpenCode Subagent ( |
Gantt Chart Diffing (#286) | 105,000 chars per diff turn | 68 chars per diff turn | 99.9% | Live PR #286 Fix |
Package Install ( | ~3,400 tokens | ~120 tokens ( | 96.4% | Automated Benchmarks |
Multi-File Git Diff Inspection | ~2,200 tokens | ~340 tokens ( | 84.5% | Automated Benchmarks |
Complete 6-Turn Bug Fix & Test Loop | 51,100 tokens | ~6,800 tokens | 86.7% Overall | Synthetic E2E |
Mega-Session Lifetime Accumulation | 17,400,000 tokens (Triggered 22h 429 lockout) | ~2,600,000 tokens | ~85.1% Total Saved | Live Forensics Audit |
Agent Quality & Fidelity Guarantee: Does OCCE Lower Work Quality?
A common fear with context optimization is information loss. OCCE is engineered around a strict Information Fidelity Principle: compress zero-signal noise (progress bars, passing tests, boilerplate); preserve 100% of high-signal diagnostic and structural data.
Verified by our automated Agent Quality Benchmark Suite (tests/test_agent_quality_fidelity.py):
Edit & Search/Replace Fidelity (
symbol_slice&file_slice):Extracted symbols preserve exact syntax, indentation, and enclosing class context.
Patches generated against slices integrate cleanly into source trees without whitespace mismatches or off-by-one line errors.
Debugging & Failure Diagnosis Fidelity (
test_compress):When tests pass, all passing dots and setup spam collapse into 1 line.
When tests fail,
test_compresspreserves 100% of the failure traceback, assertion diff, filename, and line numbers. Zero diagnostic information is omitted.
API Contract & Type Understanding (
code_skeleton):Preserves all parameter names, default values, type annotations, and first-line docstrings.
An agent reading only the skeleton knows the exact public API contract without hallucinating.
Error Propagation Fidelity (
smart_exec):Preserves nonzero return codes, full stderr, and exception tracebacks on command failure.
Attention Health Preservation:
Beyond 32k tokens, open-weight models suffer from "Lost in the Middle" (forgetting instructions, repeating tool calls). By keeping context under 25k tokens, OCCE keeps agents in the Green Attention Zone, directly improving code generation quality and task completion rates.
Architecture: Dual-Layer Defense (MCP + Companion Plugin)
OCCE operates across two coordinated layers:
Precision MCP Server (
occe/server.py):Zero-dependency Python server exposing 7 precision tools over stdio (
code_skeleton,symbol_slice,file_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
rootPathandrootUrihandshakes per MCP (2024-11-05) standard.Native Windows support: Automatically executes PowerShell (
powershell.exe -NoProfile -Command) on Windows and bash on Unix.
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), compresses clean git status runs (## branch...), and applies head/tail truncation on verbose logs (>70 lines),globdumps (>40 paths), andgrepsearch floods (>35 matches).Session context hook (
context,compaction,generate): Injects high-signal steering guidelines directly intoevent.systembefore 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
pip install -e .2. Configure OpenCode CLI (opencode.jsonc)
Add OCCE and its companion hook plugin to your project's opencode.jsonc (or global ~/.config/opencode/opencode.jsonc):
{
"$schema": "https://opencode.ai/config.json",
"plugins": [
"C:/Users/samar/.config/opencode/plugins/occe-guard.js"
],
"mcp": {
"servers": {
"context-optimizer": {
"type": "local",
"command": ["python", "-m", "occe.server"]
}
}
}
}3. Configure Claude Code CLI & Claude Desktop
Add to your Claude configuration (~/.claude.json or %APPDATA%\Claude\claude_desktop_config.json):
{
"mcpServers": {
"context-optimizer": {
"command": "python",
"args": ["-m", "occe.server"]
}
}
}Verify with:
claude mcp get context-optimizer
# Output: Status: √ Connected4. Configure Cursor IDE
Add to .cursor/mcp.json in your project or global ~/.cursor/mcp.json:
{
"mcpServers": {
"occe": {
"command": "python",
"args": ["-m", "occe.server"]
}
}
}Architecture Diagram
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 --> FileSlice["File Slicer\n(file_slice.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"]
FileSlice --> Output
NoiseGate --> Output
TestReducers --> Output
DiffEngine --> Output
Ledger --> Alerts["Attention Zone Alerts\n(GREEN / YELLOW / RED)"]Running Tests
OCCE includes a comprehensive 70-test verification suite covering AST transformations, regex noise suppression, test parsing for 4 frameworks, line-range slicing, quality fidelity benchmarks, and JSON-RPC wire protocol compliance:
# Run all 70 tests
pytest -v
# Run node.js guard hook compression tests
node tests/test_guard_compression.mjsLicense
MIT License. Built by Samar Nathani.
Available Tools
6 toolscode_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
Scored across 6 tools
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.
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.
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.
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
Related MCP Connectors
Compress coding-agent context ~64%. Hosted Neural Keep MCP for Cursor/Claude/Codex.
Cuts coding agent token burn up to 72% continuously via contradiction-free memory & verification.
AST context pruner, token budget planner, fuzzy patcher, and code solvers.
Codebase intelligence for agents: 152 structured artifacts across 21 programs, one call.
Related MCP Servers
- AlicenseAqualityBmaintenanceEnables AI coding agents to reduce token usage by condensing source code into AST skeletons, extracting specific symbols, compressing logs, and estimating token budgets.4MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents to compress terminal output and file context in real time, preserving full error tracebacks while reducing token consumption by 60-85%.43MIT
- AlicenseBqualityCmaintenanceEnables coding agents to reduce context tokens by requesting file outlines, individual symbols, compact searches, and condensed test, lint, and type-check failures instead of reading whole files or raw command output.611 npmMIT
- AlicenseBqualityBmaintenanceEnables AI coding agents to reduce token usage and context bloat through AST skeletonization, prompt distillation, caching, and token-budget governance while preserving essential code context.76,429 npm4,319 PyPI48MIT