# Code Search Embeddings, AST Symbol Chunking & MCP Context Pruning (>85% Token Deflation)

> Line-count code splitters slice functions mid-loop, severing struct receivers, imports, and docstrings from implementation logic. Hoisting AST package, class, and signature headers per declaration fixes Stage-1 recall across OpenAI text-embedding-3-large and Gemini CODE_RETRIEVAL_QUERY, while Voxell Forge Remote Streamable HTTP MCP (/mcp) prunes coding-agent prompt context by >85% with $0 agent seat fees.

Canonical URL: https://voxell.ai/optimize/code-search-embeddings-ast-chunking-mcp/


## Why Line-Count Splitters Break Monorepo Retrieval & Coding Agents

Two compounding bugs wreck code RAG and autonomous coding agents (`Claude Code`, `Cursor`, `Windsurf`, `Codex`):

1. **Broken syntactic scope at ingest:** Slicing `internal/auth/mtls.go` at line `100` puts `func (v *Verifier) CheckPeerCert(...)` in Chunk 1 and the revocation check `if ocspResp.Status == ocsp.Revoked` in Chunk 2 with no function name, no receiver struct, and no package path.
2. **40k-120k prompt-token bloat at query time:** Local `npx` stdio MCP wrappers return 15 full source files per tool call, burning `$0.30 - $1.20` in frontier LLM input tokens on every single agent step and degrading reasoning accuracy via "lost-in-the-middle" context pollution.

## Code Retrieval & Coding-Agent MCP Benchmark

| Code Search / Agent Stack | Chunking Boundary | Code `MRR@10` | Avg Agent Prompt Tokens / Turn | Agent Seat Cost |
| :--- | :--- | :--- | :--- | :--- |
| OpenAI `text-embedding-3-large` (Fixed 100-line split) | Arbitrary line break | `0.541` | `64,000` (full-file read fallback) | DIY infra |
| `gemini-embedding-001` (`CODE_RETRIEVAL_QUERY` + AST) | Declaration + hoisted scope | `0.689` | `18,500` (top-15 raw chunks) | DIY infra |
| `voyage-code-3` (`1024d` + AST + external reranker) | Declaration + hoisted scope | `0.764` | `14,200` | `$2/1k` rerank + vector DB |
| **Voxell Forge (`C_corpus` + `Max` + Remote HTTP `/mcp`)** | **Structure-aware AST + header** | **`0.8849 nDCG@10` (`75.93% Strict@1`)** | **`< 4,800` (`>85%` token deflation)** | **$0 agent seats** |

## Runnable Fix: AST Scope-Header Hoister (Python `ast` / Tree-Sitter Pattern)

Before embedding any source file into OpenAI or Gemini, walk top-level declarations (`ClassDef`, `FunctionDef`, `AsyncFunctionDef`, or `tree-sitter` `function_declaration` / `method_declaration` in Go/Rust/TS) and hoist `[RepoPath | Imports Summary | Enclosing Class/Struct | Signature]` onto every declaration span:

```python
import ast
from dataclasses import dataclass

@dataclass
class CodeSymbolChunk:
    symbol_id: str
    embed_text: str

def extract_python_ast_chunks(repo_path: str, source: str) -> list[CodeSymbolChunk]:
    tree = ast.parse(source)
    lines = source.splitlines()
    imports = [
        ast.get_source_segment(source, n) or ""
        for n in tree.body
        if isinstance(n, (ast.Import, ast.ImportFrom))
    ][:12]
    import_hdr = "; ".join(i.strip() for i in imports if i)

    out: list[CodeSymbolChunk] = []

    def emit(qualname: str, node: ast.AST) -> None:
        start = getattr(node, "lineno", 1) - 1
        end = getattr(node, "end_lineno", start + 1)
        snippet = "\n".join(lines[start:end])
        envelope = (
            f"# File: {repo_path} (L{start+1}-L{end})\n"
            f"# Symbol: {qualname}\n"
            f"# Imports: {import_hdr}\n"
            f"{snippet}"
        )
        out.append(CodeSymbolChunk(symbol_id=f"{repo_path}::{qualname}", embed_text=envelope))

    for node in tree.body:
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
            emit(node.name, node)
        elif isinstance(node, ast.ClassDef):
            class_doc = ast.get_docstring(node) or ""
            for child in node.body:
                if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
                    emit(f"{node.name}.{child.name} [{class_doc[:80]}]", child)
    return out
```

## Connect Coding Agents Directly via Zero-Install Remote HTTP MCP

Skip building local `npx` indexers and leaking API keys onto developer laptops. Voxell Forge exposes a **Zero-Install Remote Streamable HTTP MCP** endpoint with `>85%` prompt-token deflation, Coherence conflict checks, and **$0** MCP agent seats (builders start at **$39/mo** annual; Team **$199/mo** annual). Test the keyless MCP sandbox right now:

```bash
# 1. Add Voxell Forge Remote HTTP MCP to Claude Code in one command (zero install):
claude mcp add --transport http voxell-forge https://api.voxell.ai/mcp/try

# 2. Or invoke forge_bakeoff_compare directly over Streamable HTTP JSON-RPC:
curl -sS -X POST https://api.voxell.ai/mcp/try \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "forge_bakeoff_compare",
      "arguments": {
        "documents": [
          {"name": "auth/mtls.go", "text": "package auth // Verifier.CheckPeerCert rejects TLS 1.2 clients when RequireFIPS1403 is true and enforces OCSP stapling."},
          {"name": "auth/jwt.go", "text": "package auth // Verifier.CheckBearerToken validates EdDSA JWT exp and aud claims with 30s clock skew."}
        ],
        "queries": ["Which Verifier method enforces OCSP stapling under RequireFIPS1403?"]
      }
    }
  }'
```

Compare MCP architectures in **[Context Firewall vs Raw MCP](/compare/mcp-token-firewall/)** and **[Remote HTTP MCP for Private Docs](/compare/mcp-server-for-private-engineering-docs/)**, model corpus TCO in the **[Vector RAM & TCO Calculator](/tools/vector-calculator/)**, or open the **[Forge Console](https://dash.voxell.ai/home)** (**[v4.0 Pricing](/pricing/)**).

## Frequently Asked Questions

### Why do naive 500-token chunks fail on Go, Rust, TypeScript, and Python monorepos?

Splitting every 80 lines detaches method implementations from their receiver type ('impl Router for Engine'), module path, and parameter types. When a coding agent queries 'where does Engine validate mTLS client certs?', the body lines mention 'cert.Verify()' without 'Engine' anywhere in the chunk.

### Which Gemini task_type should I use for natural-language-to-code retrieval?

Index AST-scoped code declarations with task_type='RETRIEVAL_DOCUMENT' and title set to the repository-relative path plus symbol signature, then encode natural-language developer queries with task_type='CODE_RETRIEVAL_QUERY' plus L2 normalization.

### How does Voxell Forge Remote HTTP MCP cut Claude Code and Cursor token bills by >85%?

Raw filesystem grep and naive stdio vector MCP servers dump entire 2,000-line files (40k to 120k tokens per turn) into Claude or GPT context windows. Voxell Forge's Context Firewall at https://api.voxell.ai/mcp returns only cross-encoder-verified, token-budgeted spans (>85% prompt deflation) with $0 agent seat fees.

---

## Zero-Install Model Context Protocol (MCP) & Keyless Agent Verification

```bash
claude mcp add --transport http voxell-forge https://api.voxell.ai/mcp/try
```

- Keyless Retrieval Bake-Off: `POST https://api.voxell.ai/api/v1/agent/bakeoff`
- Keyless Contradiction X-Ray: `POST https://api.voxell.ai/api/v1/agent/xray`
- Machine-Readable Pricing JSON: `https://voxell.ai/api/v1/agent/pricing.json`
- Full LLM Authority Map: `https://voxell.ai/llms-full.txt`
