Zero Labs
Industry News / AI

I Built an AST-Powered Code MCP That Saves 70% Tokens — Here’s How It Works

Source · Towards AI By Cocoindex

From the publisher’s feed, collected in the ZeroLabs newsroom.

Inside CocoIndex Code: an open-source, AST-based Model Context Protocol server that makes coding agents faster, cheaper, and actually aware of your codebase.Last week, a one-line tweet about my open-source project CocoIndex Code quietly exploded on X, crossing 54K+ views and getting bookmarked dozens of times by engineers building with AI agents. The line was simple: “CocoIndex Code gives your coding agent a brain” — and it resonated because it captured a pain almost every developer has felt when working with AI coding tools.benchmarkEvery time a coding agent needs context, it typically slurps in entire files: imports, comments, boilerplate, and half the standard library if you’re unlucky. You pay for all of that in tokens and latency, even though the model usually needs just a few functions or one class to do its job.CocoIndex Code grew out of a simple question: what if agents could see code the way compilers and IDEs do, as structured syntax trees rather than raw text chunks? That question led to an AST-based MCP server that now powers semantic, incremental, and local-first code search with significant token savings in real-world tasks.Why Naive Context Wastes TokensMost code-aware tools today still do “RAG, but for code”: scan your repo, chunk files every N characters or lines, embed each chunk, and run vector search. This works, but it has two fundamental problems.First, naive chunking ignores semantics. A 500-character window happily slices through the middle of a function, glues unrelated methods together, or grabs half of a class plus some random comments. The embedding model receives a noisy mixture of signals, and search results are mediocre.Second, the agent still has to consume everything you feed it. If you retrieve multiple overlapping chunks around the same function, you pay for redundant context. On large codebases, that can mean thousands of wasted tokens per task, plus slower responses as the model digests a bloated prompt.In practice, this looks like: 1.8K+ tokens of code context for a single security audit task, 50+ seconds of wall-clock time, and follow-up questions because the agent still missed the relevant function. With CocoIndex Code’s AST-aware retrieval, the same task completed in about 34 seconds with ~650 tokens, and the agent got everything it needed in a single pass.What CocoIndex Code Actually IsCocoIndex Code is an embedded Model Context Protocol (MCP) server designed to plug directly into coding agents like Claude Code, Cursor, Codex, and any other MCP-compatible client. Instead of streaming raw files, it exposes a semantic search tool that returns precise, AST-aligned code snippets with file paths, languages, line ranges, and similarity scores.A few design constraints shaped the project from day one. Local-first by default: use local embedding models wherever possible, no API keys required to get started, no code leaves the developer’s machine. Zero infrastructure overhead: no external databases, no vector SaaS, everything lives inside a small directory in your project root. One-line integration for agents: install once, add the MCP server to your tooling, and immediately get semantic code search.Today, setup looks like this:pipx install cocoindex-codeclaude mcp add cocoindex-code -- cocoindex-codeAfter that, your coding agent can call a single MCP tool to search your codebase by natural language or example snippet.Architecture at a GlanceUnder the hood, CocoIndex Code is built on top of CocoIndex, a Rust-based data transformation engine optimized for incremental indexing and streaming workloads. The MCP server orchestrates four main layers: AST parsing, embedding, vector search, and incremental indexing.1. AST Parsing with Tree-sitterThe first layer is a Tree-sitter-based parser that turns source files into rich syntax trees. Tree-sitter is the same technology used by modern editors like Neovim and Zed for fast, incremental syntax highlighting and code analysis.For each supported language, CocoIndex Code loads the corresponding Tree-sitter grammar and walks the parsed tree to extract semantic units: function definitions, class declarations, method bodies, and other language-specific constructs. Each node becomes a chunk with its file path, programming language, line range, and raw code content.On a 200-line file, this might produce 8 to 12 coherent chunks rather than arbitrary sliding windows. Because the boundaries align with actual code structure, you never embed half a function or two unrelated methods stuck together. CocoIndex Code currently supports more than 25 languages via Tree-sitter, including Python, TypeScript, Rust, Go, Java, C/C++, Kotlin, and Swift.2. Embedding and Vector SearchOnce the AST chunks are generated, CocoIndex Code embeds each chunk into a vector space. The default setup uses a local SentenceTransformers model (such as all-MiniLM-L6-v2), which runs entirely on the developer’s machine, eliminating external calls, rate limits, and data exposure.For teams that need stronger code-specific embeddings, CocoIndex Code integrates with models like nomic-ai/CodeRankEmbed or other code-focused models, and it can also route to 100+ providers via LiteLLM, including OpenAI, Gemini, Voyage, Cohere, and local backends like Ollama.Vectors are stored in an embedded SQLite database using the sqlite-vec extension for similarity search. No Postgres, no Pinecone, no external services. Everything lives in a .cocoindex_code/ directory in your project root.3. Incremental Indexing via the CocoIndex EngineParsing and embedding an entire monorepo once is fine. Doing it on every file save is not. This is where the underlying CocoIndex engine matters. CocoIndex tracks file system changes and only re-indexes files that actually changed, turning a potentially expensive operation into a cheap incremental update.On a large codebase, the initial index typically takes on the order of tens of seconds. After that, steady-state updates are near-instantaneous because unchanged files are skipped, only new or modified files go through parsing and embedding, and the vector index updates in place.The MCP server exposes a single search tool with parameters like query (natural language or a code snippet), limit and offset for pagination, and a refresh flag to trigger an index refresh before searching. The response includes file path, language, exact line range, code content, and a similarity score.4. MCP Server IntegrationBecause CocoIndex Code is implemented as an MCP server, it integrates naturally with any MCP-aware tool. Claude Code and other IDE agents can call it as a custom tool. CLI-based agents and orchestrators can wrap it as a semantic code retrieval step. Editors like Cursor or Windsurf can route queries like “find the function that validates JWTs” directly to the MCP server instead of grepping the repo.The ergonomic win is that developers don’t have to manage yet another service, API key, or infrastructure component. They just add the MCP server and immediately get semantic code retrieval that understands their repo structure.Why AST-First Chunking Beats Naive ChunkingConsider a typical Python file with several utility functions, a couple of classes, and a long commented configuration block. A naive chunker that slices every 500 characters might cut the main function in half, group two unrelated classes into one chunk, or mix configuration constants with business logic.The embedding model sees a noisy, inconsistent sample of the file. When you search for “OAuth token validation,” the top results may include half the validation function, plus unrelated code that happens to share a few tokens.With AST-based chunking, each chunk corresponds to a complete semantic unit. A function is always embedded as a whole. A class is treated as a coherent concept. Helper methods stay grouped with the containing class. The embeddings become sharper because each vector represents a meaningful, self-contained piece of code.In real use, this translates into fewer, more precise chunks retrieved, less redundant or irrelevant context, and lower token usage with faster agent responses.Practical Outcomes and Use CasesBecause the entire stack is open source and local-first, CocoIndex Code fits naturally into a range of workflows: coding agents (Claude Code, Cursor-like tools) that need high-quality code retrieval, automated code reviews and migration agents navigating large monorepos, and SRE and infra agents searching across IaC, deployment scripts, and configuration files.Some concrete benefits teams are seeing: immediate token savings because AST-aligned chunks reduce repeated and irrelevant context; faster iteration loops with less time waiting on long completions; and easier adoption with no database to provision and no external services to configure.The core engine (CocoIndex) and CocoIndex Code MCP server are both open source under Apache 2.0, which makes it straightforward to extend, self-host, or integrate into internal platforms.How to Try It TodayIf you want to experiment with AST-based retrieval in your own stack, you can get started in a couple of minutes. Install CocoIndex Code, add the MCP server to your coding agent, and open a project. Ask your agent questions like: “Find the function that parses user JWTs,” “Show me where we validate payment webhooks,” or “Locate the class that wraps the Postgres connection.”Behind the scenes, the MCP server will incrementally index your repo with Tree-sitter, embed AST chunks with a local model, store vectors in SQLite, and return the most relevant code snippets with paths and line numbers.You can explore the source code and documentation on GitHub: https://github.com/cocoindex-io/cocoindex-codeI Built an AST-Powered Code MCP That Saves 70% Tokens — Here’s How It Works was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.