September 12, 2026•7 min read•...

Stopping the AI Token Bleed: How We Built Zero-Token Code Navigation in Rust

RustTree-sitterMCPSoftware ArchitectureDeveloper ToolsAST

Stopping the AI Token Bleed: How We Built Zero-Token Code Navigation in Rust

When developers use autonomous coding agents like Claude Code, Cursor, or Antigravity, they are pairing with an assistant that reads at superhuman speed. But there is a silent bottleneck killing both speed and quality: context window exhaustion.

To answer a simple question about a single 8-line data structure, an AI agent will often read three entire 1,000-line source files into its working memory. In a large project, an agent can burn 100,000 to 300,000 tokens of context across just a few routine prompts.

This is not just expensive—it triggers context dilution. The more irrelevant code an AI ingests, the more its reasoning degrades on the actual task at hand.

To solve this, we designed query_ast_graph, a lightweight Model Context Protocol (MCP) server written in Rust. It replaces full-file reading with surgical AST context pinning, indexing entire codebases in real time to return exact definitions and references in sub-50-token responses.

Tip:Open Source GitHub Repository: Explore the complete Rust codebase, Tree-sitter queries, and MCP server implementation on GitHub: Dahc-Dragyn/query_ast_graph.

Why Traditional Code Retrieval Breaks for AI

When tools attempt to show code structure to an AI, they typically rely on two extreme, flawed approaches:

  1. Dumb Keyword Matching (grep / ripgrep): String matching searches for pure text without understanding program syntax. It cannot distinguish between a struct definition, a commented-out line, a variable name, or a string literal. The agent gets flooded with noisy matches it must parse manually.
  2. Heavyweight Language Servers (LSP): Engines like rust-analyzer or TypeScript’s LSP are built for human interaction inside an IDE. They execute full compilation checks, take 30–60 seconds to boot, and can easily consume 1 to 4 GB of RAM. Running multiple LSPs across polyglot repositories as AI background services quickly overwhelms a development machine.
       AI Agent (MCP Client)
                 │
       JSON-RPC 2.0 over stdio
                 ▼
┌──────────────────────────────────┐
│      query_ast_graph Engine      │
│   (Lock-Free In-Memory Index)    │
└────────────────┬─────────────────┘
                 │
    ┌────────────┴────────────┐
    ▼                         ▼
┌──────────────────┐  ┌──────────────────┐
│ Tree-sitter AST  │  │ Multi-Threaded   │
│ S-Expressions    │  │ Gitignore Walker │
└────────┬─────────┘  └────────┬─────────┘
         │                     │
         ▼                     ▼
┌────────────────────────────────────────┐
│     Surgical Context Pinning           │
│   Bounded Definition + Call Sites      │
│        (< 50 Tokens / < 1ms)           │
└────────────────────────────────────────┘

Architectural Vector Comparison

MetricRegex / GrepTraditional LSP (rust-analyzer)query_ast_graph (Rust MCP)
Parsing EngineFlat text regex (No syntax awareness)Full compilation & type solving pipelineNative Tree-sitter S-Expressions
Context OverheadHigh (Dumps blocks of irrelevant lines)Moderate to High (Emits deep symbol trees)Zero-Token Pinning (< 50 tokens)
Memory FootprintEphemeral process allocations1 GB – 4 GB persistent RAMBounded In-Memory Graph (< 35 MB)
Query LatencyLinear disk traversal per searchSub-second (after 30s+ warm-up)Sub-millisecond $O(1)$ lookup
Polyglot CoverageRaw text across all filesRequires separate daemon per languageUnified (Rust, TS, TSX, Python)
Runtime FootprintExternal shell tool dependencyMulti-gigabyte runtime SDKsStandalone Static Binary (~4 MB)

How query_ast_graph Delivers Surgical Context

Instead of treating code as plain text or spinning up a multi-gigabyte compiler, query_ast_graph uses a streamlined, high-efficiency architecture:

1. Zero-Copy Tree-sitter Parsing

The engine uses Tree-sitter’s C-native ABI to parse code directly into concrete syntax trees. By running compiled S-expression queries against the syntax tree, it instantly isolates:

  • Target Definitions: Exact declaration boundaries for structs, traits, enums, functions, and interfaces.
  • Call Sites & Type Usages: Line-level records of where that symbol is instantiated or called across other files.

To guarantee that a massive class or struct cannot overwhelm the AI's memory, definitions are capped to an operational boundary of 10 lines max, delivering immediate clarity without noise.

2. Lock-Free In-Memory Graph (DashMap)

During initial startup or on-demand re-indexing, a multi-threaded crawler scans the workspace while respecting .gitignore rules. Rather than locking the whole index behind a single global mutex during updates, the symbol store uses fine-grained concurrent sharding via DashMap.

Worker threads insert definitions and references simultaneously without thread contention, allowing a multi-thousand-file workspace to build an index in under 200 milliseconds.

3. Atomic Workspace Swapping

When an AI agent shifts focus between workspaces, it passes an updated workspace path via the MCP interface. The server triggers a background scan of the new directory and swaps an atomic reference pointer to the new graph without restarting the process or dropping open JSON-RPC pipes.


The Token Economics: 99.4% Context Reduction

To understand why this architecture changes AI performance, consider an agent seeking context on a common data structure in a mid-sized codebase:

  • Traditional Naive Ingestion: The agent reads the 450-line definition file plus four 450-line files where the symbol is referenced. At roughly 7.5 tokens per line, that single question consumes ~16,875 prompt tokens.
  • AST Context Pinning: The agent queries query_ast_graph and receives the 10-line bounded definition and four exact invocation references (file and line number). Total consumption: ~87 tokens.

This represents a ~99.5% reduction in prompt token consumption. The agent spends less time waiting on API data transfer, cuts API operating costs drastically, and retains its full reasoning context for generating clean code.


Frequently Asked Questions (FAQ)

Why use Tree-sitter S-expressions instead of compiler frontends?

Compilers like rustc or tsc require complete build configurations, resolved dependencies, and strict type checking before they can parse a project. Tree-sitter uses incremental, error-tolerant parsers that extract syntactic meaning from raw files in microseconds, even if the code is currently broken or mid-refactor.

How does this integrate into an AI coding assistant?

It speaks standard Model Context Protocol (MCP) over standard input/output (stdio). Adding the compiled binary to your configuration file (like mcp_config.json in Cursor, Claude Code, or Antigravity) gives the assistant access to the query_ast_graph tool automatically.

Does it waste memory indexing build artifacts like node_modules or target?

No. The scanner embeds native .gitignore parsing. Temporary build outputs, lock files, dependency directories, and hidden files are filtered before they ever reach the parser.


Support our open-source tools and infrastructure: Support AIYoda on Ko-fi

Thanks for reading! Support our development efforts.
Support AIYoda on Ko-fi