lean-context-mcp
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., "@lean-context-mcp give me the outline of src/server.ts instead of the whole file"
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.
lean-context-mcp
An MCP server that helps coding agents (Claude Code, Cursor, any MCP client) use fewer tokens.
Instead of reading whole files, dumping raw grep output, or pasting full test logs into the context, the agent asks for exactly what it needs:
a file's outline (symbols and line ranges) instead of the whole file,
one function instead of the whole file,
a compact search that still lists every matching file,
test / lint / tsc output reduced to the failures.
Measured on a real TypeScript monorepo: 84.5% fewer tokens on like-for-like tasks, 81.7% after counting the tool definitions themselves (details and honest limits below).
Quick start
Needs Node ≥ 20. ripgrep (rg) is recommended for fast search; without it a slower built-in JS search is used automatically.
npx -y lean-context-mcp # starts the stdio server (your MCP client normally runs this for you)Claude Code
# for the current project (roots default to the directory Claude Code starts in)
claude mcp add lean-context -- npx -y lean-context-mcp
# for every project, with explicit roots
claude mcp add --scope user lean-context -e LEAN_ROOTS=/Users/you/code -- npx -y lean-context-mcpCursor
~/.cursor/mcp.json (global) or <repo>/.cursor/mcp.json (project):
{
"mcpServers": {
"lean-context": {
"command": "npx",
"args": ["-y", "lean-context-mcp"],
"env": { "LEAN_ROOTS": "/Users/you/code/myrepo" }
}
}
}Set LEAN_ROOTS for Cursor: the server's working directory is not guaranteed to be your project.
Any other MCP client
Run npx -y lean-context-mcp as a stdio server (command npx, args ["-y", "lean-context-mcp"]), with LEAN_ROOTS in its environment. You can also install it once with npm i -g lean-context-mcp and use the command lean-context-mcp.
Make the agent use it
Agents prefer their built-in tools unless told otherwise. Add one line to CLAUDE.md, AGENTS.md or .cursor/rules:
Use lean-context tools (
outline,read_symbol,search,run_compact) before reading whole files or running raw commands.
Related MCP server: token-shrink
LEAN_ROOTS: what the server may touch
LEAN_ROOTS is the list of folders the tools may read, search and run commands in (separated by : or ,). Anything outside, including .. and symlink tricks, is refused. If it is not set, the server's current directory is the only root. Relative paths in tool calls resolve against the first root.
LEAN_ROOTS=/Users/you/code/app:/Users/you/code/libTools
tool | what it returns |
| A file's symbol map (kind, signature, line range) or a directory map ( |
| The source of one symbol ( |
| ripgrep (JS fallback if |
| Runs an allowlisted command with no shell and a timeout. Returns the exit code, the duration and only the failures, with dedupe and head+tail trimming. Has extractors for vitest, jest, phpunit/Pest, pytest, tsc, eslint and go test. The full log goes to a temp file (mode 600) whose path is returned. Small outputs (≤ ~1200 chars, or when squeezing would not shrink them) come back verbatim with only a |
| Per-file notes keyed by content hash in |
| Get, set or append |
The six tool definitions cost about 1,400 tokens per session (measured).
Measured savings
Measured on a ~10k-line TypeScript monorepo (Fastify + Prisma + workers) with @anthropic-ai/tokenizer (cl100k_base as a cross-check). "Before" is what an agent would otherwise read (whole file, raw rg -n -C2, raw command output); "after" is the tool's exact output. The run_compact rows ran on a scratch copy with injected failures.
scenario | before tok | after tok | saved | needed info kept |
outline: approvals.ts | 3977 | 239 | 94% | yes |
outline: orchestrator.ts | 4585 | 163 | 96.4% | yes |
outline: auth.ts | 4179 | 72 | 98.3% | yes |
read_symbol: decideApproval in approvals.ts | 3977 | 1174 | 70.5% | yes |
read_symbol: createWorktree in git.ts | 2933 | 209 | 92.9% | yes |
outline_dir: apps/worker/src read all files | 31314 | 127 | 99.6% | yes |
outline_dir: apps/worker/src vs bare rg --files | 207 | 127 | 38.6% | yes |
outline_dir: packages/core read all files | 20615 | 156 | 99.2% | yes |
outline_dir: packages/core vs bare rg --files | 236 | 156 | 33.9% | yes |
search: "consumeApproval" 14 matches | 2511 | 1678 | 33.2% | yes |
search: "AppError" 120 matches | 16967 | 2102 | 87.6% | yes |
search: "correlationId" 45 matches | 8158 | 1213 | 85.1% | yes |
search: "AppError" full detail maxMatches 500 | 16967 | 11170 | 34.2% | yes |
search: "correlationId" full detail maxMatches 500 | 8158 | 5298 | 35.1% | yes |
run_compact: unit tests all passing exit 0 | 494 | 52 | 89.5% | yes |
run_compact: unit tests 1 injected failure exit 1 | 939 | 249 | 73.5% | yes |
run_compact: eslint 2 injected errors exit 1 | 120 | 123 | -2.5% | yes |
run_compact: tsc injected type errors exit 2 | 66 | 70 | -6.1% | yes |
schema: 6 tool definitions per session | 0 | 1398 | cost | yes |
Fair total (default settings, only rows where all needed info was kept, folder view compared with a plain file list, duplicate full-detail rows left out): 49,349 → 7,627 tokens, 84.5% saved.
Including the tool definitions (1,398 tokens, paid once per session): 81.7% saved for one session doing each task once.
Comparing the folder view with reading every file instead gives 92.4%, but that overstates it, because the outline does not contain the code.
Honest limits:
Small command outputs (≤ ~1,200 chars) come back verbatim with an
[exit N]marker, so they cost a few tokens more than raw (eslint −2.5%, tsc −6.1% above).Compact search lists every matching file with its count, but shows only the first 3 match lines per file; the rest are named as
+N more in this file (search path=…). Searching that file, or raisingmaxMatches, shows everything. Full-detail search saves only ~35%.Tool definitions cost ~1.4k tokens per session, so a very short session can cost more than it saves.
Savings depend on your repo and on the agent actually choosing these tools.
@anthropic-ai/tokenizermatches older Claude models; for current models treat the numbers as close approximations. Ratios matter more than absolute counts.
Configuration
Precedence is env > LEAN_CONFIG file (default ~/.lean-context/config.json) > defaults. Config inside a repo is never read, so a cloned repo cannot widen its own allowlist.
env | default | meaning |
| cwd | Allowed roots, separated by |
| built-in list | Replaces the allowlist; patterns separated by |
| — | Appends to the allowlist. |
|
| Location of |
|
| JSON config file |
| 8000 | Output cap per tool call. |
| 300 | Default |
|
| Path to the ripgrep binary. |
The default allowlist is npm test, npm run *, npx vitest, npx jest, npx tsc, npx eslint, tsc, eslint, phpunit, vendor/bin/phpunit, php artisan test, pytest, python -m pytest, python3 -m pytest and go test. A pattern matches as a token prefix, and * stands for exactly one token. For example, npm run * allows npm run lint -- --fix.
Security model
Every path is realpath-checked against
LEAN_ROOTS, so..and symlink escapes are rejected. Writes (notes) go through the same check, using the nearest existing ancestor.run_compactnever uses a shell. It rejects shell operators and metacharacters (|,&&,;,>, backticks,$(), as well as program paths other thanvendor/bin/*andnode_modules/.bin/*. It also blocks arguments that would turn an allowed runner into arbitrary execution:go -exec/-toolexec,npm --script-shell/--node-options, npx-p/--package/-c/--callbefore the tool name, andpytest -p/--pyargs/--rootdir/-c/--confcutdir.Note that allowing
npm run *ornpm testmeans running whatever those scripts contain in a repo you trust. UseLEAN_ALLOWto narrow the list.On timeout, the whole process group is killed.
The server only reads files and runs allowlisted commands. It makes no network calls and sends no telemetry.
Run logs go to
$TMPDIR/lean-context/(mode 600). Notes go to~/.lean-context/cache.jsonand<repo>/.lean-context/notes.md.
Why it re-execs itself
Loading several tree-sitter WASM grammars can crash Node's optimizing WASM compiler ("Fatal process out of memory: Zone"). The entry point therefore relaunches itself once with node --liftoff-only. You don't need to pass the flag. Set LEAN_NO_REEXEC=1 to disable it.
Develop
npm install
npm run lint && npm run typecheck && npm test # test builds first, then runs vitest
npm run measure -- /path/to/repo # token comparison on any repoGrammars: the 7 tree-sitter grammars used (TS, TSX, JS, PHP, Python, Go, Swift) are copied from tree-sitter-wasms into dist/grammars at build time, so the installed package does not need that 50 MB dependency.
Squeezer fixtures in test/fixtures/output are real captured outputs, except phpunit-* and artisan-fail, which are hand-written in PHPUnit 10/11 and Pest formats.
License
MIT
Available Tools
6 toolsoutlineARead-only
Symbol map of a file (signatures + line ranges) or dir (files with symbol counts). Use before reading files.
Inputs: path (required), depth.
project_notesC
Repo memory (/.lean-context/notes.md): conventions, decisions, commands.
Inputs: action (required), path, content.
read_symbolCRead-only
Source of one symbol (e.g. "fn", "Class.method") or a line range.
Inputs: file (required), symbol, endLine, startLine.
run_compactA
Run an allowlisted test/build/lint command (no shell). Returns exit code + failures only; full log path included.
Inputs: command (required), cwd, maxLines, timeoutSec.
searchBRead-only
Code search (ripgrep), grouped by file. Every matching file is listed with its count; big results are compacted. Literal unless regex=true.
Inputs: query (required), glob, path, regex, +4 more.
summary_cacheA
Short per-file notes, auto-invalidated when the file changes. get before reading; set after understanding a file.
Inputs: files (required), action (required), note.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Tools are mostly distinct: outline (structure), read_symbol (content), search (find), run_compact (execute), and two memory tools. The only overlap is project_notes vs summary_cache, but descriptions clearly separate repo-level decisions from per-file notes.
Mixed conventions: verb_noun (read_symbol, run_compact), bare verbs (search, outline), and noun phrases (project_notes, summary_cache). Still readable and predictable enough to navigate, but no single pattern holds.
Six tools is well-scoped for a lean context server, with each tool covering a distinct stage of the read/navigate/remember workflow. No bloat or redundancy.
Covers navigation (outline, search), reading (read_symbol with line ranges), memory (project_notes, summary_cache get/set), and command execution with compact output. Minor gap: no explicit listing or invalidation control of cached notes beyond automatic file-change invalidation.
Related MCP Connectors
Codebase intelligence for agents: 152 structured artifacts across 21 programs, one call.
Provide your AI coding tools with token-efficient access to up-to-date technical documentation for…
Research-backed lint + generation for agent context files (CLAUDE.md, AGENTS.md) + prompt enhancer.
Code-map tools for AI agents: see a repo's structure first, then edit only what matters.
Related MCP Servers
- AlicenseAqualityDmaintenanceProvides AI coding assistants with context optimization tools including targeted file analysis, intelligent terminal command execution with LLM-powered output extraction, and web research capabilities. Helps reduce token usage by extracting only relevant information instead of processing entire files and command outputs.529 npm63TypeScriptMIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to obtain a compressed code context where the active file is fully included and dependency files are reduced to type signatures, interfaces, and exports, cutting token usage while preserving code shape.32 npmMIT
- 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
- AlicenseAqualityBmaintenanceEnables a coding agent to get short, token-efficient answers about a project through grouped searches, focused symbol or section reads, and bounded read-only script output, with safety limits on paths, secrets, commands, and response size.3MIT