convez.ai
MCP ServerDevOps & InfraestruturaIntermediário
yvgude

LeanCTX — Sistema Operacional de Contexto para IA

yvgude/lean-ctx

Comprime, memoriza e roteia contexto entre código e IA com até 99% de economia de tokens

Ver no GitHub
Muito bomPluginScore · de 0 a 100

MCP server que otimiza a gestão de contexto entre seu código e modelos de IA, comprimindo leituras de arquivo, memorizando sessões e economizando até 99% de tokens. Oferece 63 ferramentas MCP, 10 modos de leitura e compatibilidade com Cursor, Claude Code, Copilot e outros.

Instalação

$npx convez-ai yvgude/lean-ctx

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
4,0 mil
Forks
365
Acompanhando
24
Saúde
100%
Último commit
há 1 dia
Versão
v3.12.6
Issues abertas
8
Contribuidores
28

Casos de uso

  • Reduzir consumo de tokens em sessões longas de coding
  • Manter memória de contexto persistente entre chats
  • Otimizar leitura de arquivos grandes e outputs de shell
  • Integrar com IDEs de IA (Cursor, Claude Code, Copilot, Windsurf)

Veredito

LeanCTX é uma solução madura e técnica para um problema real: desperdício brutal de tokens em desenvolvimento com IA. Implementação em Rust, zero config, local-first, com números concretos de economia (13 tokens vs 2000 em re-leitura). Ideal para quem trabalha intensivamente com coding assistants e quer controle fino sobre contexto.

README

A tradução para o português deste README ainda está na fila.

The Cognitive Context Layer for AI coding agents

Your AI coding agent wastes thousands of tokens rereading files, parsing noisy shell output, and losing context between sessions — and you have no control over any of it.

LeanCTX is the operating system for that context. One local binary that governs every token between your code and the model: it compresses what the AI reads, remembers what matters across sessions, routes each read to the right fidelity, and verifies what comes back. Zero config required. Local-first.

ProblemWith LeanCTX
Repeated file reads: ~2000 tokens eachCached re-reads: ~13 tokens
Raw git status: ~800 tokensCompressed: ~120 tokens
Context resets every chatSession memory persists across chats
No visibility into context usageReal-time dashboard + budget control


LeanCTX is the Cognitive Context Layer between your AI and your code: it perceives, compresses, remembers, routes, and governs every token that flows between them — all from one local Rust binary.

It governs every token between your code and the AI — so you make better decisions, not just cheaper ones. Works with Cursor, Claude Code, Copilot, Windsurf, Codex, Gemini and 24+ other agents — no config needed.

Why developers use LeanCTX

  • Longer useful coding sessions — less context waste = more room for actual code reasoning
  • Lower API costs — 60-99% compression on shell output, cached reads cost ~13 tokens
  • No more "I already showed you this file" — session memory persists across chats
  • Works with your existing setup — one lean-ctx setup command, no config changes needed
  • Full visibility — see exactly where your context window budget goes


What it does — the four dimensions of context

LeanCTX treats context as a managed resource, not an afterthought. One binary covers the four dimensions that decide how well an AI agent actually performs:

1. Compression — input efficiency

Your AI agent reads files and runs commands. LeanCTX compresses both automatically.

  • File reads: 10 modes (full, map, signatures, diff, lines:N-M) — cached re-reads cost ~13 tokens
  • Shell output: 56 pattern modules compress git, npm, cargo, docker, kubectl, terraform and more (270 passthrough rules)
  • Tree-sitter AST: structural understanding for 18 languages — not just text compression

2. Routing — the right fidelity per read

Not every file needs the same depth. LeanCTX sends the signal, not the noise.

  • 10 read modes: from full content down to AST signatures and entropy-filtered views
  • Adaptive ModePredictor: learns the optimal read mode per file type from past sessions
  • IntentEngine: classifies query complexity so simple lookups stay cheap

3. Memory — context that persists

Context doesn't disappear between chats anymore.

  • Session memory (CCP): persist task/facts/decisions across chats — structured recovery queries survive compaction
  • Knowledge graph: temporal facts with validity windows, episodic + procedural memory
  • Property Graph: multi-edge code graph (imports, calls, exports, type_ref) powers impact analysis and search ranking

4. Verification — control what reaches the model

Performance is accuracy, not just speed. You stay in control of the window.

  • Context Manager: browser dashboard with real-time token tracking, compression stats, utilization gauge
  • Budgets & SLOs: profiles, roles, per-agent budgets, and throttling policies
  • Context Proof (ctx_proof, ctx_verify): 4-layer verification engine with CI drift gates
  • 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 Refactoring (ctx_refactor): language-server-powered rename, references, go-to-definition via rust-analyzer, typescript-language-server, pylsp, gopls
  • Multi-Agent (ctx_agent, ctx_handoff): agent handoff with context transfer bundles, diary system, synchronized shared state
  • 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: lean-ctx pack create bundles Knowledge + Graph + Session into portable .ctxpkg files with SHA-256 integrity
  • Observability: lean-ctx gain --live for real-time savings, lean-ctx wrapped for weekly/monthly summaries (gain --svg/--share for a shareable card or self-hostable page), lean-ctx watch for TUI monitoring
  • Verified savings: lean-ctx savings is an auditable, per-event ledger (tokenizer transparency, bounce-netting, tamper-evident SHA-256 chain) — local-only, on by default
  • HTTP mode: lean-ctx serve for Streamable HTTP MCP + /v1/tools/call (used by the Cookbook + SDK)

Where it's going

LeanCTX is growing from a single context layer into a full cognitive context layer for whole teams: version-controlled context strategy, one unified graph, and a governance layer across many agents.

  • Context as Code — declarative pipelines, profiles, and policies in TOML, versioned like infrastructure
  • Unified Context Graph — code, tests, commits, CI runs, and knowledge entries in a single semantic graph
  • Agent Harness — roles, budgets, and tool permissions for multi-agent governance
  • Context Observability — SLOs on context consumption, anomaly detection, OpenTelemetry / Prometheus export

The full roadmap lives in VISION.md.

How it works (30 seconds)

AI tool  →  (MCP tools + shell commands)  →  lean-ctx  →  your repo + CLI
  • MCP server: exposes ctx_* tools (read modes, caching, deltas, search, memory, multi-agent)
  • Shell hook: transparently compresses common commands so the LLM sees less noise
  • Property Graph: multi-edge code graph powers impact analysis, related file discovery, and search ranking
  • Session memory: persists state with structured recovery so long-running work never "cold starts"
  • Context Manager: browser dashboard for real-time visibility into what's in your context window

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                               # Rust
pi install npm:pi-lean-ctx                           # Pi Coding Agent

# 2) Connect your AI tools (zero prompts, sensible defaults)
lean-ctx onboard          # or: lean-ctx setup  (guided, full control)

# 3) Verify
lean-ctx doctor

# 4) Restart your shell + AI tool, use it normally, then see the payoff
lean-ctx gain             # savings appear after your AI's first lean-ctx call

After onboarding, restart your shell and your editor/AI tool once so the MCP + hooks are active. lean-ctx gain is empty until your AI tool makes its first lean-ctx call — that's expected, not a misconfiguration.

  • 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 all 69 MCP tools are documented there).

🟢 Your first 60 seconds

"I just installed it — now what?"

lean-ctx onboard      # connect every detected AI tool
lean-ctx doctor       # confirm you're wired up

One command auto-detects Cursor/Claude/Codex/… and configures MCP + hooks. → 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

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

🔌 Wire in proxy, providers, plugins

"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

🏢 Share across a team / CI

"One shared index, headless in pipelines."

lean-ctx team serve --config team.toml
lean-ctx bootstrap            # zero-prompt CI setup

Scoped tokens, optional cloud sync, verifiable context gates. → Journey 9 — Team, Cloud & CI

🎚️ 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

📊 Prove the payoff

"Show me the numbers."

lean-ctx gain --deep          # savings, cost, per-agent, heatmap
lean-ctx wrapped              # shareable recap (also: gain --svg / gain --share)
lean-ctx savings              # verified per-event ledger (auditable; savings verify)

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

📚 The full reference

"I want to read everything."

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

Supported IDEs & AI tools

LeanCTX is a standard MCP server, so it works with any MCP-compatible client. Two integration modes are auto-selected per agent:

ModeHow it worksBest for
HybridMCP for cached reads (~13 tokens) + shell hooks for command compressionAgents with shell access (Cursor, Claude Code, Codex, ...)
MCPAll 76 tools via MCP protocol, no shell hooksProtocol-only agents (JetBrains, VS Code, Zed, ...)

Agent compatibility matrix

AgentHybridMCPSetup
Cursor●lean-ctx init --agent cursor
Claude Code●lean-ctx init --agent claude
Augment CLI / VS Code●lean-ctx init --agent augment
Codex CLI●lean-ctx init --agent codex
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
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

Any MCP-compatible client works out of the box — the table above shows agents with first-class auto-setup.

When to use (and when not to)

Great fit if you...

  • use AI coding tools daily and your sessions are shell-heavy (git/tests/builds)
  • work in medium/large repos (50+ files / monorepos)
  • want a local-first layer with no telemetry by default

Skip it if you...

  • mostly work in tiny repos and rarely call the shell from your AI tool
  • always need raw/unfiltered logs (you can still use --raw, but ROI is lower)

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 --live
lean-ctx dashboard                              # Context Manager (browser)
lean-ctx watch                                  # TUI monitor
lean-ctx benchmark report .
  • The repo ships the exact tapes used to render the GIFs in demo/
  • Regenerate locally:
vhs demo/leanctx.tape
vhs demo/gain.tape
vhs demo/benchmark.tape

Benchmarks

lean-ctx benchmark report .

By the numbers

  • 1,800+ GitHub stars in 4 months
  • 190+ forks — active community contributions
  • 181 releases — shipped daily since launch
  • 30+ supported AI coding agents — broadest MCP compatibility
  • 76 MCP tools — from simple file reads to multi-agent orchestration
  • Used in production by teams running Claude Code, Cursor, and Codex daily

Docs

Privacy & security

  • No telemetry by default
  • Optional anonymous stats sharing (opt-in during setup)
  • Disableable update check (config update_check_disabled = true or LEAN_CTX_NO_UPDATE_CHECK=1)
  • 40+ security hardening fixes in v3.5.16 (path traversal, injection, CSPRNG, CSP, resource limits — details)
  • Runs locally; your code never leaves your machine unless you explicitly enable cloud sync

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
pi uninstall npm:pi-lean-ctx   # Pi Coding Agent

Star History

Contributing

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

License

Apache License 2.0 — see LICENSE.

Ver o original no GitHub

Bom para

Relacionados