NAME
lean-ctx β Hybrid Context Optimizer β Shell Hook + MCP Server. Reduces LLM token consumption by 89-99%. Single Rust binary, zeroβ¦
SYNOPSIS
npm install -g lean-ctx-binINFO
DESCRIPTION
Hybrid Context Optimizer β Shell Hook + MCP Server. Reduces LLM token consumption by 89-99%. Single Rust binary, zero dependencies.
README
βββ ββββββββ ββββββ ββββ βββ βββββββββββββββββββ βββ
βββ βββββββββββββββββββββ βββ βββββββββββββββββββββββββ
βββ ββββββ ββββββββββββββ βββ βββ βββ ββββββ
βββ ββββββ ββββββββββββββββββ βββ βββ ββββββ
βββββββββββββββββββ ββββββ ββββββ ββββββββ βββ ββββ βββ
βββββββββββββββββββ ββββββ βββββ βββββββ βββ βββ βββ
The Intelligence Layer for AI Coding
The Intelligence Layer for AI Coding
Shell Hook + Context Server Β· 25 tools Β· 90+ patterns Β· Single Rust binary
Website Β· Install Β· How It Works Β· Tools Β· Patterns Β· Changelog Β· Discord
lean-ctx reduces LLM token consumption by up to 99% through three complementary strategies in a single binary β making AI coding faster, cheaper, and more effective.
β‘ What It Does
Without lean-ctx: With lean-ctx:LLM ββ"read auth.ts"βββΆ Editor βββΆ File LLM ββ"ctx_read auth.ts"βββΆ lean-ctx βββΆ File β² β β² β β β ~2,000 tokens (full file) β β ~13 tokens (cached) β cache+hash β ββββββββββββββββββββββββββββββββββββ βββββββ (compressed) ββββββββ΄βββββββββββββ
LLM ββ"git status"βββΆ Shell βββΆ git LLM ββ"git status"βββΆ lean-ctx βββΆ git β² β β² β β β ~800 tokens (raw output) β β ~150 tokens β compress β βββββββββββββββββββββββββββββββββββ βββββββ (filtered) ββββββ΄βββββββββββββββ
| Strategy | How | Impact |
|---|---|---|
| Shell Hook | Transparently compresses CLI output (90+ patterns) before it reaches the LLM | 60-95% savings |
| Context Server | 25 MCP tools for cached reads, mode selection, deltas, dedup, memory | 74-99% savings |
| AI Tool Hooks | One-command integration via lean-ctx init --agent <tool> | Works everywhere |
π― Token Savings β Real Numbers
| Operation | Freq | Without | With lean-ctx | Saved |
|---|---|---|---|---|
| File reads (cached) | 15Γ | 30,000 | 195 | 99% |
| File reads (map mode) | 10Γ | 20,000 | 2,000 | 90% |
| ls / find | 8Γ | 6,400 | 1,280 | 80% |
| git status/log/diff | 10Γ | 8,000 | 2,400 | 70% |
| grep / rg | 5Γ | 8,000 | 2,400 | 70% |
| cargo/npm build | 5Γ | 5,000 | 1,000 | 80% |
| Test runners | 4Γ | 10,000 | 1,000 | 90% |
| curl (JSON) | 3Γ | 1,500 | 165 | 89% |
| docker ps/build | 3Γ | 900 | 180 | 80% |
| Session total | ~89,800 | ~10,620 | 88% |
Based on typical Cursor/Claude Code sessions with medium TypeScript/Rust projects. Cached re-reads cost ~13 tokens.
π Get Started (60 seconds)
# 1. Install (pick one) curl -fsSL https://leanctx.com/install.sh | sh # universal, no Rust needed brew tap yvgude/lean-ctx && brew install lean-ctx # macOS / Linux npm install -g lean-ctx-bin # Node.js cargo install lean-ctx # Rust2. Setup (auto-configures shell + ALL detected editors)
lean-ctx setup
3. Verify
lean-ctx doctor
Troubleshooting
| Problem | Fix |
|---|---|
| Commands broken? | Run lean-ctx-off (fixes current session) |
| Permanent fix? | Run lean-ctx uninstall (removes all hooks) |
| Binary missing? | Aliases auto-fallback to original commands (safe) |
| Manual fix? | Edit ~/.zshrc, remove the lean-ctx shell hook block |
| Preview changes? | lean-ctx init --global --dry-run |
| Diagnose? | lean-ctx doctor |
lean-ctx creates a backup of your shell config before modifying it (~/.zshrc.lean-ctx.bak).
Supported editors (auto-detected by lean-ctx setup)
| Editor | Method | Status |
|---|---|---|
| Cursor | MCP + hooks + rules | β Auto |
| Claude Code | MCP + PreToolUse hooks + rules | β Auto |
| GitHub Copilot | MCP | β Auto |
| Windsurf | MCP + rules | β Auto |
| VS Code | MCP + rules | β Auto |
| Zed | Context Server (settings.json) | β Auto |
| Codex CLI | config.toml + AGENTS.md | β Auto |
| Gemini CLI | MCP + hooks + rules | β Auto |
| OpenCode | MCP + rules | β Auto |
| Pi | pi-lean-ctx npm package | β Auto |
| Qwen Code | MCP + rules | β Auto |
| Trae | MCP + rules | β Auto |
| Amazon Q Developer | MCP + rules | β Auto |
| JetBrains IDEs | MCP + rules | β Auto |
| Google Antigravity | MCP + rules | β Auto |
| Cline / Roo Code | MCP + rules | β Auto |
| Aider | Shell hook + rules | β Auto |
| Amp | Shell hook + rules | β Auto |
| AWS Kiro | MCP + rules | β Auto |
| Continue | MCP + rules | β Auto |
π§ Three Intelligence Protocols
CEPCognitive Efficiency Protocol Adaptive LLM communication with compliance scoring (0-100), task complexity classification, quality scoring, auto-validation pipeline. Measurable efficiency gains |
CCPContext Continuity Protocol Cross-session memory that persists tasks, findings, decisions across chats. LITM-aware positioning for optimal attention placement. -99.2% cold-start tokens |
TDDToken Dense Dialect Symbol shorthand ( 8-25% extra savings |
π 25 Intelligent Tools
Core
| Tool | Purpose | Savings |
|---|---|---|
ctx_read | File reads β 7 modes + lines:N-M, caching, fresh=true | 74-99% |
ctx_multi_read | Multiple file reads in one round trip | 74-99% |
ctx_tree | Directory listings (ls, find, Glob) | 34-60% |
ctx_shell | Shell commands with 90+ compression patterns | 60-90% |
ctx_search | Code search (Grep) | 50-80% |
ctx_compress | Context checkpoint for long conversations | 90-99% |
Intelligence
| Tool | What it does |
|---|---|
ctx_smart_read | Adaptive mode β auto-picks full/map/signatures/diff based on file type and cache |
ctx_delta | Incremental updates β only sends changed hunks via Myers diff |
ctx_dedup | Cross-file deduplication β finds shared imports and boilerplate |
ctx_fill | Priority-based context filling β maximizes info within a token budget |
ctx_intent | Semantic intent detection β classifies queries and auto-loads files |
ctx_response | Response compression β removes filler, applies TDD |
ctx_context | Multi-turn session overview β tracks what the LLM already knows |
ctx_graph | Project intelligence graph β dependency analysis + related file discovery |
ctx_discover | Shell history analysis β finds missed compression opportunities |
Memory & Multi-Agent
| Tool | What it does |
|---|---|
ctx_session | Cross-session memory β persist task, findings, decisions across chats |
ctx_knowledge | Persistent project knowledge β remember facts, recall by query/category |
ctx_agent | Multi-agent sharing β register agents, post/read scratchpad, coordinate sessions |
ctx_wrapped | Shareable savings report β "Spotify Wrapped" for your tokens |
Analysis
| Tool | What it does |
|---|---|
ctx_benchmark | Single-file or project-wide benchmark with preservation scores |
ctx_metrics | Session statistics with USD cost estimates |
ctx_analyze | Shannon entropy analysis + mode recommendation |
ctx_cache | Cache management: status, clear, invalidate |
π ctx_read Modes
| Mode | When to use | Token cost |
|---|---|---|
full | Files you will edit (cached re-reads β 13 tokens) | 100% first, ~0% cached |
map | Understanding a file β deps + exports + API | ~5-15% |
signatures | API surface with more detail than map | ~10-20% |
diff | Re-reading files that changed | changed lines only |
aggressive | Large files with boilerplate | ~30-50% |
entropy | Repetitive patterns (Shannon + Jaccard filtering) | ~20-40% |
lines:N-M | Specific ranges (e.g. lines:10-50,80-90) | proportional |
π Shell Hook Patterns (90+)
Pattern-based compression for 90+ commands across 34 categories:
View all 34 categories
| Category | Commands | Savings |
|---|---|---|
| Git (19) | status, log, diff, add, commit, push, pull, fetch, clone, branch, checkout, switch, merge, stash, tag, reset, remote, blame, cherry-pick | 70-95% |
| Docker (10) | build, ps, images, logs, compose ps/up/down, exec, network, volume, inspect | 70-90% |
| npm/pnpm/yarn (6) | install, test, run, list, outdated, audit | 70-90% |
| Cargo (3) | build, test, clippy | 80% |
| GitHub CLI (9) | pr list/view/create/merge, issue list/view/create, run list/view | 60-80% |
| Kubernetes (8) | get pods/services/deployments, logs, describe, apply, delete, exec, top, rollout | 60-85% |
| Python (7) | pip install/list/outdated/uninstall/check, ruff check/format | 60-80% |
| Ruby (4) | rubocop, bundle install/update, rake test, rails test | 60-85% |
| Linters (4) | eslint, biome, prettier, stylelint | 60-70% |
| Build Tools (3) | tsc, next build, vite build | 60-80% |
| Test Runners (8) | jest, vitest, pytest, go test, playwright, cypress, rspec, minitest | 90% |
| Terraform | init, plan, apply, destroy, validate, fmt, state, import, workspace | 60-85% |
| Make | make targets, parallel jobs, dry-run | 60-80% |
| Maven / Gradle | compile, test, package, install, clean, dependency trees | 60-85% |
| .NET | dotnet build, test, restore, run, publish, pack | 60-85% |
| Flutter / Dart | flutter pub, analyze, test, build; dart pub, analyze, test | 60-85% |
| Poetry / uv | install, sync, lock, run, add, remove; uv pip/sync/run | 60-85% |
| AWS (7) | s3, ec2, lambda, cloudformation, ecs, logs, sts | 60-80% |
| Databases (2) | psql, mysql/mariadb | 50-80% |
| Prisma (6) | generate, migrate, db push/pull, format, validate | 70-85% |
| Helm (5) | list, install, upgrade, status, template | 60-80% |
| Bun (3) | test, install, build | 60-85% |
| Deno (5) | test, lint, check, fmt, task | 60-85% |
| Swift (3) | test, build, package resolve | 60-80% |
| Zig (2) | test, build | 60-80% |
| CMake (3) | configure, build, ctest | 60-80% |
| Ansible (2) | playbook recap, task summary | 60-80% |
| Composer (3) | install, update, outdated | 60-80% |
| Mix (5) | test, deps, compile, format, credo/dialyzer | 60-80% |
| Bazel (3) | test, build, query | 60-80% |
| systemd (2) | systemctl, journalctl | 50-80% |
| Utils (5) | curl, grep/rg, find, ls, wget | 50-89% |
| Data (3) | env (filtered), JSON schema extraction, log dedup | 50-80% |
After lean-ctx init --global, 23 commands are transparently compressed via shell aliases:
git Β· npm Β· pnpm Β· yarn Β· cargo Β· docker Β· docker-compose Β· kubectl Β· k
gh Β· pip Β· pip3 Β· ruff Β· go Β· golangci-lint Β· eslint Β· prettier Β· tsc
ls Β· find Β· grep Β· curl Β· wget
π Examples
Directory listing β 239 β 46 tokens (-81%)
# ls -la src/ # lean-ctx -c "ls -la src/"
total 96 core/
drwxr-xr-x 4 user staff 128 ... tools/
drwxr-xr-x 11 user staff 352 ... cli.rs 9.0K
-rw-r--r-- 1 user staff 9182 ... main.rs 4.0K
-rw-r--r-- 1 user staff 4096 ... server.rs 11.9K
... shell.rs 5.2K
4 files, 2 dirs
[lean-ctx: 239β46 tok, -81%]
File reading (map mode) β 2,078 β ~30 tokens (-99%)
# Full read (284 lines, ~2078 tokens) # lean-ctx read stats.rs -m map (~30 tokens)
use serde::{Deserialize, Serialize}; stats.rs [284L]
use std::collections::HashMap; deps: serde::
use std::path::PathBuf; exports: StatsStore, load, save, record, format_gain
API:
#[derive(Serialize, Deserialize)] cl β StatsStore
pub struct StatsStore { fn β load() β StatsStore
pub total_commands: u64, fn β save(store:&StatsStore)
pub total_input_tokens: u64, fn β record(command:s, input_tokens:n, output_tokens:n)
... fn β format_gain() β String
(284 more lines) [2078 tok saved (100%)]
curl (JSON) β 127 β 14 tokens (-89%)
# curl -s httpbin.org/json # lean-ctx -c "curl -s httpbin.org/json"
{ JSON (428 bytes):
"slideshow": { {
"author": "Yours Truly", slideshow: {4K}
"date": "date of publication", }
"slides": [ [lean-ctx: 127β14 tok, -89%]
{
"title": "Wake up to WonderWidgets!",
...
Visual terminal dashboard
$ lean-ctx gain
β lean-ctx Token Savings Dashboard
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1.7M 76.8% 520 $33.71
tokens saved compression commands USD saved
Cost Breakdown (@ $2.50/M input, $10/M output)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Without lean-ctx $44.75 ($5.79 input + $38.96 output)
With lean-ctx $11.04 ($1.76 input + $9.28 output)
Saved $33.71 ($4.03 input + $29.68 output)
Top Commands
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
curl 48x ββββββββββββββββββββ 728.1K 97%
git commit 34x βββββββββββ 375.2K 50%
ctx_read 103x ββ 59.1K 38%
... +33 more commands
lean-ctx v2.17.0 | leanctx.com | lean-ctx dashboard
π¬ Scientific Compression Engine
Built on information theory and attention modeling (v2.6):
| Feature | What it does | Impact |
|---|---|---|
| Adaptive Entropy | Per-language BPE entropy + Jaccard thresholds with Kolmogorov adjustment | 10-25% |
| Attention Model | Heuristic U-curve positional weighting + structural importance scoring | β comprehension |
| TF-IDF Codebook | Cross-file pattern dedup via cosine similarity | 5-15% |
| Feedback Loop | Learns optimal thresholds per language/file type across sessions | auto-improving |
| Info Bottleneck | Entropy + task-relevance filtering (Tishby et al., 2000) | 20-40% |
| ctx_overview | Multi-resolution project map with graph-based relevance tiers | 90%+ |
π³ tree-sitter Signature Engine
AST-based signature extraction for 18 languages: TypeScript, JavaScript, Rust, Python, Go, Java, C, C++, Ruby, C#, Kotlin, Swift, PHP, Bash, Dart, Scala, Elixir, Zig.
| Capability | Regex (old) | tree-sitter |
|---|---|---|
| Multi-line signatures | β | β |
| Arrow functions | β | β |
| Nested classes/methods | Heuristic | AST scope |
| Languages | 4 | 14 |
Build without tree-sitter for a smaller binary (~5.7 MB vs ~17 MB):
cargo install lean-ctx --no-default-features
π CLI Commands
Shell Hook
lean-ctx -c "git status" # Execute + compress output
lean-ctx exec "cargo build" # Same as -c
lean-ctx shell # Interactive REPL with compression
File Operations
lean-ctx read file.rs # Full content (structured header)
lean-ctx read file.rs -m map # Deps + API signatures (~10% tokens)
lean-ctx read file.rs -m signatures # Function/class signatures only
lean-ctx read file.rs -m aggressive # Syntax-stripped (~40% tokens)
lean-ctx read file.rs -m entropy # Shannon entropy filtered (~30%)
lean-ctx read file.rs -m "lines:10-50,80-90" # Specific line ranges
lean-ctx diff file1.rs file2.rs # Compressed file diff
lean-ctx grep "pattern" src/ # Grouped search results
lean-ctx find "*.rs" src/ # Compact find results
lean-ctx ls src/ # Token-optimized directory listing
lean-ctx deps . # Project dependencies summary
Setup & Analytics
lean-ctx setup # One-command setup: shell + editors + verify
lean-ctx init --global # Install 23 shell aliases
lean-ctx init --agent claude # Claude Code hook
lean-ctx init --agent cursor # Cursor hooks.json
lean-ctx init --agent gemini # Gemini CLI hook
lean-ctx init --agent codex # Codex AGENTS.md
lean-ctx init --agent windsurf # .windsurfrules
lean-ctx init --agent cline # .clinerules
lean-ctx init --agent pi # Pi Coding Agent extension
lean-ctx gain # Visual terminal dashboard
lean-ctx gain --live # Live auto-updating dashboard
lean-ctx gain --graph # ASCII chart (30 days)
lean-ctx gain --daily # Day-by-day breakdown
lean-ctx gain --json # Raw JSON export
lean-ctx dashboard # Web dashboard (localhost:3333)
lean-ctx cheatsheet # Quick reference
lean-ctx discover # Find uncompressed commands
lean-ctx doctor # Diagnostics
lean-ctx update # Self-update
lean-ctx wrapped # Shareable savings report
lean-ctx benchmark run # Real project benchmark
lean-ctx benchmark report # Markdown report
Multi-Agent Launcher
lctx # Auto-detect agent, current dir
lctx --agent claude # Launch Claude Code with lean-ctx
lctx --agent cursor # Configure Cursor
lctx --agent gemini # Launch Gemini CLI
lctx /path/to/project "prompt" # Project + prompt
lctx --scan-only # Build project graph only
βοΈ Editor Configuration
lean-ctx setuphandles this automatically. Manual config below is only needed for edge cases.
Cursor
~/.cursor/mcp.json:
{
"mcpServers": {
"lean-ctx": { "command": "lean-ctx" }
}
}
GitHub Copilot
.github/copilot/mcp.json:
{
"servers": {
"lean-ctx": { "command": "lean-ctx" }
}
}
Claude Code
claude mcp add lean-ctx lean-ctx
Windsurf
~/.codeium/windsurf/mcp_config.json:
{
"mcpServers": {
"lean-ctx": { "command": "lean-ctx" }
}
}
If tools don't load, use the full path (e.g.,
/Users/you/.cargo/bin/lean-ctx). Windsurf spawns MCP servers with a minimal PATH.
Zed
~/.config/zed/settings.json:
{
"context_servers": {
"lean-ctx": {
"source": "custom",
"command": "lean-ctx",
"args": [],
"env": {}
}
}
}
OpenAI Codex
~/.codex/config.toml:
[mcp_servers.lean-ctx]
command = "lean-ctx"
args = []
Gemini CLI
~/.gemini/settings/mcp.json:
{
"mcpServers": {
"lean-ctx": { "command": "lean-ctx" }
}
}
Pi Coding Agent
lean-ctx init --agent pi
# Or: pi install npm:pi-lean-ctx
Pi's bash, read, grep, find, and ls tools are automatically routed through lean-ctx. Supports 55+ file extensions with auto mode selection.
OpenCode
~/.config/opencode/opencode.json:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"lean-ctx": {
"type": "local",
"command": ["lean-ctx"],
"enabled": true
}
}
}
π lean-ctx vs RTK
| Feature | RTK | lean-ctx |
|---|---|---|
| Architecture | Shell hook only | Shell hook + MCP server |
| Process model | Spawns per command | Persistent server (no EAGAIN) |
| CLI patterns | ~50 | 90+ |
| File reading | Signatures only | 7 modes (full, map, signatures, diff, aggressive, entropy, lines) |
| File caching | β | β (re-reads β 13 tokens) |
| Signature engine | Regex (4 langs) | tree-sitter AST (18 langs) |
| Dependency maps | β | β |
| Context checkpoints | β | β |
| Token counting | Estimated | tiktoken-exact |
| Entropy analysis | β | β |
| Cost tracking | β | β (USD estimates) |
| TDD mode | β | β (8-25% extra) |
| Thinking reduction | β | β (CRP v2) |
| Cross-session memory | β | β (CCP) |
| LITM positioning | β | β |
| Multi-agent sharing | β | β |
| Project knowledge store | β | β |
| Web dashboard | β | β |
| Savings reports | β | β (wrapped) |
| Raw mode / bypass | β | β (raw=true, --raw, lean-ctx-raw) |
| User-defined filters | TOML rules | TOML rules (priority over builtins) |
| Full output recovery | tee | β (tee_mode: always/failures/never) |
| Truncation warnings | β | β (transparent markers) |
| ANSI auto-strip | β | β (pre-compression) |
| Telemetry | Default ON (PII) | Zero. None. Ever. |
| Editor support | 3 editors | 23 editors/tools |
π Privacy & Security
lean-ctx is privacy-first by design:
- Zero telemetry β no data collection, no analytics, no phone-home, ever
- Zero network requests β everything runs locally on your machine
- No PII exposure β no hostnames, usernames, or project paths leave your system
- Fully auditable β MIT-licensed, single Rust binary, no hidden dependencies
See SECURITY.md.
Note on VirusTotal: Rust binaries are frequently flagged by ML-based heuristic scanners. This is a known issue. Build from source with
cargo install lean-ctxto verify.
π Uninstall
lean-ctx init --global # See what was added, then remove from shell profile
cargo uninstall lean-ctx # Remove binary
rm -rf ~/.lean-ctx # Remove stats + config
π€ Contributing
Contributions welcome! Open an issue or PR on GitHub.
Discord Β· π / Twitter Β· Buy me a coffee β
π License
MIT β see LICENSE.
Built with π¦ Rust Β· Made in Switzerland π¨π