Skip to content

CodeGraph: A Statically Derived Code and Schema Graph of Laravel Applications as a Local MCP Server

CodeGraph: A Statically Derived Code and Schema Graph of Laravel Applications as a Local MCP Server

In this article I describe CodeGraph, a macOS menu-bar application and local Model Context Protocol (MCP) server that I developed to build a typed graph of the source code and database schema of my Laravel applications. I derive the graph purely by static analysis of the origin/<branch> commit: PHP is parsed with tree-sitter, Blade templates with my own scanner, and the database schema is reconstructed by replaying migrations. No PHP runtime, Docker container or live database is required. The result is stored in one SQLite file per repository and exposed to an AI assistant (Claude Desktop or Claude Code) through 14 tools.

Every edge carries a source location (file:line) and one of three confidence levels (exact, inferred, candidate), so the consumer can distinguish syntactic facts from heuristics. On the six repositories I had configured on 21 November 2026, the graphs hold between 624 and 25,225 nodes, are built in 0.3 to 2.7 seconds, and resolve 78 to 89 % of call sites to a concrete method. In my daily work the tool reduces the localisation of a defect from a stack trace or a customer's ticket text to a small number of bounded tool calls that return the screen, route, handler, validation rules, models and tables involved.

1 Introduction

In a Laravel application the path from a symptom to its cause crosses several artefact types that the language itself does not connect. A URL is bound to a controller or Livewire component in a route file; the component renders a Blade view by name; the view binds to component methods through wire: attributes; the method validates input, calls Eloquent models, and the models map by convention to tables defined incrementally across many migrations. Most of these links are strings resolved at run time, so neither a text search nor a language server follows the whole chain.

I met the same difficulty when working with an AI coding assistant. Without a structural index the assistant must discover the chain by reading files and issuing text searches, which consumes its context window and gives no indication of how reliable each inferred link is.

I built CodeGraph to compute these links once, in advance, and to store them as a queryable graph. My original goal, recorded in my design specification of 16 October 2026, was narrow: I or a helpdesk colleague paste a stack trace or the text of a customer ticket into Claude, and the assistant locates the affected screen, route, component, validation, models, tables and translation texts. I have since generalised the project from one repository to any number of Laravel repositories, each tracked on its own branch.

I describe the system as implemented after 192 commits (16 October to 21 November 2026): about 17,900 lines of Swift in the sources and 13,700 lines in the tests. All quantitative statements are taken from my source code, my design documents in docs/superpowers/specs, or the status output of the running server.

2 System architecture

I ship CodeGraph as a single executable with two modes. Started without arguments it is a SwiftUI menu-bar application; started with --mcp it is a stdio MCP server that Claude launches itself. In MCP mode the standard output carries protocol messages only.

CodeGraph architecture: git clone and vendor cache feed the indexer, which writes graph.sqlite read by the MCP server

The graph file is the only interface between the build side and the query side; no network port is opened.

I divided the Swift package into three targets:

Target

Responsibility

External dependencies

CodeGraphCore

Git access, PHP and Blade analysis, migration replay, graph store, queries, vendor download, build coordination

swift-tree-sitter 0.25.0, tree-sitter-php 0.25.1, system SQLite

CodeGraphMCP

Server factory, tool definitions, tool runner with the response size guard

MCP Swift SDK 0.12.1

CodeGraph

Executable: menu, settings window, credential and package sheets

AppKit, SwiftUI

2.1 Source of truth

I build the graph from refs/remotes/origin/<branch>, never from the working directory or a local branch. Files are read as git blobs, so checking out another branch does not change the graph, and the indexer never modifies the checkout. The only write to the repository is git fetch --no-tags --quiet origin <branch>, executed at most once every five minutes with GIT_TERMINAL_PROMPT=0 and SSH BatchMode=yes. A watcher on the remote ref and packed-refs (FSEvents, 2 s debounce) also catches a manual fetch.

2.2 Build and consistency

A rebuild starts when the SHA of the tracked branch differs from the SHA recorded in the graph, or when the fingerprint of the vendor cache changes. I write each build to a temporary file and move it over graph.sqlite with an atomic rename, so a failed build leaves the previous graph valid. A read that collides with the rename is retried once on a new connection. Builds and fetches are serialised across processes with flock on separate lock files, which lets the MCP process keep the graph current even when the menu-bar application is not running.

2.3 Vendor declarations

A Laravel repository does not contain vendor/, yet most calls in application code go into the framework. I therefore download each production package named in composer.lock as a zip distribution, extract only its declarations (classes, inheritance, method signatures, return types, and the docblock tags @mixin, @method, @property, @return), and cache the result under name@reference. Method bodies of vendor code are not indexed. Credentials are read from ~/.composer/auth.json or from the macOS Keychain and never appear in logs, status files or tool responses. A failed download does not fail the build; the graph is built with what the cache holds and rebuilt when more packages arrive.

3 Graph model and extraction

The graph is a directed, typed multigraph. A node has a key, a kind, a name, an optional file with a line range, and string attributes. An edge has a source, a destination, a kind, a confidence, and an optional file:line. I store both in two SQLite tables indexed by (src, kind) and (dst, kind), with an FTS5 table (tokenizer unicode61, diacritics removed) for full-text search.

3.1 Indexed sources

From the tracked commit I index app/, packages/*/src, routes/, resources/views/, lang/<locale>/*.php, the migrations of the application and of local packages, the service providers, _ide_helper.php, .phpstorm.meta.php and the composer.json files. Tests and vendor/ are excluded.

3.2 Nodes

Group

Node kinds

Origin

Code structure

file, class, trait, interface, enum, method, property

tree-sitter PHP; a class also receives a role (Model, Controller, Livewire, ...)

Web layer

route, view, translation key, validation field

route files, Blade templates, lang/ arrays, rules() and validate()

Database

table, column, index, foreign key, migration

replay of migrations

Runtime texts

message

literal text of throw, abort, Log::*, flash, toast and validation messages; dynamic parts become …

Events

event

Livewire event names, where dispatch sites and listeners meet

Dependencies

package

composer.lock

Route closures are represented as method nodes (method:{closure}@<file>:<line>), and their bodies are analysed like any method.

3.3 Edges

The model defines 23 edge kinds:

Group

Edge kinds

Meaning

Structure

DEFINES, EXTENDS, IMPLEMENTS, USES_TRAIT

file → class → member; inheritance

Request path

ROUTES_TO, RENDERS, INCLUDES, WIRES

route → handler → view → sub-view; view → Livewire method or property

Texts and input

USES_TRANSLATION, VALIDATES, EMITS

method or view → translation key; rules → field; method → message

Data

MODEL_TABLE, RELATION, FK, ALTERS

model → table; model → model; column → column; migration → table

Calls

CALLS, REFERENCES, UNRESOLVED_CALL

method → method; method → class; method → an unresolved name

Container

BINDS, FACADE_OF

abstract → concrete class; facade → concrete class

Events

DISPATCHES, LISTENS, OBSERVES

dispatch site → event, job, notification or mailable; event → handler; observer → model

3.4 Confidence

I do not run a full type inference in the manner of PHPStan. Instead, every edge states how it was obtained:

Level

Obtained from

Example

exact

the syntax of the source

self::m(), $this->m(), X::m(), new X

inferred

a type: parameter and return type hints, typed properties, docblocks, container bindings, facades, Eloquent relations, inheritance, @mixin and magic forwarding

$user->orders()->first()

candidate

a name match only

an untyped receiver whose method name exists in at most 3 repository classes

A call that cannot be attributed becomes an UNRESOLVED_CALL, which is always candidate. A call into vendor code is never marked exact when it is reached through a magic method. Vendor classes serve only to resolve types: they are excluded from full-text search and from the candidate search, so common names such as get or find do not flood the results.

3.5 Build phases

The indexer processes one commit in 13 ordered phases:

  1. File selection

  2. Reading blobs through git

  3. Declarations (classes, methods, properties)

  4. Symbol table and container maps (bindings, facades)

  5. Eloquent models and relations

  6. Method bodies (calls, references, messages, dispatches)

  7. Routes, including Route::resource expansion and group prefixes

  8. Views and Blade (@include, components, wire: bindings)

  9. Listeners, property hooks and observers

  10. Translations

  11. Migrations

  12. Validations

  13. Composer packages

The order is significant: phase 9 runs after bodies and views, so that every dispatch site is known before listeners are attached.

3.6 Schema from migrations

I derive the database schema by replaying the up() bodies of all migrations in file-name order: Schema::create, Schema::table, drops and renames. Raw SQL passes through a small DDL parser. When a condition cannot be decided statically, all branches are replayed and the affected columns are marked conditional. A statement that is not recognised marks the table as possibly incomplete instead of being ignored silently.

3.7 Warnings as part of the result

Every place where the static analysis gives up is recorded as a typed warning with file:line: an unresolved view name, a wire: target that does not exist, a dynamic route name, a missing translation, an event name that is not a literal. The warnings are stored in the graph and are queryable, so an incomplete region of the graph is visible to the consumer.

4 Query interface

The MCP server exposes 14 tools. All tools except rebuild are read-only, and every tool except list_repos takes the repository name, so the data of different repositories are never mixed.

Tool

Input

Result

list_repos

none

configured repositories with branch, state, branch SHA and graph SHA

status

repo

build time, node and edge counts, call-site classification, vendor package state, warnings

analyze_stacktrace

pasted trace or log

exception, message, SQLSTATE with table and column, frames mapped to methods, views, routes and packages, matching throw sites

find_by_text

text seen on screen

full-text hits resolved to screens: view → component or controller → route

outline

class or file

inheritance, properties, methods with signatures, routes, views, relations, usage counts

node

key or short name

attributes and edges grouped by kind

neighbors

key, depth 1–3

the surrounding subgraph, ordered by depth and confidence

path

two keys

up to 3 shortest paths, strongest first (bidirectional BFS, depth ≤ 8)

table

table name

columns, types, indexes, foreign keys, migrations, models

route

URI or name

handler, middleware, view, validation

source

path, line range

an excerpt of the file at the tracked commit, at most 300 lines

packages

optional filter

Composer packages with locked version and constraint

warnings

kind, file

places where the graph is incomplete

rebuild

repo

schedules a fetch and a new build

4.1 Stack trace analysis

analyze_stacktrace accepts a Laravel log line, an Ignition copy or bare path:line pairs. Frames in my own code are mapped to method nodes, including route closures. A frame in a compiled Blade file is mapped back to its template; a vendor frame is mapped to its Composer package with the locked version, and the first vendor frame called from my code is marked as the entry. If the line number lies outside the method range at the tracked commit, the frame is flagged as not matching, which indicates that the trace comes from another version. Independently of line numbers, throw sites are found by matching the static text of the exception message (at least 8 characters).

4.2 Bounded responses

Each response occupies the context window of the assistant. On repository R3 (about 11,200 nodes) I measured that a neighbors call at depth 2 returned 149,690 characters, roughly 37,000 tokens, of which the edges alone accounted for 91,000 characters. I therefore introduced a budget of 32,000 characters for node and neighbors and a hard limit of 64,000 characters for every tool.

Edges are returned in a fixed order: depth first, then exact before inferred before candidate, then my own code before vendor code. The response therefore never drops an exact edge in favour of a candidate. Whatever does not fit is reported in an omitted field with counts per edge kind and an offset for the next page. In addition, the default confidence (exact) and a file equal to the file of the source node are left out of the encoding.

4.3 Name resolution

A key may be given as a short class name, Class::method, a table, a view, a route name or a bare method name. An ambiguous name returns a structured list of at most 10 candidates, and an unknown name returns up to 5 full-text suggestions. On R3, 117 of 826 method names occur in more than one class, so this case is common.

5 How the tool helps me as a developer

5.1 Measured state of the graphs

I use CodeGraph on six Laravel repositories. Their names are pseudonymised as R1 to R6, ordered by graph size. The table gives the size and build time of each graph as reported by the status tool on 21 November 2026.

Repository

Nodes

Edges

Build time (s)

Vendor packages cached

R1

25,225

78,389

2.66

137

R2

19,739

47,755

2.61

177

R3

11,232

27,079

1.21

145 (+1 local)

R4

8,832

21,006

0.84

104

R5

4,474

9,325

0.61

120

R6

624

474

0.28

97

The build time covers the indexing of one commit with vendor declarations already in the cache. No repository reported a parse error.

Share of call sites resolved to a concrete method in six repositories (78 to 89 %)

The unit is the call site (one call expression), classified by its best edge. Before I added vendor declarations, a call on a known type whose method belonged to a vendor class produced no edge at all, and a chain such as User::where()->orderBy()->first() was lost after the first call. These calls now form the framework share.

5.2 Effects on my work

  • Defect localisation from a stack trace. I paste the trace; one call returns the exception, the affected table and column from SQLSTATE, the method of each frame, and the screens and routes that reach it. I no longer open the files frame by frame.

  • Localisation from a customer's wording. A ticket usually quotes text from the screen. Full-text search over translation values, views, routes, validation fields and literal messages, with diacritics ignored, maps the quoted text to the view, its component or controller, and the route.

  • Impact analysis before a change. Incoming edges of a method, a column or an event show what depends on it. The path tool answers how a route reaches a table, and reports the weakest confidence along the path.

  • Schema knowledge without a database. The table tool returns columns, indexes, foreign keys and the migrations that produced them, derived from the migrations of the tracked commit.

  • No runtime environment. The analysis needs neither PHP, Docker nor a database, so it also works for a colleague who only has a clone. Because the source is origin/<branch>, the answers describe the shared code and not my uncommitted working directory.

  • Graded trust. An exact edge is a syntactic fact. For a candidate edge the server instructs the assistant to verify the behaviour with the source tool. This reduces the risk that a heuristic link is presented to me as certain.

  • Economy of context. The budget of 32,000 characters and the paging mechanism keep a structural answer to about 8,000 tokens, where the unbounded response reached 37,000.

  • Currency without effort. The graph follows the remote branch automatically, and a rebuild takes under three seconds on my largest repository.

5.3 Verification

I test the system on three levels: roughly 700 unit and integration test functions over a small Laravel-like fixture repository, end-to-end tests that start the built binary in MCP mode, and golden tests against R3. The golden tests check, among others, the chain from a route to its Livewire component, a real stack trace, a Slovak full-text query, and that no own-code edge is lost when vendor declarations are added. They also assert that a full build finishes within 30 seconds.

6 Limitations and threats to validity

  • No precise type inference. I do not use PHPStan or Larastan. Dynamic calls and unclear types end as candidate edges or UNRESOLVED_CALL; between 11 and 22 % of call sites in my repositories are in these two groups.

  • Call-site coverage has a blind spot. The total counts only call sites with at least one edge. A call on a known but incompletely declared type that lacks the method receives no edge and is not counted, so the resolved share is an upper estimate.

  • Blade is scanned, not parsed. My scanner is not an HTML grammar; unusual constructs can escape it.

  • The schema is a reconstruction. A schema replayed from migrations need not equal the live database. Raw SQL is parsed only partly; R2 reports 10 unrecognised statements and 75 undecidable migration conditions.

  • Dynamic names are invisible. Route names, middleware, view names and event names that are computed at run time are reported as warnings and are missing from the graph. R2 reports 90 warnings of this kind for routes.

  • Container maps depend on helper files. Facade and binding maps rely on _ide_helper.php and .phpstorm.meta.php; when these are older than composer.lock, the status reports ide_helper_stale.

  • Scope. The tool supports Laravel applications, the remote origin, macOS 14 or newer and Apple Silicon. It has no connection to Sentry or to a live database.

  • Evidence. The figures in this article describe six repositories of one author. I have not measured the time saved per ticket, nor compared the assistant's accuracy with and without the graph; the benefits in section 5.2 follow from the mechanism and from my own use, not from a controlled experiment.

  • Untested deployment condition. Whether the background fetch works under a colleague's SSH configuration has not been verified; if it does not, the graph is updated only after a manual git fetch.

7 Conclusion

I have shown that the implicit, string-based links of a Laravel application can be recovered statically, without executing the application, and stored as a graph that an AI assistant queries through a small set of bounded tools. Three design decisions carry the result: the graph is a deterministic function of the remote commit and the locked package versions; every edge declares its confidence and source location; and every place where the analysis fails is recorded as a warning. With these properties the graph resolves 78 to 89 % of call sites in my six repositories and is rebuilt in under three seconds.

For my work the practical consequence is that a stack trace or a sentence from a customer is translated into the screen, route, handler, models and tables in a few tool calls, with an explicit indication of what is certain and what must be verified in the source. The next step I consider necessary is a controlled measurement of this effect on real helpdesk tickets.

I use Google Analytics to see which articles people read. It sets cookies only if you allow it. Privacy policy