OpenCode Context Optimizer (OCCE)
This MCP server reduces context/token usage by giving coding agents precision tools for code inspection, command/test output compression, diffs, and token monitoring.
code_skeleton: Extracts AST outlines with signatures/docstrings and replaces bodies with stubs.symbol_slice: Extracts the exact implementation of a named class/function/method.smart_exec: Runs shell commands while stripping ANSI/progress noise and truncating output.test_compress: Runs pytest/cargo/go/jest/vitest and collapses passing tests, isolating failures.diff_compact: Produces compact zero-context git diffs.token_ledger: Reports session token usage, savings, and GREEN/YELLOW/RED attention health.Works as a zero-dependency stdio MCP server for OpenCode, Claude Code, and Cursor, with Python AST and heuristic polyglot support.
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: mcp-context-condenser
Core Tools
OCCE exposes 6 specialized tools adhering to the Model Context Protocol (MCP):
Tool | What It Does | Token Reduction |
| Extracts an AST outline (classes, signatures, type annotations, and first-line docstrings) with line-range anchors ( | 80% – 94% |
| Extracts the exact, un-stubbed implementation of a single requested class, function, or method. Used in tandem with | 85% – 95% |
| Executes shell commands through a 4-stage noise-gate: ANSI escape code stripping, carriage return | 70% – 95% |
| 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% |
| Generates a zero-context ( | 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). | 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 ( | 92.2% |
Run Pytest Suite (42 pass, 1 fail) | ~2,800 tokens | ~190 tokens ( | 93.2% |
Package Install ( | ~3,400 tokens | ~120 tokens ( | 96.4% |
Multi-File Git Diff Inspection | ~2,200 tokens | ~340 tokens ( | 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:
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
rootPathandrootUrihandshakes per MCP (2024-11-05) standard.
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),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-mcp2. 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
bashtool output (stripping ANSI codes and collapsing test passes).Automatically monitors native
readcalls 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 -vLicense
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.
Codebase intelligence for agents: 152 structured artifacts across 21 programs, one call.
Reduces AI Agent token usage by 40% via three-stage SOP workflow.
Shared memory for coding agents. Stop re-explaining your codebase every session.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables Claude Code to reduce token usage by 70-90% using a local LLM for codebase indexing, tool output compression, and turn summarization.33 npm3MIT
- 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
- AlicenseNot gradedqualityCmaintenanceEnables AI coding agents to conserve tokens by enforcing rules like delegating heavy work to subagents, checkpointing before token limits, and grepping before reading files.MIT