Skip to content

Code intelligence · MCP

ContextBrain

Structural code intelligence for AI coding agents. Every repository is parsed into syntax trees, every reference is resolved to the symbol it really points at, and Claude Code asks structural questions over MCP: what breaks if I change this, what calls this, which table does this write to, each answer cited to file and line.

Overview

ContextBrain is a multi-tenant code intelligence platform that gives Claude Code a resolved, typed model of a codebase. Coding agents normally rebuild their understanding of a repository every session through grep, file reads and guesswork, which costs tokens and misses anything that is not a literal text match. ContextBrain parses each repository into syntax trees, resolves every reference to the symbol it actually points at, and stores the result as a heterogeneous knowledge graph of code and database structure in PostgreSQL with pgvector. An MCP server lets the agent ask structural questions directly, and every answer comes with file and line citations.

What resolution changes

A chunk-and-embed system knows that two files mention User. ContextBrain knows that User in one file and App\Models\User in another are the same class, that it extends Authenticatable, maps to the users table, and is called from 14 specific sites. That difference, resolution instead of text similarity, is the whole point of the system.

Beyond code

The same platform also indexes routes, schema, tickets, docs and design files, and connects to GitHub, Jira, Figma, Slack and Sentry, so assistants and teammates recall one shared context. This page focuses on the code-intelligence core.

Honest measurement

An efficiency benchmark showed that the first MCP integration cost more than using no MCP at all, and that result was reported as it was, then fixed. An internal audit also found a security issue in the graph-query path, which was fixed before shipping.

26concrete edge types in the graph
103 s → 41 sfull rebuild on a production Laravel app
50–200×faster no-op re-sync than a rebuild
5×less context than reading the same files
−67%tool-description size (17 KB to 5.8 KB)
−4%tokens vs no MCP overall, −21% on hub queries

Architecture

Repositories are parsed once per file, references are resolved by per-language cascades, and the result is a graph in PostgreSQL with embeddings beside it. An MCP server turns that graph into cited context packs, and four short skill files tell Claude Code when to reach for it instead of grep.

ContextBrain: repositories are parsed, resolved into a graph in PostgreSQL with pgvector, and served to Claude Code over MCP as cited context packs fallbacks to text search Repositories PHP · TS · Pythonper tenant Parse tree-sitter · WASMone tree per file Resolve per-language cascadesprovenance tags Graph store PostgreSQL · pgvector26 edge types MCP server search · resolveimpact · trace_path Claude Code + 4 skill files Context pack citation validator · containment deduptoken-budget ranking, dropped counters Call log mcp_call_log5-reason taxonomy
From repository to cited answer. The dashed line is the fallback log that shows which questions the graph could not answer.

Parsing

tree-sitter via WASM

Language-specific grammars and resolvers for Python, TypeScript and PHP. PHP uses the php_only grammar, since templates add parse noise and no symbols.

ERROR-ratio tripwire

The share of ERROR nodes in each tree is watched. Over the threshold, the file falls back to the full grammar, so a mixed PHP and HTML file degrades gracefully instead of silently losing edges.

One parse, every visitor

The original pipeline ran eight parse arms that each re-parsed every file. It is now one visitor pipeline per file, with tree.delete() freeing WASM memory before the next. Full rebuilds fell 60% and a second repository improved 41%, with exact edge-count parity across all 26 edge types before the old pipeline was retired.

Incremental indexing

A content hash per module chunk is the canary. Unchanged files are skipped, so a no-op re-sync runs 50 to 200 times faster than a rebuild and the graph keeps up with active repositories.

Symbol resolution

Resolution is the core, and each language has its own cascade.

LanguageHow names are resolvedSafeguard
PHPA shared FQN cascade used by every visitor: per-file use-map aliases, namespace prefixing for relative names, absolute names passed through. Laravel-aware visitors model runtime behaviour statically: inheritance, class references, Eloquent relations (including string-form), service-provider bindings so interfaces resolve to implementations, facade aliases from config, and routes to controller actions.Route resolution reaches 76 to 78%
PythonA bare name resolves only when a same-directory file has that name and it is not a standard-library module. The standard library always wins. Resolved edges carry a same_dir_bare provenance tag.stdlib_shadowed caught a local file shadowing Python’s secrets module, a real security hazard
TypeScriptHandles compound file extensions, tsconfig path aliases with longest-prefix matching, and monorepo workspace packages. Built by sweeping two real repositories first.tsconfig_extends_ignored flags configs it does not yet merge, instead of resolving them wrong

Sweep, predict, reconcile, provenance

  1. 01
    Sweep

    Before any change, grep and SQL floor counts establish how many edges the change should produce.

  2. 02
    Predict

    The expected edge count is written down before the code is.

  3. 03
    Reconcile

    The actual count is compared with the prediction. The TypeScript resolver predicted +121 edges and produced +123. The Python resolver matched once a measurement artifact was traced.

  4. 04
    Provenance

    Resolved edges carry tags recording which rule produced them, so graph quality is an auditable number and silent failures, the dangerous kind, get caught.

Graph model

Twenty-six concrete edge types are exposed to the agent as eight directional families. Edges are stored in one direction only, and finer detail such as call type, read versus write and resolution confidence lives in edge properties instead of new types. Candidates such as RE_EXPORTS, OVERRIDES and DECORATES wait until the call log shows traversals that miss without them.

ContextBrain graph example: controller calls a service, which queries a model that extends a base class, maps to a table, which a second table references CALLS QUERIES EXTENDS MAPS_TO FOREIGN_KEY UserController ::store UserService ::create App\Models\User resolved FQN Authenticatable users table orders table
One path through the graph: a controller, the service it calls, the model that service queries, and the tables behind it.

Code structure

DEFINES · IMPORTS · CALLS · EXTENDS · IMPLEMENTS

Code to database

MAPS_TO (model to table) · QUERIES (code to data access) · FOREIGN_KEY (table to table)

Serving layer

MCP toolWhat it does
search_codebaseFind code by meaning with pgvector when the symbol name is unknown, then switch to the graph once it is known.
resolve_entityTurn a name into the one symbol it really refers to, with its definition and relations.
get_impact_analysisFollow edges outward from a symbol to show what a change would affect.
trace_pathN-hop traversal that returns the chunk content along the path, measured at 5x compression against reading the files.

Context packs

Citation validator

Every file and line reference in a response is checked against real code.

Containment dedup

When one returned chunk sits inside another, the more specific one wins.

Budgeted ranking

Results fit a token budget, with separate dropped_for_budget and dropped_for_dedup counters so it is always clear why something is missing.

Fallback log

Every fall-back from graph or semantic retrieval to plain text search is written to mcp_call_log (JSONB) with a five-reason taxonomy. It is the real-usage signal for what to build next.

Four skill files (exploring, tracing, editing and querying), each under 300 words, live in .contextbrain/skills/ and are wired into CLAUDE.md.

Token efficiency, measured

The finding

Registering the MCP server added about 50 KB of tool schema to every session. Whenever the tools were not called, sessions cost 36 to 96% more than with no MCP.

Fix 1: metadata by default

include_content defaults to false on impact analysis, search, trace and resolve. Content is fetched only when needed.

Fix 2: smaller schema

Tool descriptions shrank from 17 KB to 5.8 KB, a 67% cut.

The result

Measured on a 200K-line Laravel application against a no-MCP baseline: 4% fewer tokens overall and 21% fewer on hub-detection queries. Tool schema is a fixed cost paid every session, and it has to earn its place.

Multi-tenancy and stack

Organisations and repositories are indexed in isolation on one shared platform, so ContextBrain serves an engineering organisation rather than one developer’s machine.

TypeScriptPythontree-sitter (WASM)PostgreSQLpgvectorJSONB call loggingMCPClaude Code skills