tree-lens
This server is a tree-sitter-based MCP tool that lets an agent inspect codebases structurally and navigate symbols without reading whole files.
List a file's definitions (classes, functions, methods, fields) with line ranges.
Read a single definition's source by exact name from a file.
Run AST structural searches using tree-sitter S-expression patterns.
Index an entire workspace and query definitions, references, callers, and callees by name.
Measure resolution coverage with resolution statistics across the index.
Run built-in security audit presets for dangerous patterns (eval/exec, innerHTML, JDBC, etc.).
Get grammar node types and fields to write valid query patterns.
Analyze approximate cyclomatic complexity per function.
Manage workspace indexes: build, inspect status, or delete persisted caches.
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., "@tree-lens Show me the outline of src/main.py"
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.
kimi-tree-lens
Syntax-tree X-ray for Kimi Code
English | 简体中文
Why
Reading whole files wastes context, and Grep finds strings but cannot express structure — "every assignment to a field inside a constructor" is out of its reach. kimi-tree-lens compiles tree-sitter to WASM and serves it over the Model Context Protocol, so the agent queries the syntax tree instead — inside strict path confinement and hard resource caps:
Outline instead of read — list a file's definitions with line ranges, then fetch only the one method that matters.
Structural search — S-expression queries capture AST shapes string tools cannot express.
Workspace-scale navigation — a persisted, incrementally-refreshed symbol index answers "where is this defined / called" across tens of thousands of files.
Security audits as presets — dangerous-pattern queries (eval/exec, subprocess with
shell=,innerHTMLassignment, JDBCexecute,System.exit,os/exec…) shipped built-in.
A managed plugin for Kimi Code.
Related MCP server: ast-outline-mcp
Design philosophy
Keep context clean, no noise — the agent's most expensive resource is context; the outline-first, definition-second read path turns "look at one method" from ingesting a whole file into one precise hit.
No built-in LSP server — LSP serves humans inside editors (completion, diagnostics, sessions); this plugin serves an agent beside a codebase, and tree-sitter's granularity is exactly right for that without the extra weight.
Security fence — the agent points this tool at arbitrary code: path confinement, read-time re-validation, hash pinning and resource caps are not bolted-on features; they are the price of admission.
Supported languages
Java · Python · TypeScript · TSX · Go
Tools
Tool | Purpose |
| Outline a file (classes, functions, methods, fields...) with line ranges |
| Parse a file's outline and cache it (later calls on the same file are cache hits); cheap triage of search results before reading files |
| Read one definition's source by exact name |
| Run a tree-sitter query (S-expression pattern) against a file |
| Parse all supported sources under a directory into a symbol index |
| Name-based navigation over the index; |
| Heuristic call-graph over the index; hits carry language + receiver + resolution confidence, optional file/language filters |
| Measure resolution coverage of the whole index: exact/likely/name-only tiers, per- |
| Index state, totals, watcher status |
| Drop an index: clears it from the session and deletes its persisted cache files; omit |
| Built-in audit queries (eval/exec, subprocess, innerHTML, JDBC...) |
| Grammar node types and fields, for writing correct query patterns |
| Approximate cyclomatic complexity per function, worst first |
Install
Prerequisite: Node.js ≥ 20.6.
In Kimi Code, run:
/plugins install https://github.com/zhaoxingxing06/kimi-tree-lensThen /reload or start a new session — that's it. Installing automatically registers:
the
tree-lensMCP server — all tools become available asmcp__tree-lens__*1 read-only sub-agent,
tree-lens-tracer(call-chain tracing; see Sub-agents)3 hooks enforcing a read-before-edit gate (see Read-before-edit gate)
Plus the always-on usage prompt (SYSTEM.md) and the on-demand code-search skill. On first launch the MCP server installs its runtime dependencies automatically (one-time, needs network). Grammar WASMs for all five languages ship prebuilt and are SHA-256-verified at load time — no build step is ever required.
Sub-agents
Installing also registers 1 read-only sub-agent, tree-lens-tracer — it has no write tools and no index_workspace (indexing stays with the main agent), traces "who calls X / what does X call" through callers / callees / ast_search, and returns the chain as a box-drawn tree of nodes, each node backed by file:line evidence and a confidence tier.
Outline cache
The cached_outline(file) MCP tool parses a supported source file into a definition outline (name, kind, line ranges — no code) and caches it at ~/.kimi-code/tree-lens-hook/outlines/ keyed by size + mtimeMs; later calls on an unchanged file are cache hits. Use it to triage search results before deciding which files to read.
Read-before-edit gate
While the plugin is enabled, three hooks maintain per-session read state and surface call-site context around edits (fail-open: if a hook crashes or times out, the operation proceeds):
Hook | Event | Behavior |
| PostToolUse on | Records every file the session touches into a per-session ledger |
| PreToolUse on | Blocks an edit once per symbol, only when it touches definitions whose exact or type-anchored call sites the session has not read yet, or whose same-named copies in other modules have drifted (body differs; universal method names like |
| SessionStart | Builds the workspace symbol index in the background so later queries are fast |
Writing a brand-new file is always exempt (the target does not exist yet). Ledger state and the edit-trace traces.log live under ~/.kimi-code/tree-lens-gate/, keyed by session id + cwd.
Envelope the model receives on a block (placeholder data):
[tree-lens gate] edit paused once to surface impact info — re-issue the SAME edit to proceed (already recorded; the retry passes silently).
src/order/service.ts
call sites not read this session:
- calcTotal (function:120), called at:
src/order/checkout.ts:88 (exact)
src/order/invoice.ts:45 (exact)
cross-module drift:
- calcTotal: body differs in module-a, module-b (identical in module-c) — check whether this change should be ported
("not read" is ledger-based: full-file reads count as fully read; if you already know these, just re-issue.)First line is the action: re-issue the same edit to proceed (at most one block per symbol per session)
call sites not read this session: exact or type-anchored call sites the session has not read yetcross-module drift: same-named definitions in other modules whose bodies differ (universal method names liketoString/equalsare skipped); omitted when all copies are identicalWhen both sections are empty the edit passes silently
Troubleshooting
Symptom | Fix |
Tools don't show up | Run |
First launch is slow or fails | The one-time dependency install needs network; if it fails (offline), run |
| A grammar WASM was rebuilt or tampered; run |
Unsupported file type / Node errors | The plugin needs Node.js ≥ 20.6; check |
Security model
This plugin is designed to be pointed at arbitrary code by an LLM agent:
Path confinement — every
file/rootargument must resolve (afterrealpath) inside the workspace roots advertised by the host,$TREE_SITTER_MCP_ROOTS, or the nearest project marker (.git,package.json,pom.xml, ...). Paths with no marker are rejected unlessTREE_SITTER_MCP_ALLOW_UNCONFINED=1is set explicitly.Read-time re-validation — file paths are re-resolved and fence-checked inside the worker at read time, so symlink swaps between validation and I/O cannot escape the workspace.
Grammar integrity — every grammar WASM is SHA-256 pinned in
lib/grammar-hashes.json; a mismatch refuses to load.Resource caps — 1 MB per file, NUL-byte binary rejection, soft/hard deadlines per tool (timed-out workers are replaced), bounded index (SQLite default 20000 files / hard 100000; JSON fallback 1500 / 5000; depth 40) and bounded output sizes.
No network, no subprocess — the server only reads files under allowed roots and writes its index cache under
~/.kimi-code/tree-sitter-plugin-cache/.
Reference project benchmark report
metric | value |
cold index (449 Java files, 4088 symbols) | ~1.1s |
scale · cold index | 3.4s (~5846 files/s) |
scale · single-file incremental re-index | 213ms (parsed=1, reused=19999) |
scale · query latency (200 randomized lookups) | p50 0ms / p95 1ms / max 150ms |
scale · process RSS after index | ~295 MB |
License
MIT. Bundled grammar WASMs are built from the official tree-sitter-java/-python/-typescript/-go repositories (MIT licensed) at pinned tags; see build-wasm.sh for the exact versions.
Available Tools
15 toolsanalyze_complexityCyclomatic complexity per functionA
Approximate cyclomatic complexity (1 + decision points: if/loops/case/catch/&&/||/ternary) per function in a source file, worst first.
Inputs: file (required), language.
ast_searchAST structural searchA
Run a tree-sitter query (S-expression pattern) against a source file and return captures with line numbers. Use for AST-shaped matching that Grep cannot express.
Inputs: file (required), pattern (required), limit, offset, +1 more.
calleesFind functions called by a functionA
Heuristic (name-based) call sites inside a function's body, grouped per callee name, with file, language, receiver object and a confidence tier (exact/likely/name) for the callee resolution. Same-named callees of different classes are grouped under one name; use the resolved_to fields to disambiguate. Accepts optional file/language filters. If the index for root does not exist yet it is built automatically.
Inputs: name (required), file, root, limit, +2 more.
callersFind call sites of a functionA
Heuristic (name-based) call sites of a function in the indexed workspace: each hit gives file, line, language, enclosing caller function and receiver object, plus a confidence tier (exact when the receiver's declared type or an import resolves the callee, likely for same-dir/unique names, name as fallback). Same-named methods of different classes are mixed in one result; filter by resolved_to for a precise call graph. Accepts optional file/language filters. If the index for root does not exist yet it is built automatically.
Inputs: name (required), file, root, limit, +2 more.
delete_indexDelete a workspace indexA
Drop a workspace symbol index built by index_workspace: removes it from the current session and deletes its persisted cache files (SQLite db / JSON) so the next index_workspace rebuilds from scratch. Omit root when exactly one index exists; with several indexes you must pass root. Non-destructive to source files — only cache is removed.
Inputs: root.
find_referencesFind identifier occurrencesA
Occurrences of an identifier across the indexed workspace, marking definition sites. References are classified with confidence tiers: exact (import-resolved or local), likely (same-dir or unique name), name (fallback). If the index for root does not exist yet it is built automatically (first call may be slow).
Inputs: name (required), file, root, limit, +1 more.
get_node_typesList grammar node typesA
List named node types, anonymous tokens and field names for a language's grammar — use it to write correct ast_search query patterns without trial and error.
Inputs: file, language.
go_to_definitionFind definitions by nameA
Definition sites of a name across the indexed workspace, nearest to the optional file first. If the index for root does not exist yet it is built automatically (first call may be slow).
Inputs: name (required), file, root, limit, +1 more.
index_statusReport index statusA
Report current workspace index state: root, version, totals, watcher active, pending dirty paths. Without root, reports the most recently built index plus all available roots.
Inputs: root.
index_workspaceIndex workspace symbolsA
Parse all supported source files under a directory into a persisted symbol index (definitions + identifier occurrences + call sites), backed by SQLite when available (JSON fallback). Run once before find_references / go_to_definition. Indexes are kept per root: indexing a new root adds a second index instead of replacing the existing one.
Inputs: root (required), maxFiles.
list_definitionsList definitions in a fileA
List definitions (classes, functions, methods, fields, structs...) in a source file with name, kind and line ranges. Structural alternative to reading the whole file.
Inputs: file (required), language.
list_presetsList audit query presetsB
List built-in and user-provided audit query presets per language (eval/exec, subprocess shell, innerHTML, System.exit, os/exec...).
Inputs: language.
preset_searchRun an audit query presetA
Run a named preset (see list_presets) against a source file and return capture hits with line numbers.
Inputs: file (required), name (required), language.
read_definitionRead one definitionA
Read the source code of one definition (method/class/function...) by exact name from a source file. Overloads and same-named definitions are all returned with line numbers.
Inputs: file (required), name (required), language, maxLines.
resolution_statsMeasure cross-file resolution coverageA
Aggregate resolution statistics over the indexed workspace: share of call sites resolved at each confidence tier (exact/likely/name), how import names resolve, and how many names are defined in several files. Use it to measure, not assert, how well cross-file navigation works on a given codebase.
Inputs: root.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 15 tools
Most tools target clearly distinct operations (read vs list vs search vs index), and descriptions include enough detail to separate them. Minor overlap exists between find_references/callers and go_to_definition/read_definition, but the descriptions identify different granularities and index dependencies.
All tool names use consistent snake_case with a clear verb_noun or noun form (list_definitions, index_workspace, preset_search, callers, callees). No mixed conventions or vague generic verbs appear.
15 tools is well within the appropriate range for a code-analysis server: file-level reading/querying, workspace indexing, reference resolution, call-graph helpers, and presets each have a clear place. The count feels deliberate rather than padded.
The surface covers the domain well: per-file definitions, AST queries, presets, indexing lifecycle, reference/definition lookup, and call-graph analysis. A minor gap is the lack of workspace-wide AST/search operations and no listing of files/symbols across the workspace, but agents can work around those with existing tools.
Maintenance
Related MCP Connectors
Code intelligence for coding agents: semantic, AST, graph, and full-text search. 279+ languages.
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
Hosted code graph over MCP: exact callers, dependencies, and cross-repo blast radius for AI agents.
Shared context for your codebase: a hosted code knowledge graph over MCP. Free plan, OAuth sign-up.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables LLM agents to query a codebase's structural knowledge (symbols, imports, call graphs, etc.) via MCP, reducing tokens and improving correctness compared to raw file access.32 npm7MIT
- AlicenseAqualityCmaintenanceEnables AI coding agents to efficiently explore codebases by providing structural outlines, module digests, symbol bodies, and AST-aware grep via MCP.414 npm1MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents to query code structure efficiently through 16 MCP tools, including symbol lookup, full-text search, dependency analysis, and refactor planning, powered by tree-sitter parsing and index-backed code intelligence.3MIT
- AlicenseNot gradedqualityBmaintenanceProvides IDE-like coding capabilities for AI agents via MCP, enabling semantic code retrieval, symbol-level editing, refactoring, and navigation across many programming languages.MIT