
Essay Code and Repo Agents
Codebase Summarization Agent Using Tree-Sitter and Embeddings
Parsing code into syntax-aware chunks gives agents better retrieval.
A codebase summarization agent using Tree-sitter and embeddings starts with a simple principle. Code should be understood through its structure. Parsing before embedding gives the agent meaningful units to retrieve, while incremental updates and a persistent runtime keep that knowledge useful. This foundation for repository understanding still requires more than vector search to answer exact dependency questions.
Why reading raw files is an expensive way for an agent to understand code
An agent goes through files, runs another search, and uses more tokens without finding where the bug lives. Each tool call shows more source, but even with more context, the agent may still fail to see how the pieces connect. Codebase-Memory documents exploration sessions that require dozens of tool calls before an agent can answer a structural question about what breaks when a function changes.
That mismatch makes exploration expensive. Production agentic workloads report per-task LLM API costs of several dollars on non-trivial repositories, with input tokens dominating even when caching is used. Text search can find a reference, but to follow a dependency chain, the agent has to search again, then again. Each step consumes tokens and raises the risk that earlier context will be lost. The cost comes not just from reading code, but from repeatedly reconstructing connections between fragments.
Repository size compounds the problem. Agent4cs notes that industrial codebases are often far larger than typical context-window sizes, so loading everything will not work in general. Call graphs, module boundaries, and impact analysis ask how code is structured, no matter how much text fits into a prompt. When the agent reads flat files, it has to rebuild those structures in the same context that limits how much it can explore.
Why code structure is the right unit of analysis, and what Tree-sitter provides
The useful unit of retrieval is often a function, class, or block. A line window can end halfway through a statement or separate a function from the context that explains it. A syntactic boundary instead preserves a meaningful piece of code. That gives retrieval a coherent starting point.
Tree-sitter makes those boundaries available by parsing source into an abstract syntax tree, or AST. The tree exposes the language’s structure so that a chunking pipeline can work with actual code units. CocoIndex’s Tree-sitter integration follows functions, classes, and blocks across every major language. Tree-sitter Code Summarizer MCP targets functions, methods, classes, interfaces, types, and enums, attaching metadata for downstream embedding. Filename-based language detection lets its pipeline handle a polyglot repository without per-language configuration.
Syntactic boundaries still have to fit an embedding model’s limits. Large AST nodes are recursively processed into their children, while oversized leaf nodes fall back to line-based chunking. Nodes below a minimum size are dropped to keep out noise.
How to turn parsed chunks into a searchable embedding index
Once the chunks are coherent, each can be embedded as a vector and stored with its source metadata. That metadata includes the filename, start and end lines, symbol name, parent context, and language. A natural-language query can then find whole code units along with where they are in the repository. CocoIndex shares the same embedder between indexing and querying, keeping the two paths consistent by construction [1].
Consider a query looking for authentication code. A retrieved function would arrive with its filename, its start and end line range, and its docstring, where present. The filename locates it, the line range bounds it, and the docstring supplies its stated purpose. Its symbol name and parent context further identify what the agent has found.
The embedding and storage choices depend on where the code can be processed. Tree-sitter Code Summarizer MCP uses @xenova/transformers with all-MiniLM-L6-v2 and LanceDB for entirely on-machine embedding, with zero code leaving the machine. Cloud options include OpenAI’s text-embedding-3-small, optimized for efficiency, and text-embedding-3-large, with higher capacity. Cloud embedding batches use concurrency controls and exponential-backoff retry. LanceDB suits offline or privacy-sensitive deployments, while Qdrant is common for production deployments with multiple concurrent agents.
A weighted rerank uses the vector score along with symbol-name matches, file-path signals, and how recent the code is. Optional filters constrain results by file glob, language, or symbol kind without changing the query embedding. Tree-sitter Code Summarizer MCP stores workspace_id, a chunk hash, and created_at with each vector, supporting per-file replacement during re-indexing. These fields make the index both searchable and maintainable.
Keeping the index current as the codebase changes
Commits, saves, and rebases change the repository, while a static index continues to describe its earlier state. An agent reading that index may be reasoning about code that no longer exists. Live updates are therefore what separates an ongoing agent tool from a one-shot documentation generator.
CocoIndex’s filesystem source in live mode re-embeds and re-upserts only chunks whose content changed, so a one-line edit limits work to affected syntactic units. Its memoization mechanism skips a function decorated with memo=True when both the file’s content and the function’s own code are unchanged.
Other implementations track change through different signals. Tree-sitter Code Summarizer MCP records modification time and size in .code-memory-db/index-state.json to identify files needing reprocessing. It then replaces entries per file so stale chunks do not accumulate. Codebase-Memory uses a file watcher and content hashes to maintain its graph incrementally. The pipeline handles changes to embedding models or chunk-size strategies in the same incremental way, recomputing only the rows that those changes affect and keeping the rest.
Production agentic workloads report per-task LLM API costs of several dollars on non-trivial repositories, with input tokens dominating even when caching is used.
Exposing the index as an agent tool via MCP
MCP, the Model Context Protocol, is an open tool-connection standard created at Anthropic that lets LLM agents call tools through compatible orchestrators and IDEs. An index made available through MCP lets an agent use what is stored in it directly. The agent can ask for a specific kind of information without requesting a file dump and inferring everything afterward.
Tree-sitter Code Summarizer MCP exposes eight tools spanning ingestion, navigation, and retrieval. Its tools are index_workspace, semantic_search, clear_index, index_status, find_symbol, get_file_outline, get_file_tree, and open_file_chunk. These interfaces distinguish a semantic lookup from a symbol lookup or a request for a file’s outline. They also give the agent access to index status and the underlying code chunks.
Codebase-Memory exposes 14 structural query tools through MCP, including call-path tracing, impact analysis, and hub detection, with sub-millisecond query latency. A typed answer to one of those questions gives the agent a relationship to reason about. The same index can also back a REST endpoint for Slack slash commands or webhook triggers. Its usefulness need not stop at the IDE.
How hierarchical summarization scales from function to repository level
A searchable function index does not, by itself, explain a whole repository. Similarity search finds code units that match a query, but an account of a module must bring those units together and keep track of how they relate. Hierarchical summarization addresses that gap by following the repository’s own organization. Summaries of functions are used to write summaries of folders, which are then used to write summaries of modules.
Agent4cs proposes a bottom-up multi-agent way to do this work. A summarization agent produces function-level summaries, a keyword-extraction agent identifies critical information from subfolders, and a quality-assurance agent refines outputs for readability, coherence, and completeness. The refinement loop can catch a folder summary that contradicts its child summaries and request a revision. That makes the architecture more than a single prompt applied at several scales. It gives the higher-level account a way to reconcile its parts.
Agent4cs was accepted at the 23rd European Conference on Multi-Agent Systems (EUMAS 2026). Its evaluation on seven frontier models found an average improvement in semantic consistency across all folder levels, with up to 38% gains in normalized keyword coverage on real-world datasets compared with structured prompting baselines. The coverage result needs care because the keyword-extraction agent inserts terms from subfolders into higher-level summaries, partly embedding the signal later measured. The semantic consistency improvement is the more robust finding.
The result supports an architecture pattern. The embedding index answers a request to find code for a task. The hierarchical layer explains what a module does and how it relates to another module. Together, they can provide structured documentation that stays available as well as answers to individual queries.
When graph-based retrieval outperforms vector search, and when it does not
The strongest objection to an embedding-only agent is that proximity is not a typed relationship. Code that calls a function, implements an interface, imports a module, or tests a behavior can all be related without being related in the same way. Embeddings compress those distinctions into similarity. For refactoring and root-cause analysis, however, the distinction may be the point of the question.
Codebase-Memory uses Tree-sitter to build a knowledge graph in SQLite for code in a wide range of languages. It exposes typed structural tools through MCP and deliberately bypasses vector retrieval for exact call-graph queries. That lets retrieval follow code relationships rather than approximate them through semantic closeness. For graph-native questions such as hub detection, caller ranking, and impact analysis, it does as well as or better than the file-exploration agent on most of the languages tested.
Codebase-Memory achieves 83% answer quality, below the file-exploration agent’s higher score, while using fewer tokens and tool calls. The file-exploration agent still does better on questions that need the actual source text.
The practical choice is to route questions according to the evidence they need. Vector search works well for requests to find code that does something, while graph traversal works well for questions about what changing a symbol could break. A mature codebase agent has both and uses each for the queries it handles well. Both can share Tree-sitter as their parsing foundation, with its output consumed as embedding-ready chunks or graph edges. A different retrieval backend does not require a different parser.
Putting the pipeline together as a deployable agent
These stages form an agent only when they can operate across sessions. Parsing supplies coherent units, embeddings make them searchable, and incremental processing maintains them as code changes. Structural tools and hierarchical summaries broaden the questions the system can answer. The persistent index holds that work beyond any single model context. Persistence is what lets the initial indexing cost be amortized across future queries.
The runtime must support the operational work that the parsing and retrieval logic does not handle alone. That includes scheduling re-index runs, managing concurrency during large initial indexing jobs, retrying failed embedding calls with backoff, and surfacing index health to the operator. With automatic updates, each rebuild can start without a human having to trigger it. The maintained index is then ongoing state rather than an artifact left behind by a completed job.
MCP makes that state available through more than one working surface. The same index can be used by an IDE plugin, a Slack slash command, a CI pipeline step, or an orchestrating agent that is reviewing a pull request. An agent runtime built for this work, or agent OS layer, keeps those uses connected to a service that is kept up to date. Its role follows from the architecture rather than sitting outside it as an optional flourish. The developer gains a repo-aware agent designed to stay current, remain queryable, and compose with the rest of the stack.
Notes
- Codebase-Memory: Tree-Sitter-Based Knowledge Graphs
Supplied the knowledge-graph approach, the structural query tools, and the answer quality, token and tool-call comparison with file exploration.
- Agent4cs: A Multi-agent System for Code Summarization in Large Hierarchical Codebases
Provided the bottom-up multi-agent hierarchical summarization design and its evaluation results.


