Dokumentation

Core Tools - Dateien & Code

ctx_read, ctx_multi_read, ctx_tree, ctx_shell, ctx_search, ctx_execute - die grundlegenden Tools für Dateizugriff, Verzeichnisnavigation, Befehlsausführung und Code-Suche, und Sandbox-Code-Ausführung.

Die grundlegenden Tools. Diese handhaben Dateizugriff, Verzeichnisnavigation, Befehlsausführung und Code-Suche, Sandbox-Code-Ausführung - die Operationen, die 90% der KI-Coding-Interaktionen ausmachen.

ctx_read

ctx_read is the most impactful tool in LeanCTX. It replaces your editor's built-in file read with an intelligent, session-aware reader that caches content, extracts dependency maps, and computes diffs. Every response includes structured headers with file references, dependencies, and exports.

Parameter

ParameterTypErforderlichBeschreibung
pathstringYesAbsolute file path
modestringNoauto, full (default), map, signatures, diff, aggressive, entropy, task, reference, or lines:N-M (e.g. lines:10-80 or lines:10-80,120,200-240)
start_linenumberNoRead from this line number to end of file (bypasses cache stubs)
freshbooleanNoBypass cache and force a full re-read. Use after context compaction, in subagents, or when you see a cache-hit but no longer have the file content.

Mode: auto

Auto-selects the best mode for a file based on size, language, and token signature. Use it when you’re not sure whether you need map, signatures, or full.

ctx_read server.rs --mode auto
→ [auto] resolved to map

Mode: full (default)

Reads the entire file with structured headers (dependencies, exports) and stores it in the session cache with a BLAKE3 hash. On subsequent reads, returns a compact cache-hit message instead of the full content.

# First read: returns full content with structured header
ctx_read auth.ts
→ [full file content...]
  F1=auth.ts 123L
   deps db,crypto
   exports createUser,validateSession

# Second read: returns cache hit (~13 tokens)
ctx_read auth.ts
→ F1=auth.ts cached 2t 123L

Savings: ~99% on re-reads.

Mode: map

Returns a dependency graph, exports list, and API signatures - everything the LLM needs to understand a file's role without reading its implementation. Use for context files you won't edit.

ctx_read server.rs --mode map
→ F2=server.rs [262L]
    deps: rmcp::model::, rmcp::handler::server::ServerHandler, ...
    exports: -
    API:
      fn tool_def(name:&'static str, ...) → Tool
      fn get_str(args:...) → Option<String>
      fn execute_command(command:s) → String
  [2135 tok saved (93%)]

Supports 18 languages via tree-sitter AST parsing (TS/JS, Rust, Python, Go, Java, C, C++, Ruby, C#, Kotlin, Swift, PHP, Bash, Dart, Scala, Elixir, Zig). Savings: 85-95%.

Mode: signatures

Extracts function signatures, interface definitions, type aliases, and class declarations using tree-sitter AST parsing across 18 languages (TS/JS, Rust, Python, Go, Java, C, C++, Ruby, C#, Kotlin, Swift, PHP, Bash, Dart, Scala, Elixir, Zig). More detail than map mode - includes private functions, nested signatures, and multi-line definitions. Uses compact notation with type abbreviations.

ctx_read auth.ts --mode signatures
→ F1=auth.ts [123L] deps:[db,crypto]
  fn generateToken():s
  fn ⊛ createUser(email:s, password:s, name:s, locale:s)
  fn ⊛ authenticateUser(email:s, password:s)
  fn ⊛ validateSession(token:s)
  [794 tok saved (87%)]

Mode: diff

If the file was previously cached and has changed, returns only the changed lines.

ctx_read auth.ts --mode diff
→ F1=auth.ts [diff]
  L42: - const TOKEN_EXPIRY = 3600;
  L42: + const TOKEN_EXPIRY = 7200;
  [saved 890 tokens (97%)]

Mode: aggressive

Returns full file content with syntax stripping: reduced indentation, removed comments, stripped empty lines. Savings: 20-40%.

Mode: entropy

Shannon entropy filtering removes low-information lines. Jaccard similarity deduplicates similar code blocks. Best for files with boilerplate or repetitive patterns. Savings: 60-85%.

Mode: task (graph-driven)

Task-conditioned read: filters the file down to task-relevant lines (information bottleneck filter), and appends a compact Graph Context footer listing the most relevant related files (imports, imported-by, transitive-dep, type-provider).

How it knows the task: set your current task via ctx_session action=task (or any workflow that sets session task), then read with mode=task.

Graph context is best-effort: it uses an existing project graph if present (prefers SQLite property graph; falls back to the lightweight JSON graph index). It does not build graphs implicitly in task mode - run ctx_graph action=build (fast) or ctx_impact action=build (deep) once per project to enable it.

ctx_session action=task value="fix auth refresh token bug"
ctx_read src/auth/service.rs --mode task
→ F1=src/auth/service.rs 412L [task-filtered: 412→38]
  ...task-relevant lines...
--- GRAPH CONTEXT (source=graph_index, 4 related files, 9180 tok) ---
  src/auth/token.rs [imports] (1220 tok)
  src/http/middleware.rs [imported-by] (980 tok)
--- END GRAPH CONTEXT ---

Mode: reference

Ultra-compact reference line for files you want to keep in mind without pulling content into the context window. Useful when a file is relevant by name/location, but you don’t want to spend tokens yet.

ctx_read Cargo.lock --mode reference
→ F9=Cargo.lock: 14823 lines, 39210 tok (lock)

Mode: lines:N-M

Read only specific lines with line numbers. Supports single lines and comma-separated ranges: lines:10-80, lines:42, lines:10-80,120,200-240.

ctx_read src/server.rs --mode lines:120-150
→ F3=src/server.rs 812L lines:120-150
  120| pub fn handle_request(...) {
  ...

Structured Headers

Every ctx_read response includes a structured header:

F1=auth.ts 123L
 deps db,crypto
 exports createUser,validateSession
  • F1, F2, ... - file reference IDs that persist for the session
  • =short_path - abbreviated file path
  • 123L - line count
  • deps ... - imported modules (compact list)
  • exports ... - exported names (compact list)

Compact Notation

  • - async function
  • :s, :n, :b - type abbreviations (string, number, boolean)
  • fn, cl, if, tp - keyword abbreviations

Security

All file reads pass through the PathJail sandbox. Paths must resolve inside the project root - ../ traversal, symlink attacks, and absolute paths outside the project are rejected. Files exceeding LCTX_MAX_READ_BYTES (default: 5 MB) are rejected to prevent accidental ingestion of large binaries or generated files.

Cache Safety

The session cache auto-clears after 5 minutes of inactivity. For explicit control, use the fresh=true parameter to bypass cache for a single read, or ctx_cache to manage the entire cache (clear, invalidate, status).

Mode Selection Guide

SituationModusTokens
Understanding a file's rolemap~5-15%
Understanding an API surfacesignatures~10-20%
Editing a filefull100% first, ~0% cached
Checking changesdiffOnly changed lines
Large boilerplate filesaggressive~30-50%
Repetitive patternsentropy~20-40%
Task-driven context + next readstaskHighly variable
Keep a pointer onlyreference~1 line
Only a slice of a large filelines:N-MProportional to range
Not sure which mode to useautoBest-effort
Full reference →

ctx_multi_read

Batch variant of ctx_read: pass multiple file paths in one call. Each file uses the same mode and line-range rules as ctx_read, with shared session cache and file IDs (F1, F2, …).

Parameter

ParameterTypErforderlichBeschreibung
pathsstring[]YesAbsolute file paths to read
modestringNoSame values as ctx_read, including optional lines:N-M

Example

ctx_multi_read paths=["/app/src/auth.ts","/app/src/db.ts"] --mode map
→ F1=auth.ts [88L] ...
  F2=db.ts [64L] ...
Full reference →

ctx_tree

ctx_tree generates compact project structure maps using indentation instead of Unicode box-drawing characters. Each directory shows a file count for quick orientation.

Parameter

ParameterTypErforderlichBeschreibung
pathstringNoDirectory to list (default: project root)
depthnumberNoMaximum depth (default: 3)
show_hiddenbooleanNoInclude hidden files and directories (default: false)

Example

ctx_tree --depth 2

→ lean-ctx/rust/
    src/ (22)
      core/ (9)
      tools/ (8)
      patterns/ (5)
    examples/ (1)
    Cargo.toml
    README.md
  [64 tok saved (34%)]

Why It Saves Tokens

Traditional directory listings use Unicode box-drawing characters (├──, └──) which consume 3-4 tokens each. LeanCTX uses simple indentation (1 token per level), and shows file counts per directory instead of listing every file. For large projects, this saves 30-50% tokens.

TDD Mode

Tree output is already ultra-compact by design. TDD mode does not apply additional compression to ctx_tree - the output format is the same regardless of CRP_MODE.

Full reference →

ctx_shell

ctx_shell executes shell commands and applies pattern-based compression to the output. It recognizes 95+ common developer tools across 34 categories and strips verbose boilerplate while preserving actionable information.

The same compression is also available via the shell hook (lean-ctx -c command), which compresses output transparently without requiring the LLM to use context server tools.

Parameter

ParameterTypErforderlichBeschreibung
commandstringYesShell command to execute
cwdstringNoWorking directory for command execution. Persists via cd tracking across calls.
rawbooleanNoSkip compression and return full uncompressed output. Use for small outputs or when full detail is critical. Default: false.

When tee_mode is set to always in config, full uncompressed output is automatically saved to ~/.lean-ctx/tee/. Use lean-ctx tee last to view the most recent saved output.

Input Validation & Security

ctx_shell enforces multiple security layers:

  • File-write blocking - Shell redirects (>, >>), heredocs that write to files (cat <<EOF > file.txt), and tee are rejected with a clear error. Heredocs for input piping (e.g. psql <<EOF) are allowed. Use the native Write tool for file creation.
  • Command size limit - Commands over 8KB are rejected. Large heredocs corrupt the MCP protocol stream.
  • Output size cap - Output exceeding LCTX_MAX_SHELL_BYTES (default: 1 MB) is truncated with a [truncated] marker to prevent context window overflow.
  • Metadata neutralization - All output is sanitized to strip control characters and potential prompt injection patterns.

Supported Patterns (95+)

KategorieBefehleEinsparung
Git (19)status, log, diff, add, commit, push, pull, fetch, clone, branch, checkout, switch, merge, stash, tag, reset, remote, blame, cherry-pick70-95%
Docker (10)build, ps, images, logs, compose ps/up/down, exec, network, volume, inspect70-90%
npm/pnpm/yarn (6)install, test, run, list, outdated, audit70-90%
Cargo (3)build, test, clippy80%
GitHub CLI (9)pr list/view/create/merge, issue list/view/create, run list/view60-80%
Kubernetes (9)get, logs, describe, apply, delete, exec, top, rollout, scale60-85%
Python (7)pip install/list/outdated/uninstall/check, ruff check/format60-80%
Ruby (4)rubocop, bundle install/update, rake test, rails test (minitest)60-85%
Linters (4)eslint, biome, prettier, stylelint60-70%
Build Tools (3)tsc, next build, vite build60-80%
Test Runners (8)jest, vitest, pytest, go test, playwright, cypress, rspec, minitest90%
Utils (5)curl, grep/rg, find, ls, wget50-89%
Data (3)env (filtered), JSON schema extraction, log deduplication50-80%
Terraformplan, apply, fmt, validate, init, state list/show60-85%
Makemake builds, target summaries, parallel job output60-80%
Maven / Gradlemvn compile/test/package, gradle build/test60-85%
.NETdotnet build, test, restore, publish60-85%
Flutter / Dartflutter build/test/analyze, dart analyze/test/pub60-85%
Poetry / uvpoetry install/lock/show, uv pip/sync/run60-80%
AWS (7)s3, ec2, lambda, cloudformation, ecs, logs, sts60-80%
Databases (2)psql, mysql/mariadb50-80%
Prisma (6)generate, migrate, db push/pull, format, validate70-85%
Helm (5)list, install, upgrade, status, template60-80%
Bun (3)test, install, build60-85%
Deno (5)test, lint, check, fmt, task60-85%
Swift (3)test, build, package resolve60-80%
Zig (2)test, build60-80%
CMake (3)configure, build, ctest60-80%
Ansible (2)playbook recap, task summary60-80%
Composer (3)install, update, outdated60-80%
Mix (5)test, deps, compile, credo, dialyzer60-80%
Bazel (3)test, build, query60-80%
systemd (2)systemctl, journalctl50-80%

Savings measured per command execution: (raw_output_tokens - compressed_tokens) / raw_output_tokens using tiktoken o200k_base. Ranges reflect variation across typical command outputs.

Examples

git status

ctx_shell "git status"
→ feature/auth ↑3
  staged: +session.ts ~login.ts ~api.ts
  unstaged: ~session.ts
  untracked: session.test.ts
  [534 tok saved (87%)]

npm install

ctx_shell "npm install express"
→ +express@4.18.2 (3 deps, 847ms)
  [82 tok saved (71%)]

TypeScript Compiler

ctx_shell "npx tsc --noEmit"
→ 3 errors in 2 files:
  auth.ts:42 TS2345 type mismatch
  db.ts:15 TS2304 name not found
  db.ts:28 TS2304 name not found

kubectl get pods

ctx_shell "kubectl get pods"
→ 5 pods: 4 Running, 1 CrashLoopBackOff
  api-7d8f-abc12     1/1 Running   0 2d
  web-5c4e-def34     1/1 Running   0 1d
  worker-crash-xyz   0/1 CrashLoop 12 4h

docker compose ps

ctx_shell "docker compose ps"
→ 3 services: 3 running
  api    :8080 Up 2h
  db     :5432 Up 2h
  redis  :6379 Up 2h

Test Runners

ctx_shell "npm test"
→ 42 passed, 2 failed, 1 skipped (3.2s)
  FAIL auth.test.ts:23 "should validate token"
    Expected: true, Received: false
  FAIL db.test.ts:45 "should retry on connection error"
    Timeout after 5000ms

curl (JSON)

ctx_shell "curl -s https://api.example.com/users"
→ 200 OK | application/json | 2.3KB
  [item1, item2, ... +48 items]

Shell Hook Mode

Use LeanCTX as a transparent shell wrapper for automatic compression:

# Auto-install 23 aliases
lean-ctx init --global

# Or single command
lean-ctx -c git status

# Or manual aliases
alias git='lean-ctx -c git'
alias kubectl='lean-ctx -c kubectl'

# Interactive shell
lean-ctx shell

Error Recovery (Tee)

When a command fails (non-zero exit code), LeanCTX automatically saves the full uncompressed output to ~/.lean-ctx/tee/ for debugging. This ensures compressed output doesn't hide error details you might need.

Fallback

For unrecognized commands, generic compression applies: removes empty lines, strips ANSI codes, and truncates very long output with a summary.

Full reference →

ctx_search searches files for patterns using regex and returns only matching lines with compact file paths. Avoids reading entire files when looking for specific code.

Parameter

ParameterTypErforderlichBeschreibung
patternstringYesRegex pattern to search for
pathstringNoDirectory to search in (default: current dir)
extstringNoFile extension filter (e.g. "rs", "ts")
max_resultsnumberNoMaximum matches to return (default: 20)
ignore_gitignorebooleanNoInclude files normally excluded by .gitignore. Default: false.

Example

$ ctx_search "pub fn" --path src/core --ext rs --max_results 5

5 matches in 1 files:
cache.rs:27 pub fn hit_rate(&self) -> f64
cache.rs:34 pub fn tokens_saved(&self) -> u64
cache.rs:38 pub fn savings_percent(&self) -> f64
cache.rs:54 pub fn new() -> Self
cache.rs:69 pub fn get(&self, path: &str) -> Option<&CacheEntry>
[~1200 tok saved vs full reads]

Token Savings

Instead of reading entire files to find code, ctx_search returns only the matching lines. Typical savings are 50-80% compared to reading all files that contain matches.

TDD Integration

When TDD mode is active, long identifiers in search results are automatically mapped to short IDs (α1, α2...) with a §MAP table appended. This further reduces token cost for large search result sets.

Features

  • Full regex support (Rust regex crate)
  • File extension filtering
  • Automatic binary file exclusion (images, compiled files, lock files)
  • Compact path shortening (home directory → ~)
  • Token savings summary appended to results
Full reference →

ctx_execute

ctx_execute runs code in isolated subprocesses across 11 languages. Only stdout enters the context window - stderr is captured separately with exit codes. Use it to validate logic, transform data, or run quick computations without leaving the AI conversation.

Parameter

ParameterTypErforderlichBeschreibung
languagestringYesRuntime language (see supported list below)
codestringYesCode to execute
intentstringNoShort description of what the code does (included in output header)
timeoutnumberNoMaximum execution time in seconds (default: 30)
actionstringNobatch to run multiple scripts, file to process a file

Supported Languages

LanguageRuntimeAliases
JavaScriptNode.js / Bunjavascript, js, node
TypeScriptBun / ts-nodetypescript, ts
Pythonpython3 / pythonpython, py
Shellbash / sh (cmd on Windows)shell, bash, sh
Rubyrubyruby, rb
Gogo rungo, golang
Rustrustc + runrust, rs
PHPphpphp
Perlperlperl, pl
RRscriptr, R
Elixirelixirelixir, ex

Example: Single Script

ctx_execute language="python" code="print(sum(range(100)))"
→ 4950
  [python | 12 ms]

Example: Batch Execution

ctx_execute action="batch" items='[
  {"language":"python","code":"print(2**10)"},
  {"language":"shell","code":"echo hello"}
]'
→ [1/2] 1024
  [2/2] hello
  2 tasks, 28 ms total

Example: File Processing

ctx_execute action="file" path="/data/users.csv" intent="count unique emails"
→ 1423 lines, 45230 bytes, 8921 words
  Intent: count unique emails

Safety

  • Each script runs in an isolated subprocess with LEAN_CTX_SANDBOX=1 environment variable
  • Default timeout: 30 seconds (configurable per call)
  • Large outputs are smart-truncated (60% head / 40% tail) to stay within token limits
  • Only stdout enters the AI context - stderr is shown separately for debugging
Full reference →

ctx_expand v3.3.3

ctx_expand retrieves the full uncompressed content of a previously archived tool result. When the Tool Result Archive is enabled, compressed tool responses include an [ARCHIVE: <id>] reference. The agent calls ctx_expand to get back the complete data on demand.

This enables zero-loss compression: the context window stays small, but the agent can always access the full details when needed.

Parameter

ParameterTypErforderlichBeschreibung
idstringYesThe archive reference ID (from the [ARCHIVE: ...] marker in a compressed response)
actionstringNoget (default) - retrieve full content; list - show all archived entries; stats - show archive statistics

Example: Retrieve Archived Content

# Agent sees in compressed response:
#   [ARCHIVE: a1b2c3d4] Use ctx_expand to retrieve full output

ctx_expand id="a1b2c3d4"
→ [Full uncompressed content from original tool call]

Example: List Archives

ctx_expand action="list"
→ 3 archived results (2.1 MB total)
  a1b2c3d4  ctx_shell "cargo test"      12 min ago  45KB
  e5f6g7h8  ctx_read server.rs          8 min ago   23KB
  i9j0k1l2  ctx_search "TODO"           3 min ago   12KB

How It Works

  1. When a tool result exceeds the configured token threshold (default: 500), LeanCTX stores the full content to ~/.lean-ctx/archive/
  2. The compressed response includes the archive reference ID
  3. The agent calls ctx_expand with that ID to retrieve the original content
  4. Archived entries are automatically cleaned up after the configured TTL (default: 120 minutes)

Configure the archive via config.toml - see Archive Configuration.

Full reference →

ctx_call v3.4.0

ctx_call is a compatibility meta-tool that lets MCP clients call any ctx_* tool by name using a stable schema. This is useful for clients that freeze the tool registry at startup (static tools/list).

ParameterTypeDescription
toolstringName of the ctx_* tool to call (e.g. ctx_read)
argumentsobjectArguments to pass to the target tool

ctx_provider v3.4.5

ctx_provider fetches external context from providers like GitLab. It supports listing issues, MRs, and pipelines directly within the agent context. Requires GITLAB_TOKEN or LEAN_CTX_GITLAB_TOKEN environment variable.

ParameterTypeDescription
actionstringgitlab_issues, gitlab_issue, gitlab_mrs, gitlab_pipelines
iidnumberIssue or MR number (for gitlab_issue)
statestringFilter by state: opened, closed, merged