Tree-Sitter Code Parsing Use Cases for AI Agents
Part of the Code Knowledge Graphs guide. Start with Knowledge Graph for Code Explained: A Practical Guide
I can extract normalize(value) from a syntax tree and still have the wrong dependency graph. The call's spelling tells me where to look, but if a local binding shadows it, which this query doesn't check, there's more work before I can tell an agent what will break.
I build Pharaoh. Its parser, pharaoh-parser, is open source under MIT and built on Tree-sitter.
The useful place to start is a small file and a query you can inspect. Extract declarations for function search, imports for dependency analysis, and call expressions for candidate caller relationships, then check what each capture actually proves before handing it to an agent.
A concrete syntax tree keeps the punctuation
Tree-sitter produces a concrete syntax tree, or CST, with punctuation tokens inside its larger constructs, and each node has a type and a source range, so a tool can tell a declaration from a comment that happens to mention the same name and say where each one sits.
An abstract syntax tree, or AST, leaves out less useful syntactic detail, and Tree-sitter's named-node APIs let you skip anonymous tokens, including punctuation, so you can traverse something that behaves much like an AST without maintaining a separate tree.
Keep the distinction practical. For an agent choosing a function to inspect, the declaration's location matters, the comma between parameters usually doesn't, and neither tells you whether production ever reaches that function.
Extract functions, imports and calls
Save the examples below as two source files and two .scm query files. The teaching queries have deliberately limited coverage and use the upstream grammars' node types.
TypeScript
Use this as sample.ts:
import { normalize } from "./names";
export function label(value: string) {
return normalize(value);
}
export const tag = (value: string) => normalize(value);
Save this as typescript.scm:
(function_declaration
name: (identifier) @function.name) @function.definition
(variable_declarator
name: (identifier) @function.name
value: (arrow_function)) @function.definition
(import_statement
source: (string) @import.source) @import.statement
(call_expression
function: (_) @call.target) @call.expression
A query pattern describes a node shape, adds field constraints when needed, and labels matches with captures such as @function.name, which your program can read, without assigning semantic meaning to that label.
The fixture contains two kinds of function. typescript.scm captures label and tag as names, the import's "./names" string, and the two normalize call targets, with no name resolution. The arrow pattern's definition capture is the variable_declarator, tag = (value: string) => normalize(value) without const, and the function pattern's is the function_declaration, so neither includes the surrounding export_statement.
Notice the coverage boundary. typescript.scm doesn't extract class methods or anonymous callbacks as named functions, doesn't resolve an import to a file, and doesn't establish which declaration a call refers to, even when the target is a plain identifier.
tree-sitter-typescript provides separate TypeScript and TSX grammars. Use the TSX grammar when extending this exercise to JSX syntax.
Python
Use this as sample.py:
from names import normalize
def label(value):
return normalize(value)
Save this as python.scm:
(function_definition
name: (identifier) @function.name) @function.definition
(import_statement) @import.statement
(import_from_statement
module_name: (dotted_name) @import.source) @import.statement
(call
function: (_) @call.target) @call.expression
The Python fixture uses a from import. python.scm captures label, that import with module name names, and the normalize call target, while the extra import pattern handles ordinary import names statements. Relative imports such as from .names import normalize produce no capture at all, because their module_name is a relative_import, not a dotted_name, so add a pattern for them before you trust the import list.
The node types come from each grammar. tree-sitter-python uses call, while tree-sitter-typescript uses call_expression, so port the pattern itself, not just the language label.
Check the TypeScript node definitions when adding syntax.
The Python node definitions describe the corresponding Python shapes.
Run both queries
In a Python 3.10 or newer environment, install the Python bindings and the two grammar packages:
python3 -m pip install tree-sitter
python3 -m pip install tree-sitter-typescript
python3 -m pip install tree-sitter-python
Save this runner as captures.py alongside the four files:
import sys
from pathlib import Path
import tree_sitter_python
import tree_sitter_typescript
from tree_sitter import Language, Parser, Query, QueryCursor
languages = {
"ts": Language(tree_sitter_typescript.language_typescript()),
"py": Language(tree_sitter_python.language()),
}
language = languages[sys.argv[1]]
source = Path(sys.argv[3]).read_bytes()
tree = Parser(language).parse(source)
query = Query(language, Path(sys.argv[2]).read_text(encoding="utf-8"))
captures = QueryCursor(query).captures(tree.root_node)
for name, nodes in captures.items():
for node in nodes:
print(name, node.start_point.row + 1, repr(node.text.decode("utf-8")))
Run it from that directory:
python3 captures.py ts typescript.scm sample.ts
python3 captures.py py python.scm sample.py
The output is grouped by capture name. captures.py prints each name, its one-based starting line, and the matched text, keeping file-local matches visible before you add resolution.
The QueryCursor API documents the dictionary returned by captures.
I would test the next pattern against a file that already causes trouble in your repo. Add an aliased import, a method call, a nested function, or a relative Python import and inspect the captures before expanding the index.
A call expression still needs resolution
Change the TypeScript import to import { normalize as clean } from "./names" and call clean(value). The call capture now contains clean, even though the imported name is normalize, and the declaration in the other file can keep that original name, so matching names alone would lose the relationship.
This is where the use cases separate. Function discovery can start with names and locations, dependency analysis needs module resolution, and a caller graph also needs to connect references to declarations, with unresolved references kept visible rather than silently treated as absent.
See how parse trees become a code knowledge graph for the next layer.
Incremental parsing doesn't update your whole index
Tree-sitter supports reusing an edited tree. First update the old tree's ranges with the edit's starting byte offset, its old and new end positions, and row-column coordinates, then parse the new source while passing that tree. The new tree can share unchanged structure with the old one.
That helps when an editor repeatedly parses a changing file. Your application still needs a policy for invalidating extracted records and relationships when a declaration moves or an import changes.
Tree-sitter can also represent malformed input with ERROR nodes, or recover by inserting zero-width missing tokens, so check both kinds before trusting an extraction, especially around a declaration your agent is editing. The documentation for error and missing-node queries explains why an ERROR query alone doesn't find missing nodes.
I wouldn't equate a successful parse with a complete index. Keep parse diagnostics beside the extracted records, preserve which revision they describe, and let the agent see any failed files, otherwise a missing caller can look like evidence that no caller exists.
Isolate WASM aborts from the server
Syntax recovery and runtime failure need different handling. For an Emscripten-based WASM parser, an abort can leave its runtime unusable, even if JavaScript receives an exception, so discard that runtime.
Emscripten's abort documentation says recovery isn't possible at that point.
I would put that parser in a disposable child process. In Node, child_process.fork creates an independent process, giving the parent a boundary for detecting an exit, recording the failed job, and starting a fresh runtime for later work.
Give each job a timeout and a bounded input size. If it fails, report the coverage gap, keep any incomplete result out of the published index, and avoid retrying the same crashing input indefinitely, so one file doesn't monopolize the worker queue.
What the graph adds for an agent
Pharaoh is a hosted service that maps TypeScript, JavaScript, Python, C and C++ repositories into a graph and answers questions over MCP.
For a concrete example, get_unused_code can return a path from an entry point to a requested function, and the full result below was captured from repository Pharaoh-so/cal.diy, revision 54343aa6, on October 26, 2026.
# Reachability in cal.diy
- checkAdminOrOwner (packages/features/auth/lib/checkAdminOrOwner.ts): reachable: getAtomEventTypeApp → getEventTypesAppIntegration → checkAdminOrOwner
That result connects a function to a path in the mapped repo. For cleanup, Pharaoh labels unreached functions Dead only when every signal agrees, including no names in other files and no production imports of their file, while Possibly unused retains those ambiguous references for you to inspect.
The comparison of code graph MCP servers covers how each one indexes, hosts and refreshes a repository.
The change-impact guide covers callers to inspect before an edit.
Keep freshness separate from parser speed. Pharaoh maps the default branch, re-maps a live repo when that branch receives a push, and doesn't include uncommitted edits, so a local query and the hosted graph can describe different revisions of the same file.
Start with a function you know has callers. Check whether the captures give you enough evidence to find them before you trust the index to guide an edit.
Connect a repository to Pharaoh.
Article Record
Update HistoryMeaningful revisions to this article
- Embedded a YouTube video to give readers an additional way to understand Tree-Sitter code parsing use cases for AI agents.