AI Coding Agents
Build a Tree-sitter Code Outline and Symbol Reader for Coding Agents
A Tree-sitter code outline gives an LLM the names and line ranges of definitions before it reads their bodies. Use the outline when the agent knows the file and needs to choose a small number of functions or classes, then fetch each selected definition with its module imports and escalate to the full file when surrounding code affects the decision.
Decide what the first read should answer
Suppose a coding agent knows a cleanup bug is in a particular module. Its first question is which implementation handles the failing case. If the module defines a synchronous manager, an asynchronous manager, and several wrappers, returning a qualified name and a line range for each definition helps the agent choose where to look. A second read can show the chosen method, the decorator that affects how it is called, and the import aliases that appear in its body. Start with the whole file if the task already requires comparing those implementations or tracking how they share state.
The first read in this design is a map of one file. It exposes the classes and functions it can identify, including methods and nested definitions. The second read stays tied to the revision the agent inspected. A full-file operation remains available when the answer depends on code between definitions, such as an assignment that builds a registry or a gate that selects an implementation during import. Qualification distinguishes a method on one manager from a method with the same name on another.
Billing follows the material that reaches the model. A compact outline can avoid sending bodies the agent never uses, and an extra call can require another model request. If the model later asks for the full file too, the session can end up carrying the outline, the extracted body, and the entire module. Track fallback and repeated requests alongside provider-reported input usage. A smaller response on the first call only shows what happened at that point in the task. Measure coding agent token savings
Pick between syntax, language servers, and repo maps
A Tree-sitter query can capture the outer definition using the documented tags convention and capture its identifier separately as @name. The example uses @definition.class and @definition.function and limits its grammar to Python. It derives each qualified name from enclosing definitions. When a definition is decorated, it returns the larger decorated region so the later read includes the decorator lines. The grammar and the file together determine the range. The lookup can run without a project index or a workspace language server. Tree-sitter code navigation
| Option | Scope | Choose it when |
|---|---|---|
| This Tree-sitter reader | Definitions and source in a known Python file | The file is known and selecting a few definitions is enough to start |
| Aider repo map | Ranked view across repository files | The agent needs to choose where to look across the repository |
| Language server document symbols | Symbol discovery through a language server for a document | The host already has a language server and needs its view of the file |
| Serena | File summaries and symbol searches through its backend | The agent needs to move from file discovery to wider symbol lookup |
| Claude Code code intelligence | Symbol navigation and diagnostics through language server plugins | Claude Code already runs the language server for the project |
| Whole-file read | All source text in a known file | The task depends on intervening code or many definitions together |
Aider uses Tree-sitter to build its repo map. As of November 30, 2026, its docs describe a graph ranking algorithm over files connected by dependencies, with --map-tokens defaulting to 1k tokens. Aider adjusts how much of the map it supplies as the conversation changes, so treat that setting as a budget input. A repo map answers which files or identifiers look relevant. This reader answers where a chosen file defines its own functions and classes. A host could use those operations in that order when a task starts with only a rough location. Aider repository map docs, Aider’s Tree-sitter implementation
With a language server in place, compare a syntax-only outline with the server’s document symbol operation before building a new parser service. Serena offers get_symbols_overview for a file’s top-level symbols and find_symbol for local or global lookup with a language server backend. As of November 30, 2026, Claude Code’s code intelligence documentation describes a read-only LSP tool for navigation through an installed language server and plugin support for diagnostics after edits. Use project-aware navigation when the task is to trace callers or resolve a name across files. The reference reader only matches definitions found in the supplied file. Serena tools, Claude Code code intelligence, ByteCosts Serena review
The Codebase-Memory authors evaluated their Tree-sitter-based knowledge graph on 31 real-world repositories. They report 83% answer quality for the graph and 92% for a file-exploration agent, with the graph using one-tenth as many tokens. Use the result to decide what to check in your own trial, especially whether the agent can answer questions about shared state or control flow after reading isolated definitions. Measure what your agent got right as well as what it spent. Codebase-Memory paper
Parse the file and build the outline
Save the following two blocks in order as outline.py. The program uses the packages tree-sitter and tree-sitter-python. It defines two MCP-style descriptors using the spec’s name, description, and inputSchema fields. The descriptors describe the functions you can register with your host. The example itself runs locally from the command line. Configure the workspace root in the host, and let the model supply files relative to that root. Use the normal filesystem permissions or process isolation of your host to enforce access. MCP tools specification
import argparse
import hashlib
from io import BytesIO
import json
from pathlib import Path
import sysconfig
from tokenize import detect_encoding
from tree_sitter import Language, Parser, Query, QueryCursor
import tree_sitter_python
PYTHON = Language(tree_sitter_python.language())
TAGS = Query(PYTHON, """
(function_definition name: (identifier) @name) @definition.function
(class_definition name: (identifier) @name) @definition.class
""")
DEFINITIONS = {"function_definition", "class_definition"}
IMPORTS = {"import_statement", "import_from_statement", "future_import_statement"}
def mcp_tool(name, description, properties, required):
return {
"name": name, "description": description,
"inputSchema": {
"type": "object", "properties": properties,
"required": required, "additionalProperties": False,
},
}
STRING = {"type": "string"}
TOOLS = [
mcp_tool("outline", "List Python definitions and their line ranges.",
{"file": STRING}, ["file"]),
mcp_tool("read_symbol", "Read one qualified definition plus module imports.",
{"file": STRING, "name": STRING, "revision": STRING},
["file", "name", "revision"]),
]
def qualified_name(node, name):
parts = [name]
parent = node.parent
while parent is not None:
if parent.type in DEFINITIONS:
parts.append(parent.child_by_field_name("name").text.decode("utf-8"))
parent = parent.parent
return ".".join(reversed(parts))
def snapshot(root, file):
relative = Path(file)
if relative.is_absolute():
raise ValueError("use a workspace-relative file")
root = Path(root).resolve()
path = (root / relative).resolve(strict=True)
if not path.is_relative_to(root) or path.suffix != ".py" or not path.is_file():
raise ValueError("expected a Python file inside the workspace")
raw = path.read_bytes()
encoding, _ = detect_encoding(BytesIO(raw).readline)
source = raw.decode(encoding).encode("utf-8")
tree = Parser(PYTHON).parse(source)
if tree.root_node.has_error:
raise ValueError("parse errors: inspect the file directly")
revision = hashlib.sha256(raw).hexdigest()
return raw, source, tree, revision
def definitions(tree):
found = []
for _, captures in QueryCursor(TAGS).matches(tree.root_node):
kind = "function" if "definition.function" in captures else "class"
definition = captures[f"definition.{kind}"][0]
name = qualified_name(definition, captures["name"][0].text.decode("utf-8"))
node = definition
if node.parent is not None and node.parent.type == "decorated_definition":
node = node.parent
end_row, end_column = node.end_point
found.append(({
"name": name, "kind": kind, "start": node.start_point.row + 1,
"end": end_row + int(end_column != 0),
}, node))
return sorted(found, key=lambda item: item[1].start_byte)
The parser hashes the original file bytes and parses a UTF-8 representation after detecting the Python source encoding. Build the ranges and slices from the same parse buffer so byte offsets refer to the correct representation. A line range is one-based and inclusive, and a multiline or decorated definition spans all of the lines that the captured region covers. The response returns the definition text with its initial indentation preserved. A client can display the filename and range next to it or use them to request more context from the file.
For a method, the response includes the method definition and direct module-level imports. A class request returns the class definition including methods inside it. The import list deliberately includes direct module imports in source order, including unused ones. A short list preserves aliases without asking the tool to infer name resolution. Imports inside the selected definition already appear in the extracted text. Conditional imports elsewhere in the file and imports in enclosing definitions require a wider read. If a function calls an imported alias and also closes over a local variable from its parent, read the enclosing function before changing that call.
def outline(root, file):
_, _, tree, revision = snapshot(root, file)
return {"revision": revision, "symbols": [entry for entry, _ in definitions(tree)]}
def read_symbol(root, file, name, revision=None):
_, source, tree, current = snapshot(root, file)
if revision is not None and revision != current:
raise ValueError("file changed: refresh the outline")
matches = [(entry, node) for entry, node in definitions(tree) if entry["name"] == name]
if len(matches) != 1:
raise ValueError("symbol missing or ambiguous: inspect the file directly")
entry, node = matches[0]
start = source.rfind(b"\n", 0, node.start_byte) + 1
imports = [
child.text.decode("utf-8") for child in tree.root_node.named_children
if child.type in IMPORTS
]
return {
"revision": current, **entry, "imports": imports,
"source": source[start:node.end_byte].decode("utf-8"),
}
def measure():
root = Path(sysconfig.get_path("stdlib"))
file = "contextlib.py"
raw, _, tree, revision = snapshot(root, file)
result = {"revision": revision, "symbols": [entry for entry, _ in definitions(tree)]}
compact = json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
print(f"{file}: outline={len(compact)} B, full={len(raw)} B, "
f"ratio={len(compact) / len(raw):.2%}")
if __name__ == "__main__":
cli = argparse.ArgumentParser()
cli.add_argument("file", nargs="?")
cli.add_argument("name", nargs="?")
cli.add_argument("--revision")
cli.add_argument("--root", default=".")
cli.add_argument("--measure", action="store_true")
args = cli.parse_args()
if args.measure:
measure()
elif args.file:
result = (read_symbol(args.root, args.file, args.name, args.revision)
if args.name else outline(args.root, args.file))
print(json.dumps(result, ensure_ascii=False, indent=2))
else:
cli.error("provide a file or use --measure")
The revision protects the handoff between the two reads. For example, if another process edits the file after the agent receives the outline, reject the follow-up with the old digest and ask the agent to refresh. A bare symbol name that appears several times in the same lexical scope also triggers a direct read. Python can define and rebind names in source order, and a list of syntax captures alone cannot tell the agent which branch of a conditional is active. Return an error the agent can act on, including whether the file changed, the lookup was ambiguous, or the parser reported errors.
Walk through a targeted read and measure its size
Save the fixture below as fixture.py beside outline.py. It defines two classes with a run member and two top-level definitions named same.
from __future__ import annotations
import functools as ft
if False:
import math
class First:
@staticmethod
async def run():
return "café"
class Second:
def run(self):
return "other"
def same():
pass
def same():
pass
With the packages installed into a local virtual environment, run python3 -B outline.py fixture.py using that environment’s interpreter. To inspect the asynchronous definition, pass First.run as the second positional argument and copy the outline’s revision into --revision. Check that the output includes the decorator, the indented definition, and the module import list. Try the repeated same name to see the ambiguity error, then use your normal file reader to check what the repeated definitions mean for the task. To test the revision check, edit the fixture and repeat the First.run lookup with the old revision. Expect an error asking you to refresh the outline.
To compare payload sizes, run python3 -B outline.py --measure. The program picks the local Python standard library’s contextlib.py and divides the byte length of the compact UTF-8 outline JSON, including the revision, by the length of the original file bytes. Use compact JSON here even though the CLI displays an indented result during interactive use. The measurement answers what one particular serialized outline weighs relative to a particular file. In a run on CPython 3.13.14 with tree-sitter 0.27.0 and tree-sitter-python 0.25.0, the full contextlib.py file measured 27,801 bytes and the compact outline 6,568 bytes, a ratio of 23.63%. Expect a smaller outline-to-file ratio when function bodies account for more of the source, and a larger ratio when the source consists mostly of short definitions. Measure that ratio on your own files before treating this example as representative.
To extend that experiment to an agent session, start with a case that reads one method. Compare the bytes in the outline, the symbol result including imports, and the full text that the baseline agent receives. Add the tool arguments and wrapper overhead if you want to compare complete messages. Then run matched tasks with a whole-file baseline and compare provider usage by billing category, extra model requests, fallbacks, and patch acceptance. A byte ratio describes payload size. Provider usage captures the charges that come from carrying those payloads through later turns. Coding agent cost telemetry
Choose the default and the fallback
Read the whole file when the agent needs to fix a module’s initialization, inspect constants and registry assignments, compare several neighboring methods, or reason about conditional definitions. Whole-file reading can also be the shorter path for small modules and for work that begins with a precise failure line. To decide, ask what evidence will be needed to verify the proposed change. If it spans the imports, global state, and several classes, starting with a series of symbol reads may obscure their relationships and add round trips.
Start a trial with a few tasks for which one file is already known and a few for which the file is unknown. Keep the same tests and patch acceptance rules for both reading modes. For known files, give the agent an outline and let it switch to full-file reading after it identifies a missing dependency. For unknown files, use a repo map or project-aware symbol navigation to narrow the scope first. Record the choice that got the agent to an accepted result. If repeated file reads dominate either run, measure how much you can remove by reusing results for an unchanged revision. Detect duplicate file reads in coding agents, Build an agent cost ledger
Sources
- Tree-sitter code navigation (Tree-sitter, accessed 2026-11-30)
- Repository map (Aider, accessed 2026-11-30)
- Building a better repository map with Tree-sitter (Aider, accessed 2026-11-30)
- Serena tools (Serena, accessed 2026-11-30)
- Code intelligence plugins (Anthropic, accessed 2026-11-30)
- Codebase-Memory (Codebase-Memory authors, accessed 2026-11-30)
- MCP tools specification (Model Context Protocol, accessed 2026-11-30)
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
Build a Tree-sitter Code Outline and Symbol Reader for Coding Agents. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/tree-sitter-code-outline-for-agents/