cctx
Reduce Claude Code token usage by 70-90% using a free local LLM (Ollama). MCP server + Stop hook with codebase indexing, tool output compression, and turn summarization.
Install / Use
claude mcp add anil7948 -- npx -y github:anil7948/cctxIf the server publishes to npm under a different name, use that package instead — check the repo README.
MCP Server
Model Context Protocol server
Quality Score
Category
AI & Machine LearningSupported Platforms
Tags
Skill content
View source on GitHubcctx — Claude Code Token Optimizer
Reduce Claude Code token usage by 70–90% using a free, local LLM.
cctx is a CLI tool + MCP server that runs three token-reduction layers alongside Claude Code — codebase indexing, tool output compression, and turn summarization — all powered by Ollama running on your machine. No API calls, no subscription fees, no config beyond cctx setup.
Why this exists
Claude Code's context window fills up fast. Every bash run, every file read, every grep result gets appended verbatim. By turn 15 you're paying for — and waiting on — tens of thousands of tokens of resolved history and raw tool noise that Claude no longer needs in full.
cctx intercepts that bloat at three layers using a small local LLM (phi3.5, 2.2 GB) that runs entirely on your machine:
| Layer | Problem | What cctx does | Typical savings |
|---|---|---|---|
| 1 — Codebase index | Session start reads 15–25 files | Pre-built semantic file map served via MCP; query by topic to get only relevant files | ~90% on session start |
| 2 — Tool output compression | bash/read_file/grep output appended raw | PostToolUse hook: rules-based + local LLM compression, auto-registered on setup | ~70% on agentic loops |
| 3 — Turn summarization | History bloats over 10+ turns | Async structured JSON summary of each completed turn; session consolidation maintains current-truth decisions | ~83% on long sessions |
| 4 — Cross-session memory | Context resets every session | Key decisions and patterns extracted at flush; injected into every future session automatically | Avoids re-explaining project state |
All four layers are automatic after cctx setup. You never call any tools yourself.
What's new in v1.3.0
| Feature | What it does | |---------|-------------| | Smaller context pages | Page size reduced to 20K chars — fixes truncation when Claude Code spills large tool results to a preview file | | Filler note stripping | Generic notes ("no significant exports", "standard module") are dropped — reduces page weight by ~30% | | Smarter FTS search | Stopwords filtered, wildcard suffix matching, fallback to token-scored LIKE scan when FTS returns nothing |
What's new in v1.2.0
| Feature | What it does |
|---------|-------------|
| FTS5 keyword search | get_codebase_context(query: "auth") returns only relevant files |
| Context utilization monitor | get_optimized_context warns at 75% capacity to compact before quality degrades |
| Session checkpoints | Synthesizes a "pick up where you left off" note at session start |
| Deterministic structural extraction | Exports/imports parsed by regex — eliminates hallucinated APIs |
| Safe compression guards | Blocks compression that drops or invents code symbols |
| Zero-touch MCP upgrade | npm install -g cctx-optimizer re-registers MCP automatically |
What's new in v1.1.0
| Feature | What it does |
|---------|-------------|
| Cross-session memory | Project facts persist across sessions via project_knowledge |
| Session consolidation | Per-turn summaries distilled into always-current session_knowledge |
| PostToolUse compress hook | Auto-compresses bash/read_file/grep output at 60–70% |
| Paginated codebase index | No truncation on 100+ file projects |
| Parallel indexer | Large projects indexed in minutes instead of hours |
| GPU acceleration | Auto-detects Metal/CUDA for Ollama calls |
Architecture
cctx runs as a local MCP server that Claude Code calls on every turn. There is no proxy, no cloud hop, and no change to how you use Claude Code. All three optimization layers operate in the background.
The optimization pipeline
Session start — instead of Claude reading 15–25 files to orient itself, get_codebase_context returns a pre-computed semantic map of your project: purpose, exports, and key imports per file, built by a local LLM and cached in SQLite. Claude understands your codebase instantly without spending a single input token on raw file content.
During tool calls — when Claude runs bash, grep, a test suite, or reads a file, compress_tool_result intercepts the output before it enters context. Structured formats (bash exit code + lines, grep matches, test pass/fail + failing assertions) are compressed with deterministic rules at zero added latency. Unpredictable content (file bodies, web results) goes through the local LLM. The distinction matters: an agentic loop making 20 tool calls cannot afford 20 LLM round-trips. Rules handle the volume; the LLM handles the complexity.
End of turn — the Claude Code Stop hook fires cctx session hook-stop, which records the raw turn and queues async summarization. The local LLM converts the full turn into a structured JSON summary — preserving file paths, decisions, and open questions, discarding the rest. Each summary is roughly 10x smaller than the original.
Next turn — get_optimized_context assembles the session: all prior turns as compact summaries, plus the most recent turn verbatim. Claude picks up exactly where it left off, without re-reading resolved history.
On privacy: every step above runs on your machine. Your code, your tool outputs, and your conversation history never leave your local environment.
Requirements
- Node.js 20+
- macOS, Linux, or Windows (WSL) — Ollama supports all three
- ~2.5 GB free disk for the default model (
phi3.5) - Claude Code installed
Quick start
npm install -g cctx-optimizer
cctx setup # ~5 min on first run (model download is the slow part)
Restart Claude Code, then start coding. After your first session:
cctx session stats
That's it. See Install and setup for the full walkthrough.
Setup & Integration
cctx setup is idempotent and non-destructive. It manages its own Ollama binary in ~/.cctx/bin/ on a dedicated port (11435), completely isolated from any existing Ollama installation. Safe to re-run at any time.
Install
npm install -g cctx-optimizer
cctx setup
Or build from source:
git clone https://github.com/anil7948/cctx
cd cctx
npm install && npm run build && npm link
cctx setup
What cctx setup does
The wizard runs eight steps and prints progress for each:
- Download Ollama — fetches a managed binary to
~/.cctx/bin/, isolated from any system Ollama you already have - Start daemon — launches Ollama on port
11435 - Pull model — downloads
phi3.5(~2.2 GB — this is the slow step, runs once) - Register MCP server — writes to
~/.claude.json(Claude Code 2.x); automatically refreshed on everynpm install -gupgrade — no manual re-registration needed - Register Stop hook — writes to
~/.claude/settings.jsonto record sessions on exit - Write tool instructions — writes
~/.cctx/instructions.mdand registers it via~/.claude/CLAUDE.md - Index project — builds the initial semantic map of your current project
- Smoke test — verifies the full summarization pipeline end-to-end
Non-interactive mode:
cctx setup --model phi3.5 --yes
After setup
- Restart Claude Code — it reads the MCP config and instructions at launch
- Verify —
cctx doctor(all checks should be green) - Index each project —
cctx index runin any project directory you work in
Token savings: what to expect
| Session type | Layer 2 savings | Layer 3 savings | Total | |---|---|---|---| | Short session (1–3 turns) | Minimal | None | ~0% | | Medium session (5–10 turns) | 50–70% on tool-heavy turns | 40–60% | 40–65% | | Long agentic session (15+ turns) | 70–85% | 80–90% | 70–90% |
Layer 2 only activates when Claude makes large tool calls. Read-only or conversational sessions won't show compression numbers — this is expected.
Layer 3 needs at least 3–4 turns before summaries exist. Check cctx session stats after a real coding session, not after a quick question.
Verify it's working
cctx doctor
Output:
✔ Ollama binary ~/.cctx/bin/ollama
✔ Daemon running pid 12345 port 11435
✔ Active model phi3.5 installed
✔ Claude Code MCP registered
✔ Stop hook registered (~/.claude/settings.json)
✔ Codebase index 57 files, last run 2026-05-15T10:00:00Z
✔ Summarizer 1.3s
Watch live savings during a session:
cctx session stats --watch # refreshes every 3 seconds
Commands
Setup and lifecycle
| Command | Description |
|---|---|
| cctx setup [--model <name>] [--yes] | One-time wizard. Safe to re-run — all steps are idempotent. |
| cctx daemon start\|stop\|status\|restart | Manage the background Ollama daemon. |
| cctx doctor | Health check with per-check fix hints. |
| cctx register-instructions | Re-register tool instructions after reinstalls or Claude Code updates. |
| cctx uninstall [--keep-models] | Remove daemon, config, Stop hook, instructions, and optionally models. |
Models
cctx model list
cctx model set <name>
cctx model pull <name>
cctx model remove <name>
The default model is phi3.5 (2.2 GB), which has been tested and confirmed to work reliably with cctx's JSON summarization pipeline. It runs on CPU without a GPU and uses one automatically when available.
Support for additional Ollama models is planned. Any model available at ollama.com/library can be pulled and set via cctx model pull <name> && cctx model set <name>, though JSON output reliability may vary by model.
Switch models: cctx model pull <name> && cctx model set <name> && cctx daemon restart
Codebase index (Layer 1)
cctx index run [--path <dir>] [--force]
Index changed files. Shows (N/total) progress per file.
First run: ~5-8s per file on CPU. Subsequent runs skip unchanged files.
cctx index status
Show indexed file count, pending changes, last run time.
cctx index watch [--path <dir>]
Watch for file saves and re-index automatically. Reports each batch.
Use --force to regenerate all summaries (e.g. after switching models).
Sessions (Layer 3)
cctx session list List sessions with turn count
cctx session stats [--session-id <id>] [--watch] Token savings breakdown; --watch refreshes live
cctx session flush [--session-id <id>] Force summarization of pending turns
cctx session export [--format json|md] [--out file] Export summaries + codebase map
Force context compaction mid-session
/compact-local
Inside Claude Code, or from a shell: cctx session flush
CLAUDE.md injection
cctx inject [--file CLAUDE.md]
Writes the semantic project map into a managed block in CLAUDE.md. Useful for projects where you want the map baked in even without the MCP server active.
Config
cctx config show
cctx config get <key> # e.g. cctx config get model.active
cctx config set <key> <val> # e.g. cctx config set ollama.port 11436
Keys are dotted paths. Values auto-coerce (true/false → boolean, numeric strings → number).
Configuration reference
Global config: ~/.cctx/config.json. Per-project overrides: <project>/.cctx/config.json. Project values deep-merge over globals.
| Key | Default | Description |
|---|---|---|
| ollama.port | 11435 | Separate from system Ollama on 11434 |
| ollama.managedByUser | false | Set true to use your own Ollam
Truncated for display — read the full file on GitHub.
Related Skills
claude-mem
93.3kPersistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
Understand-Anything
81.6kGraphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.
Agent-Reach
78.2kGive your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.
ruflo
70.6k🌊 The original agent meta-harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
