This page looks best with JavaScript enabled

CodeGraph: Helping AI Coding Assistants Understand the Codebase

 ·  โ˜• 9 min read

1. What CodeGraph Is

CodeGraph is a local-first code intelligence tool. It parses a codebase with tree-sitter, stores symbols, relationships, and files in a local SQLite database, and exposes them as a queryable knowledge graph through MCP, a CLI, and a TypeScript API.

Put simply, it turns “grep, glob, and Read all over the code” into an index built ahead of time, so an AI assistant can answer structural questions with just a few queries.

The project has been published to npm as @colbymchenry/codegraph, and supports mainstream AI coding tools including Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, and Gemini CLI.

2. Why You Need It

When an AI coding assistant explores an unfamiliar codebase, most of its time goes into discovery: find the files first, then read them, then piece together the call relationships. That process generates a large number of grep / glob / Read calls, burns tokens, and slows down responses.

CodeGraph’s approach is this: the structure is already built before the agent asks. Symbol relationships, call graphs, inheritance chains, route bindings, and the like all live in the index, and queries run at sub-millisecond speed.

Without CodeGraph, the agent has to “sweep the files” itself; with CodeGraph, the agent goes straight to “querying the graph.”

3. Comparison: With and Without CodeGraph

3.1 The Same Question, Two Paths

Suppose you ask the agent: “How does a request reach the database?”

Without CodeGraph:

Question โ†’ grep for keywords โ†’ glob for directories โ†’ Read multiple files
     โ†’ grep again for call relationships โ†’ Read again โ†’ maybe spawn a sub-agent to keep sweeping
     โ†’ piece together an answer (10โ€“20+ tool calls, a large number of tokens)

With CodeGraph:

Question โ†’ codegraph_explore (returns the relevant symbol source + call path in one go)
     โ†’ codegraph_node to dig deeper if needed (1โ€“4 calls in total, usually 0 Reads)
     โ†’ give the answer
DimensionWithout CodeGraphWith CodeGraph
Finding a symbol definitiongrep text, prone to missing duplicates and false matchesFTS5 symbol search, with type, location, signature
Call relationshipsMultiple greps + Reads to trace by handcallers / callees / explore paths unfolded in one step
Impact analysisNearly impossible to do systematicallyimpact computes the blast radius of a change
Cross-file flowsBreaks easily at language/module boundariesFramework routes + dynamic dispatch bridged by synthesized edges
Large filesRead the whole file, token explosionReturns only the relevant symbol fragments
Data privacyNo extra dependencies100% local SQLite, never leaves the machine
First-time costZeroRequires codegraph init to build the index (one-time)

3.2 Quantitative Benchmarks

Test method: Claude Code in headless mode, the same architectural question, with and without the CodeGraph MCP, 4 runs each taking the median. Covers 7 open-source repositories and 7 languages, ranging in size from ~110 files to ~10k files.

Summary (median average):

MetricImprovement
CostAbout 16% lower
TokensAbout 47% fewer
TimeAbout 22% faster
Tool callsAbout 58% fewer
File readsClose to 0 (4โ€“9 per question without CodeGraph)

Per-repository comparison:

CodebaseLanguage ยท SizeCostTokensTimeTool calls
VS CodeTS ยท ~10kโ†“18%โ†“64%โ†“11%โ†“81%
ExcalidrawTS ยท ~640Flatโ†“25%โ†“27%โ†“40%
DjangoPython ยท ~3kโ†“8%โ†“60%โ†“13%โ†“77%
TokioRust ยท ~790Flatโ†“38%โ†“18%โ†“57%
OkHttpJava ยท ~645โ†“25%โ†“54%โ†“31%โ†“50%
GinGo ยท ~110โ†“19%โ†“23%โ†“24%โ†“44%
AlamofireSwift ยท ~110โ†“40%โ†“64%โ†“33%โ†“58%

The pattern is obvious: the larger the repository and the more complex the structural question, the more exaggerated the discovery overhead becomes without CodeGraph.

3.3 When You Can Skip It

ScenarioExplanation
Tiny projects (a few files)The agent reading everything directly is faster than building an index
Plain-text searchFinding log strings, comments, config entries โ€” grep is a better fit
Non-source filesREADME, .env, yaml config โ€” CodeGraph does not index them
Compilation/type correctnessStill relies on the compiler, linter, and tests
Fully dynamic reflectionRuntime eval and heavy reflection โ€” the graph will mark what it does not cover
The agent does not use the CodeGraph toolsInstalled but the agent still takes the grep path, which becomes pure overhead

4. How It Works

CodeGraph turns source code into a queryable graph in four stages:

File โ†’ Extract (tree-sitter AST) โ†’ Store (SQLite + FTS5)
              โ†“
        Resolve (imports, name matching, framework patterns)
              โ†“
        Graph query (callers, callees, impact)
              โ†“
        Context building (AI-facing markdown/JSON)

4.1 Extraction

tree-sitter parses source into an AST, and per-language extractors pull out of it:

  • Nodes: functions, classes, methods, types, routes, components, etc.
  • Edges: calls, imports, inheritance, implementation, references, etc.

Parsing runs in a separate worker thread. The extraction results come from the AST, not an LLM summary, so they are reproducible and trustworthy.

4.2 Storage

All data is written to .codegraph/codegraph.db under the project directory, with FTS5 full-text search support. It prefers the native better-sqlite3 and transparently falls back to the WASM backend when unavailable.

4.3 Resolution

After extraction, references still have to be connected to definitions:

  • Function calls โ†’ target definitions
  • import โ†’ source file
  • Class inheritance, interface implementation
  • Framework routes (Django urls.py, Express app.get, Spring @GetMapping, etc.)

For dynamic dispatch boundaries that static resolution cannot follow (callbacks, observers, React setStateโ†’render, JSX child components, etc.), CodeGraph bridges them with synthesized edges and marks them provenance: 'heuristic', so the agent knows how the edge was inferred.

4.4 Automatic Sync

Once the MCP service starts, it uses the operating system’s native file event watching to detect project changes and incrementally updates the index after debouncing. By default no manual sync is needed; the graph stays fresh as you code.

4.5 What the Graph Can Answer

Question typeCorresponding capability
Where is X defined?Symbol search (FTS5)
Who calls Y?callers traversal
What does Y call?callees / node source
What does changing Z affect?impact blast radius
How does X reach Y?Call paths in explore
Which handler does this URL map to?Framework route resolution

Node types include file, module, class, function, method, interface, route, component, and 20+ more; edge types include contains, calls, imports, extends, implements, references, returns, and so on.

5. Quick Start

5.1 Install the CLI

No Node.js required (a runtime is bundled):

1
2
3
4
5
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh

# Windows (PowerShell)
irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex

With Node already installed you can also use:

1
npm i -g @colbymchenry/codegraph

After installing, open a new terminal to make sure the codegraph command is available.

5.2 Connect It to Your AI Tools

1
codegraph install

The installer automatically detects installed agents (Claude Code, Cursor, Codex, etc.) and writes the CodeGraph MCP service into the corresponding configuration. Installing only the CLI is not enough โ€” this step is what actually connects CodeGraph to the agent.

Non-interactive install:

1
codegraph install --yes
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
โ”Œ  CodeGraph v1.0.1
โ”‚
โ—†  Claude Code: Updated ~/.claude.json
โ”‚
โ—†  Claude Code: Updated ~/.claude/settings.json
โ”‚
โ—†  Claude Code: Created ~/.claude/CLAUDE.md
โ”‚
โ—†  Cursor: Updated ~/.cursor/mcp.json
โ”‚
โ—  Cursor: Restart Cursor for MCP changes to take effect.
โ”‚
โ—†  Codex CLI: Updated ~/.codex/config.toml
โ”‚
โ—†  Codex CLI: Created ~/.codex/AGENTS.md
โ”‚
โ—‡  Quick start โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚                     โ”‚
โ”‚  cd your-project    โ”‚
โ”‚  codegraph init -i  โ”‚
โ”‚                     โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
codegraph collects anonymous usage stats (no code, paths, or names) โ€” "codegraph telemetry off" or CODEGRAPH_TELEMETRY=0 disables. Details: https://github.com/colbymchenry/codegraph/blob/main/TELEMETRY.md
โ”‚
โ””  Done! Restart your agents to use CodeGraph.

5.3 Initialize the Project

1
2
cd your-project
codegraph init
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
โ”Œ  Initializing CodeGraph
โ”‚
โ—†  Initialized in /Users/shaowenchen/Code/github/your-project
โ”‚
โ”‚  โ—† Scanning files โ€” 249 found
โ”‚  โ—† Parsing code โ€” done
โ”‚  โ—† Resolving refs โ€” done
โ”‚
โ—†  Indexed 249 files
โ”‚
โ—  4,076 nodes, 16,629 edges in 2.1s
โ”‚
โ””  Done

This creates .codegraph/ under the project and builds the full index. Afterward file changes sync automatically; no need to run init again.

5.4 Restart the Agent

Restart Cursor / Claude Code and so on so the MCP configuration takes effect. When a .codegraph/ directory exists in the project, the agent automatically gets the CodeGraph tools.

5.5 Uninstalling

1
2
codegraph uninstall          # remove the MCP configuration from all agents
codegraph uninit             # delete the .codegraph/ index for a single project

6. MCP Tool Reference

CodeGraph exposes the following tools over MCP:

ToolPurpose
codegraph_exploreThe workhorse: returns the source, call paths, and impact scope for several related symbols at once
codegraph_searchFind a symbol by name
codegraph_callersFind all call sites (including callback registration)
codegraph_calleesFind what is being called
codegraph_impactAnalyze the blast radius of changing a symbol
codegraph_nodeGet the details, full source, and call chain of a single symbol
codegraph_filesInspect the structure of the indexed files
codegraph_statusCheck the health of the index

Choosing a tool by intent:

  • “How does X work?” “How does X reach Y?” โ†’ codegraph_explore (usually enough in one call)
  • “Where is X?” โ†’ codegraph_search
  • “Who calls this function?” “What will break if I change it?” โ†’ codegraph_callers
  • “What does this function call internally?” โ†’ codegraph_node (includeCode: true)
  • Reading a source file โ†’ codegraph_node with a file path (equivalent to Read, plus dependency information)

7. Usage Advice

  1. Use CodeGraph directly for structural questions; do not rebuild with grep + Read information the index already has
  2. Trust the AST resolution results; there is no need to double-check with grep
  3. Watch for staleness hints after editing โ€” if a response begins with โš ๏ธ Some files referenced below were edited since the last index syncโ€ฆ, use Read to confirm the latest content of the listed files
  4. For a project that is not indexed: CodeGraph will report inactive, and the user needs to run codegraph init themselves

A few design principles worth knowing:

  • Local-first: the index lives in SQLite under .codegraph/, no API Key required, no external service dependency
  • Determinism over guessing: the graph comes from the tree-sitter AST, and synthesized edges are explicitly marked as heuristic inferences
  • One call returns enough context: codegraph_explore is designed to give an answer in a single call
  • Framework-aware: route resolution for 17+ web frameworks (Django, Flask, FastAPI, Express, Spring, Gin, Rails, etc.)

8. Common CLI Commands

1
2
3
4
5
6
codegraph init          # initialize and build the index
codegraph status        # view index status and files pending sync
codegraph sync          # manual sync (usually unnecessary)
codegraph query ...     # command-line query
codegraph upgrade       # check for and apply upgrades
codegraph serve --mcp   # start the MCP service manually (the agent starts it automatically)

9. Summary

CodeGraph turns an AI coding assistant from “fishing for needles in an ocean of files” into “querying a pre-built code knowledge graph directly.”

  • Comparison: without CodeGraph the agent relies on grep/Read for discovery (10โ€“20+ calls); with CodeGraph it is usually 1โ€“4 queries and close to zero file reads
  • Principle: tree-sitter parsing โ†’ SQLite storage โ†’ reference resolution + framework awareness โ†’ exposed to the agent via MCP
  • Usage: install the CLI โ†’ codegraph install to connect the agent โ†’ codegraph init in the project โ†’ restart the agent

If you already write code with Cursor or Claude Code, spending two minutes on the installation flow will make the agent noticeably more efficient on structural questions.


ๅพฎไฟกๅ…ฌไผ—ๅท
WRITTEN BY
ๅพฎไฟกๅ…ฌไผ—ๅท