lean-ctx README

The project's README from github.com/yvgude/lean-ctx. As one markdown file: README.md.

██╗     ███████╗ █████╗ ███╗   ██╗     ██████╗████████╗██╗  ██╗
██║     ██╔════╝██╔══██╗████╗  ██║    ██╔════╝╚══██╔══╝╚██╗██╔╝
██║     █████╗  ███████║██╔██╗ ██║    ██║        ██║    ╚███╔╝
██║     ██╔══╝  ██╔══██║██║╚██╗██║    ██║        ██║    ██╔██╗
███████╗███████╗██║  ██║██║ ╚████║    ╚██████╗   ██║   ██╔╝ ██╗
╚══════╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝     ╚═════╝   ╚═╝   ╚═╝  ╚═╝

LeanCTX

Context Gateway for AI Systems.

Less context. More intelligence.

Make every agent more effective.

The claim is a stance, not a measured quality or savings promise, until a published cost-per-accepted-outcome (CPAO) study exists.

LeanCTX sits between AI tools and the information they read. It selects task-relevant context, applies supported access and content controls before delivery, and records the context operations and delivery evidence it can observe. Your application, agent loop and model stay yours.

The open-source LeanCTX | OSS runs locally through CLI, MCP, hooks and proxy paths. The LeanCTX | SDK embeds supported LeanCTX | OSS capabilities in your application.


GitHub Stars   CI Security crates.io Downloads npm AUR Mixed license Discord X/Twitter Configurable telemetry

Website  ·  Docs  ·  Install  ·  Scenarios  ·  Demo  ·  Benchmarks  ·  Cookbook  ·  Security  ·  Changelog


Where it sits

Files · repositories · tool results · configured providers
                          │
                          ▼
                LeanCTX Context Gateway
             Select · Control · Learn · Prove
                          │
                          ▼
                Your AI application / agent
                          │
                          ▼
                     Your model

For coding workflows, start with Claude Code, Cursor or Codex. The installation matrix distinguishes first-class paths from other compatibility references.

Your work Start here
Improve the context path of existing AI tools Community setup
Apply shared context controls across an organization Enterprise — licensed controls and deployment scope
Build context control into your application LeanCTX | SDK — stable interfaces and separate SDK/OEM terms

What is LeanCTX? · Where LeanCTX fits · Architecture

See it in action:

Map-mode file read + compressed git output demo
Read + Shell
Map-mode reads + compressed CLI output
lean-ctx gain terminal summary demo
Gain (terminal)
Token usage + estimated cost differences
lean-ctx benchmark report demo
Benchmark measurement
Measure compression by language + mode

All GIFs are generated from reproducible VHS tapes in demo/.

Why developers use LeanCTX


Find LeanCTX useful? Give it a star — it helps others find the Context Gateway for AI systems.


Inside LeanCTX | OSS

The Engine puts Select, Control, Learn and Prove into the context paths of your existing AI tools. Your host keeps control of the task, agent loop and model.

1. Select — the context each task needs

Search and structural views help an agent find relevant information before reading entire files. Supported read and shell paths can return focused views of files and command output, with references for recovering detail.

2. Control — configured rules on supported paths

Review the security policy for defaults, supported controls and coverage limits. A filesystem boundary is not an operating-system sandbox.

3. Learn — connect work across sessions

Keep useful task records and discover relationships between code and local knowledge. Learning here means context continuity; it does not train your model.

4. Prove — inspect what the Engine recorded

Inspect source references, recorded policy decisions and delivery evidence from supported paths. lean-ctx inspect explains observed context operations. A context-only integration records its prepared result; it cannot prove a later model call made by the host.

Usage and cost — measure the result

Context controls and evidence come first. Usage estimates and calculated costs help you assess their operational effect; they do not prove answer quality.

Shadow Mode — a simulated baseline

Shadow Mode estimates what the same work would have cost without LeanCTX, without changing the active workflow. The baseline is simulated from the uncompressed token counts and the same outcome signals, not a second measured run, so its reports estimate cost, tokens and CPAO deltas; they do not measure answer quality.

LeanCTX records local cost and outcome signals without adding those reports to agent context. CPAO (cost per accepted outcome) is one comparison metric; Shadow Mode provides simulated savings estimates. Keep estimates, provider-measured usage and outcome quality separate.

lean-ctx savings --period week                 # costs, token savings, and CPAO
lean-ctx value-report --format markdown --last 20  # recent outcome quality
lean-ctx shadow --latest                       # latest baseline comparison

Quick start: usage tracking

# Enable shadow mode for savings comparison
lean-ctx config set shadow.enabled true

# After using LeanCTX for a while:
lean-ctx savings
lean-ctx shadow --latest
Feature overview (see generated MCP registry for the current count)
  • Web & Research (ctx_url_read): pull a public web page, PDF, or YouTube transcript into context as compressed, citation-backed text — facts/quotes return claims with a confidence score + source URL, relevance-ranked research-compression distils to a token budget, SSRF-guarded (http/https only)
  • Graph-Powered Intelligence: hybrid search (BM25 + embeddings + graph proximity via RRF), incremental git-diff updates
  • LSP-backed symbols: ctx_patch op=replace_symbol edits a whole symbol body and ctx_callgraph finds references, through rust-analyzer, typescript-language-server, pylsp or gopls
  • Multi-Agent — Research (ctx_agent, ctx_handoff): experimental local agent handoff with context transfer bundles, diary system, and shared state; not a hosted or generally available team service
  • Archive Full-Text Search (ctx_expand search_all): FTS5-powered cross-archive search over all previously archived tool outputs
  • PR Context Packs: lean-ctx pack --pr builds a PR-ready context pack (changed files, related tests, impact, artifacts)
  • Context Packages — Research: lean-ctx pack create bundles local Knowledge, Graph and Session state into .ctxpkg files with SHA-256 integrity; this is experimental local packaging, not a generally available Context Kits or hosted sharing product
  • Context Time Machine — Research: lean-ctx snapshot create|list|show|verify|restore|publish|import handles git-anchored, signed local snapshots and file-based sharing; dashboard replay and restore are experimental, and hosted history or a hosted registry is not a generally available product
  • Observability: lean-ctx cockpit shows local activity and recorded context metrics (Savings · Spend · Report · Proof, recorded calls in the Ledger); lean-ctx gain is the terminal summary (--json for scripts), and gain --svg/--share creates a shareable card or self-hostable page
  • Usage ledger: lean-ctx savings is a local per-event ledger with tokenizer transparency, bounce-netting and a tamper-evident SHA-256 chain; provider-measured savings require the proxy's counterfactual holdout
  • HTTP mode: lean-ctx serve for Streamable HTTP MCP + /v1/tools/call (used by the Cookbook and external clients)

Addons — Research preview

Addon manifests and gateway integration remain experimental Research interfaces. Local addon release|add|list commands handle signed packages; they do not provide a public marketplace, hosted registry, managed distribution or addon search. A package can carry a sandboxed WASM module or an [mcp] declaration for an external server.

lean-ctx addon release ./my-addon   # build a signed .ctxpkg — no artifact host, no CI
lean-ctx addon add ./my-addon-1.0.0.ctxpkg   # verify, disclose, ask, install
lean-ctx addon list                 # what's installed, what loads, what's wired

The local workflow verifies signatures and module hashes, shows the publisher key and declared command before installation, and never installs the external server. Opt-in post-processing can send addon results through compression, ctx_expand, BM25, graph and knowledge. Results remain untrusted; configured secret scrubbing does not cover every possible secret. See the status-qualified addon guide for the boundary.

Research directions

LeanCTX remains the Context Gateway for AI Systems. These research directions extend its context capabilities; they are not supported product commitments.

The full roadmap lives in VISION.md.

How it works

LeanCTX works on two planes — what your agents read and what they send to the model:

read path:   AI tool  →  (MCP tools + shell)  →  lean-ctx  →  your repo + CLI
wire path:   AI tool  →  lean-ctx proxy        →  model provider   (supported, configured requests)

Get started

# 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                               # Rust

# 2) One-command setup for your agent
lean-ctx wrap cursor      # or: wrap claude / wrap codex

# Inspect recorded context metrics after your AI's first lean-ctx call.
lean-ctx cockpit          # Savings · Spend · Report · Proof in the browser (also: lean-ctx dashboard)
lean-ctx gain --terminal  # the same numbers as a terminal summary (--json for scripts)
lean-ctx cockpit stop     # stop the background Cockpit server (--foreground keeps it in the terminal)

lean-ctx wrap registers the MCP server and configures the supported local transport for that agent. Undo anytime with lean-ctx unwrap cursor.

Claude Pro/Max: subscription OAuth cannot use a custom ANTHROPIC_BASE_URL. lean-ctx wrap claude therefore adds no proxy redirect while enabling the ctx_* tools and shell-output compression; an existing custom endpoint remains untouched. Claude wire-level request compression requires ANTHROPIC_API_KEY. See advanced proxy setup.

Alternative: full control
lean-ctx onboard          # connect all detected AI tools (zero prompts)
lean-ctx setup            # interactive wizard with every option

Building from source on Windows? Clone the repo and run ./install.ps1 in PowerShell — it builds the release binary and installs it into Cargo's bin directory (pass -BuildOnly to build without installing).

Windows code signing and Smart App Control

The current release workflow signs new Windows binaries as Thinkery AG, including the binaries inside ZIP archives and Python companion wheels. Earlier releases may still contain unsigned executables. Signing does not guarantee acceptance by every Windows security policy.

If Windows blocks an older unsigned download, use WSL or build locally with cargo install lean-ctx; do not disable system-wide security protections for this tool. Windows-side MCP clients can launch the WSL installation with wsl lean-ctx mcp.

See Windows signing and verification and #1820 for verification status.

Troubleshooting / Safety
  • Disable immediately (current shell): lean-ctx-off
  • Run a single command uncompressed: lean-ctx -c --raw "git status"
  • Only activate in AI agent sessions: set shell_activation = "agents-only" in ~/.config/lean-ctx/config.toml
  • Per-project config override: create .lean-ctx.toml in your project root (auto-merged with global config)
  • Docker projects sharing /workspace: create .lean-ctx-id with a unique name to prevent context collisions
  • Update: lean-ctx update
  • Diagnose (shareable): lean-ctx doctor --json

Real-world scenarios

LeanCTX grows with you. Below are the journeys most people actually take — each links to a complete, function-by-function walkthrough in the Reference (every CLI command and the complete MCP tools are documented there).

🟢 Your first setup

"I just installed it — now what?"

lean-ctx wrap cursor  # one-command setup for your agent
lean-ctx doctor       # confirm you're wired up

wrap configures the supported integration; doctor checks the resulting setup. → Journey 1 — Setup & Onboarding

📖 Coding every day

"Stop re-reading the same files."

lean-ctx read src/server.rs -m map   # API surface, ~13 tok on re-read
lean-ctx -c "git status"             # compressed shell output

Your agent reads less and searches smarter — automatically. → Journey 2 — Daily Use

🧠 Resume where you left off

"My new chat forgot everything."

lean-ctx overview                    # task-aware project recap
lean-ctx knowledge recall "auth"     # facts that survive resets
lean-ctx knowledge consolidate       # import session + compact lifecycle
lean-ctx knowledge consolidate --all # compact every project store

Session memory + a project knowledge graph persist across chats. → Journey 3 — Memory & Knowledge

🗺️ Understand a new codebase

"Where does this function ripple to?"

lean-ctx graph impact src/auth.rs    # blast radius
lean-ctx smells scan                 # code-smell hotspots

A multi-edge property graph powers impact analysis + ranked search. → Journey 4 — Code Intelligence

🔌 Providers & multi-repo

"Pull in GitHub issues and our Postgres schema."

lean-ctx provider list
lean-ctx serve --root ./api --root ./web   # multi-repo

External data flows through the same consolidation pipeline. → Journey 5 — Advanced & Integrations

🛠️ Keep it healthy

"Update, fix, or cleanly remove."

lean-ctx doctor --fix
lean-ctx update

Self-healing diagnostics; surgical uninstall that only removes its own blocks. → Journey 6 — Lifecycle & Troubleshooting

🎛️ Take control of the window

"Budget my context like a pro."

lean-ctx plan "refactor billing" --budget 8000
lean-ctx compile --mode balanced

Phi-scored planning + knapsack compilation + a context ledger. → Journey 7 — Context Engineering

🤝 Run a team of agents

"Planner + coder + reviewer on one repo."

ctx_agent action=register role=dev
ctx_handoff action=create        # baton-pass with full context

Shared message bus, diaries, knowledge, and deterministic handoffs. → Journey 8 — Multi-Agent Collaboration

🏢 Headless in CI

"The same engine, headless in pipelines."

lean-ctx bootstrap            # zero-prompt CI setup

Everything local works without an account. The Cloud (shared knowledge for teams and your own machines) follows with 3.12.1.

🎚️ Tune & govern

"Make it behave exactly how we want."

lean-ctx compression standard
lean-ctx harden               # enforce token discipline

Compression levels, tool profiles, themes, and rules governance. → Journey 10 — Customization & Governance

📊 Measure usage and cost

"Show me the numbers."

lean-ctx cockpit              # Savings · Spend · Report · Proof in the browser
lean-ctx gain --deep --terminal  # terminal: savings, cost, per-agent, heatmap (--json for scripts)
lean-ctx gain --svg           # shareable recap card (also: gain --share / gain --wrapped)
lean-ctx savings              # verified per-event ledger (auditable; savings verify)

All analytics live in the Cockpit and the CLI — never burning agent tokens. → Journey 11 — Analytics & Insights

📚 The full reference

"I want to read everything."

Every command and the generated MCP registry, organized as user journeys, plus appendices for the CLI map, MCP tools, and paths & config. → Reference index

Supported IDEs & AI tools

LeanCTX provides an MCP server. Client support depends on transport, tool handling, and configuration; the matrix below records the integration scope. Two integration modes are selected for supported agents:

Mode How it works Best for
Hybrid MCP for cached reads and references + shell hooks for command compression Agents with shell access (Cursor, Claude Code, Codex, ...)
MCP Complete tool set via MCP protocol, no shell hooks Protocol-only agents (JetBrains, VS Code, Zed, ...)

Agent compatibility matrix

Agent Hybrid MCP Setup
Cursor ● lean-ctx init --agent cursor
Claude Code ● lean-ctx init --agent claude
CodeBuddy ● lean-ctx init --agent codebuddy
Augment CLI / VS Code ● lean-ctx init --agent augment
Codex CLI ● lean-ctx init --agent codex
Grok ● lean-ctx init --agent grok
Gemini CLI ● lean-ctx init --agent gemini
Windsurf ● lean-ctx init --agent windsurf
GitHub Copilot ● lean-ctx init --agent copilot
CRUSH ● lean-ctx init --agent crush
Hermes ● lean-ctx init --agent hermes
OpenCode ● lean-ctx init --agent opencode
Pi ● lean-ctx init --agent pi
Qoder ● lean-ctx init --agent qoder
Amp ● lean-ctx init --agent amp
Cline ● lean-ctx init --agent cline
Roo Code ● lean-ctx init --agent roo
Kiro ● lean-ctx init --agent kiro
Antigravity ● lean-ctx init --agent antigravity
Amazon Q ● lean-ctx init --agent amazonq
Qwen ● lean-ctx init --agent qwen
Trae ● lean-ctx init --agent trae
Verdent ● lean-ctx init --agent verdent
Aider ● lean-ctx init --agent aider
Mistral Vibe ● lean-ctx init --agent vibe
Continue ● lean-ctx init --agent continue
JetBrains IDEs ● lean-ctx init --agent jetbrains
QoderWork ● lean-ctx init --agent qoderwork
VS Code ● lean-ctx init --agent vscode
Zed ● lean-ctx init --agent zed
Neovim ● lean-ctx init --agent neovim
Emacs ● lean-ctx init --agent emacs
Sublime Text ● lean-ctx init --agent sublime

MCP clients need compatible transport, tool support, and configuration. The table lists setup targets; the client constraints distinguish verified integrations from generic compatibility.

When to use (and when not to)

Great fit if you...

Skip it if you...

The honest fine print: the payoff depends on three levers — reach (own the window via the proxy/engine, not just the ctx_* tool layer), context lifetime (one long-lived session vs. a fresh process per phase), and provider pricing (prompt-cache-priced vs. re-billed every turn). They stack into a clear win where they line up and net to break-even where they don't. See the win vs. break-even matrix for the full breakdown and how to tune for each case.

Demo

Try these in any repo:

lean-ctx read rust/src/server/mod.rs -m map
lean-ctx -c "git log -n 5 --oneline"
lean-ctx gain                                   # terminal summary
lean-ctx cockpit                                # Savings · Spend · Report · Proof (browser)
lean-ctx benchmark report .
vhs demo/leanctx.tape
vhs demo/gain.tape
vhs demo/benchmark.tape

Benchmarks

Measurements and estimates require a declared workload and method. The earlier per-read-mode compression table (map / signatures over 50 files) is withdrawn along with the other historical figures in BENCHMARKS.md; measure your own repository with lean-ctx benchmark report . instead. Cache references can reduce repeated context; their token cost depends on the emitted result and tokenizer.

Measure the Engine's own advertised schema, instruction, and briefing overhead with lean-ctx doctor overhead --gate. The deterministic lean-ctx benchmark dual-arm --json replay reports a synthetic upper bound: its baseline never uses the provider's prompt cache, while agent hosts can cache the prefix with or without LeanCTX. It is not a provider invoice, an on/off comparison or an outcome-quality evaluation. The on/off comparison the Engine offers is the proxy's opt-in compression holdout ([proxy] compression_holdout).

Proxy rewrites preserve stable output for prompt-cache eligibility under the same inputs and settings, and the compression engine checks that critical facts (failing tests, error codes, locations) survive or it delivers the original. Actual cache hits, prices, and discounts depend on the provider. Quality results state their evidence tier (A mechanism … E production) — see context-quality-v1. A powered with/without quality study has not been run yet; the proxy's compression holdout measures prompt size on real traffic and reports answer quality as unknown. What each number can and cannot show, per data path: measurement scope.

Adoption and compatibility

Docs

Privacy & security

See SECURITY.md.

Uninstall

One command removes everything — it stops all processes, then deletes hooks, editor configs, rules, autostart (LaunchAgent/systemd), the data dir, and the binary itself:

lean-ctx uninstall                 # full clean removal
lean-ctx uninstall --dry-run       # preview every change, write nothing
lean-ctx uninstall --keep-config   # keep MCP configs + rules (for reinstall)
lean-ctx-off                       # or just disable for the current shell session

No binary on PATH (or you used the curl installer)? Run the same removal from the installer:

curl -fsSL https://leanctx.com/install.sh | sh -s -- --uninstall

If you installed via a package manager, uninstall removes everything it wrote and tells you the one command to finish removing the binary:

brew uninstall lean-ctx        # Homebrew
cargo uninstall lean-ctx       # cargo install
npm uninstall -g lean-ctx-bin  # npm

Star History

Star History Chart

Contributing

Start with CONTRIBUTING.md. Easy first PR: propose a new CLI compression pattern via the issue template.

License

LeanCTX | OSS and its open interfaces (rust/, packages/, docs/, scripts/) are Apache-2.0. LICENSE.md and LICENSE_MATRIX.toml are the path-level authority for that Apache host.

The consolidated development tree also carries sdk/ (client bindings) and ee/ (commercial Runtime, Suite and services) next to the host. Both keep their own existing terms, are not Apache-2.0 and are not approved for publication; the host-only mirror contains neither directory. Their presence in one checkout relicenses nothing. SOURCE_LAYOUT.md lists each path with its current terms.

lean-ctx (yvgude/lean-ctx)

Searching Database…

What is this?LeanCTX is a 'Context Gateway' that runs locally alongside your AI coding agent, deciding what context the model actually sees, compressing it, and tracking the cost and outcome of that work.
Is this a CLI tool or does it run as a background service?It is a local binary and MCP server with CLI subcommands (serve, gain, watch, pack, snapshot) plus a browser dashboard — it sits in the middle of your agent's requests rather than being a library you import.
How do I get LeanCTX running with my coding agent?Run the lean-ctx setup command — it installs the engine and wires it into your existing agent with no configuration changes required.
Which coding agents does it work with?Cursor, Claude Code, Copilot, Windsurf, Codex, Gemini CLI and 30+ other agents — it plugs in as a local MCP server rather than needing agent-specific integration.
Are the token savings guaranteed?No — actual savings depend on the workload and which modes are enabled. LeanCTX ships a local savings ledger and a Shadow Mode comparison so you can verify the measured reduction yourself rather than trust a fixed claim.
Does my code or context leave my machine?No — LeanCTX is local-first; your context and memory stay on your machine in portable .ctxpkg files, and you can swap model providers (OpenAI, Anthropic, Gemini) without losing or exposing that data.
What is Shadow Mode?It runs LeanCTX's treatment alongside a configured baseline without changing your actual workflow, then reports cost, tokens and CPAO deltas plus whether output quality held — it only recommends savings when the comparison backs them up.
What does CPAO mean?Cost Per Accepted Outcome — LeanCTX's north-star metric for comparing how much a useful piece of AI work actually costs, instead of just counting raw tokens saved.
Can I extend LeanCTX with third-party tools?Yes, through signed addons: either a sandboxed WASM module that runs inside the pipeline, or an [mcp] manifest entry that wires in an external MCP server. There is deliberately no addon marketplace, and every addon's output is scrubbed for secrets and tagged untrusted before it reaches the model.
What is a .ctxpkg file?A portable, signed package bundling code knowledge, the graph, and session memory, which you can move across machines or switch between model providers without losing accumulated context.
Creator
yvgude
Size
204.7 MB
Stars
4K
Age
8mo
Commits · 90 Days