codegraph

by colbymchenry

Not rated
GitHub

About

Pre-indexed code knowledge graph, auto syncs on code changes, for Claude Code, Codex, Gemini, Cursor, OpenCode, AntiGravity, Kiro, and Hermes Agent — fewer tokens, fewer tool calls, 100% local

Details

Author
colbymchenry
Categories
Other, AI, Knowledge Base

Setup

Install codegraph in your MCP client (Claude Desktop, Cursor, Windsurf, and others).

Repository: https://github.com/colbymchenry/codegraph

Follow the installation instructions in the repository README, then restart your MCP client.

Already installed? Runcodegraph upgrade

Supercharge Claude Code, Cursor, Codex, OpenCode, Hermes Agent, Gemini, Antigravity, and Kiro with Semantic Code Intelligence

The fastest complete code graph · surgical context · built for how agents actually work · 100% local

The CodeGraph platform is coming— for every PR, know exactly what to test, what could break, which flows are affected, and whether business logic is compromised.

Getearly beta accessto the hosted product ·getcodegraph.com

No Node.js required— one command grabs the right build for your OS:

# 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

Already have Node? Use npm instead (works on any version)

CodeGraph bundles its own runtime — nothing to compile, no native build, works the same everywhere. The installer putscodegraphon your PATH butdoesn't change your current shell— open a new terminal before the next step so the command resolves.

Upgrade any timewithcodegraph upgrade— it detects how you installed (bundle, npm, or npx) and updates in place. Add--checkto see if an update is available, orcodegraph upgrade <version>to pin one.

In anew terminal, run the installer to connect CodeGraph to the agents you use:

Detects and auto-configures Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, and Kiro — wiring the CodeGraph MCP server into each.This is the step that connects CodeGraph to your agent;installing the CLI in step 1 does not do it on its own. It only wires up your agent — it doesnotindex any code; building each project's graph is the separatecodegraph initin step 3. (Shortcut:npx @colbymchenry/codegraphdownloads and runs this in one go.)

codegraph initcreates the local.codegraph/directory and builds the full graph in the same step — one command, done.

Auto-sync is enabled by default. CodeGraph watches the project and updates the graph on every file change — while your agent edits code, or you add, modify, or delete files.The index is never stale, and there is nothing to re-run.

Changed your mind? One command removes CodeGraph from every agent it configuredandthe CLI itself — every install it finds (standalone bundle, npm global package, launcher link), shown to you before anything is deleted:

Pass--keep-clito remove only the agent configurations and keep the CLI installed.

Reverses the installer — strips CodeGraph's MCP server config, instructions, and permissions from each configured agent. Your project indexes (.codegraph/) are left untouched; remove those per-project withcodegraph uninit. Use--targetto remove from specific agents, or--yesto run non-interactively.

Every language below gets the same treatment — full structural extraction and cross-file resolution into one graph, no per-language setup:

Per-language details — extensions, frameworks, and what exactly gets extracted — inSupported Languages.

When an AI agent needs to understand code — to answer a question or make a change — it discovers structure the slow way: grep, glob, and Read, one file at a time, rebuilding call paths and dependencies by hand. That's a pile of tool calls and round-trips before it even starts the real work.

CodeGraph hands the agent the exact code it needs in one call.It's a pre-built knowledge graph of every symbol, call edge, and dependency in your codebase — so instead of crawling files, the agent asks one question and gets back the relevant source, the call paths between those symbols (including dynamic-dispatch hops grep can't follow), and the blast radius of a change.Surgical context, not a file-by-file search— which means fewer tool calls and faster answers on every codebase, large or small.

A note on cost:CodeGraph's win oneverycodebase is precision — the agent stops crawling files and answers from the graph. On current models that precision is also a large direct saving: the 2026-07 re-validation measured60% lower cost and 69% fewer tokens on averageacross the seven benchmark repos, because a strong modelwithoutthe graph burns millions of tokens re-deriving structure. The savings scale with repo size and tangle — dramatic on VS-Code-class trees, modest on a 100-file project — and compound across a team's daily agent usage.

Tested across7 real-world open-source codebasesspanning 7 languages, comparing an agent (Claude Code, headless) answering one architecture questionwithandwithoutCodeGraph, at themedian of 4 runs per arm.Re-validated 2026-07-21 onClaude Opus 4.8against the current build — the Rust kernel plus this cycle's resolution overhaul.

The universal win — every repo, every size: 89% fewer tool calls · 60% cheaper · 69% fewer tokens · file reads cut to zero on all seven repos.

With the index available, the agent answers from a couple ofcodegraph_explorecalls and stops. Without it, the agent burns its budget on discovery — up to57 tool calls and 4.3M tokensre-deriving what the graph already knew. TheTimecolumn averages 20% faster but is the noisiest metric: on two small repos a strong model's raw grep loop finishes the wall-clock race sooner while still spending 5–10× the tokens and money — noted per-row below.

¹ The small-repo floor effect: Opus 4.8 greps small trees fast enough to win wall-clock while spending ~5–10× the tokens and ~4–7× the cost — the with-arm still answers from zero file reads. ² OkHttp's without-arm got lucky in 5 calls; the with-arm answered in 1 call for ~$0.03 more.File reads= median files opened — the surgical-context win in one column: the agent never reads a file on any of the seven repos when CodeGraph is present.

Per-repo breakdown — WITH vs WITHOUT (median of 4)

Methodology.Each arm isclaude -p(Claude Opus 4.8) run headlessly against the repo with--strict-mcp-config:WITH= CodeGraph's MCP server enabled,WITHOUT= an empty MCP config. Built-in Read/Grep/Bash stay available to both. Same question per repo,4 runs per arm, median reported. Cost = the run'stotal_cost_usd; Tokens = total tokens processed (input incl. cached + output); Time = wall-clock; Tool calls = every tool invocation, including those inside any sub-agents the model spawns. Repos cloned at--depth 1and indexed by the same CodeGraph build that served them. Re-validated 2026-07-21 on the current build (native Rust kernel, adaptive parallel resolution, scoped sync).

Why CodeGraph wins:with the index available, the agent answers directly — usually onecodegraph_explorereturns the relevant source — and stops, with zero file reads on every benchmark repo. Without it, the agent spends most of its budget on discovery (find/ls/grep) before reading the right code. CodeGraph only helps when querieddirectly, so its instructions steer agents to answer directly rather than delegate exploration to file-reading sub-agents — otherwise a sub-agent reads files regardless and CodeGraph becomes overhead.

CodeGraph's parsing engine is anative Rust kernel: 20 languages — TypeScript, JavaScript, Java, Python, Go, C, C++, Rust, C#, Ruby, PHP, Swift, Kotlin, Scala, Dart, R, Lua, Luau (Metal and CUDA ride the C++ path) — parse in compiled code with one boundary crossing per file. Every language shipped only after its graphs provedbyte-for-byte identicalto the reference engine on real repositories, from small libraries up to the Linux kernel; platforms without a prebuilt binary and files with syntax errors fall back per-file automatically, same graph either way.

And it scales itself to the machine it's on.Worker pools, parallel resolution, and analysis caches are sized from what the system actually has — real core counts (container/cgroup-aware, so a VPS that grants 2 cores gets sized for 2, not the host's 64), honestly-measured available RAM on macOS and Linux, and the measured cost ofyourproject's resolution work:

- On a workstation:the full parallel pipeline — native parse workers, a multi-worker resolver pool that engages the moment it pays for itself, memory-gated analysis caches. The Swift compiler repository (27k files of Swift and C++) fresh-indexes in about 100 seconds; a one-file edit re-syncs in ~4.
- On a 2-core / 6GB VPS:the same graph, from a pipeline tuned tofinish— the Linux kernel (70k files, 2M symbols, 6.4M relationships) indexes to completion in under 12 minutes where RAM-first designs run out of memory before reaching 1%.
- Every day after day one:saving a file updates the graph in well under a second — the watcher fires 300ms after a lone save and syncs exactly what changed (~0.3s of work on a 4,400-file project, ~0.4s on the 27,000-file Swift compiler repo), never re-scanning the tree. Measured against the fastest competing indexer's re-index-on-change: 2–7× faster on medium and larger repos across a 31-repo, 30-language benchmark — and the gap widens with repo size, because their cost grows with the repository and ours grows with the change.

How auto-syncing works — and why you don't need to runcodegraph syncmanually

When your agent (Claude Code, Cursor, Codex, opencode) launchescodegraph serve --mcp, three layers keep the index in step with your code — and make sure the agent never gets a silent wrong answer in the brief window between an edit and the next sync:
- File watcher with debounced auto-sync.A native FSEvents / inotify / ReadDirectoryChangesW watcher captures every source-file create / modify / delete and triggers a re-index after a debounce window (default2000ms, tunable viaCODEGRAPH_WATCH_DEBOUNCE_MS, clamped to
[100ms, 60s]). Bursts of edits collapse into a single sync.
- Per-file staleness banner.During the brief debounce window, MCP tool responses that would reference a still-pending file prepend a⚠️banner naming it and telling the agent toReadit directly. Pending files NOT referenced by the response surface as a small footer instead. Either way, the agent gets an explicit signal — validated with Claude Code, where the agent literally says "Reading the file directly for the live content" before opening it.
- Connect-time catch-up.When the MCP server (re)connects, codegraph runs a fast(size, mtime)+ content-hash reconciliation against the working tree before answering the first query — so edits made while no MCP server was running (agit pullfrom the terminal, edits from another editor, a previous agent session that exited) get absorbed on the next session's first tool call.

agent writes src/Widget.ts → watcher fires (<100ms) → debounce (default 2s) → sync; Widget.ts is in the index → next agent query sees it

Verify any timewithcodegraph status(CLI). If anything is pending, you'll see a### Pending sync:section naming the files and their edit age.

The handful of cases where manualcodegraph syncmakes sense: the watcher is disabled (sandboxed environments, orCODEGRAPH_NO_DAEMON=1), or you're scripting against the index outside an agent session and want a pre-flight sync at the start of your script.

→ Full deep-dive inGuides → Indexing a Project.

CodeGraph detects web-framework routing files and emitsroutenodes linked byreferencesedges to their handler classes or functions. Querying callers of a view/controller now surfaces the URL pattern that binds it.

Mixed iOS / React Native / Expo bridging

Real iOS and React Native codebases live across multiple languages — a Swift caller invokes an Objective-C selector that's been auto-bridged, a JS file calls into a native module via the React Native bridge, a JSX component delegates to a native view manager. Static tree-sitter extraction stops at each language boundary. CodeGraph bridges them socodegraph_exploreconnects the flow end-to-end across the gap — call paths and blast radius cross the boundary instead of stopping at it.

Validated on real codebases(small + medium + large for each bridge):

Each bridge emits edges taggedprovenance:'heuristic'withmetadata.synthesizedBy:set to a stable channel name (e.g.swift-objc-bridge,rn-event-channel,fabric-native-impl,expo-module-extract), so the agent can tell at a glance how a hop got into the graph.

- Ask which agent(s) to configure — auto-detects installed ones from:Claude Code,Cursor,Codex CLI,opencode,Hermes Agent,Gemini CLI,Antigravity IDE,Kiro
- Prompt to installcodegraphon your PATH (so agents can launch the MCP server)
- Ask whether configs apply to all your projects or just this one
- Write each chosen agent's MCP server config, plus a small marker-fenced CodeGraph section in the agent's instructions file (CLAUDE.md/AGENTS.md/GEMINI.md) — that's how subagents and non-MCP agents learn thecodegraph explorecommand, since the MCP server's own guidance only reaches the main agent. Removed cleanly bycodegraph uninstall.
- Set up auto-allow permissions when Claude Code is one of the targets

The installerwires up your agents only — it does not index your code.After it finishes, build each project's graph yourself withcodegraph init(step 3). One globalcodegraph installcovers every project; you runcodegraph initonce per project.

codegraph install --yes # auto-detect agents, install global codegraph install --target=cursor,claude --yes # explicit target list codegraph install --target=auto --location=local # detected agents, project-local codegraph install --print-config codex # print snippet, no file writes

Restart your agent (Claude Code / Cursor / Codex CLI / opencode / Hermes Agent / Gemini CLI / Antigravity IDE / Kiro) for the MCP server to load.

Builds the per-project knowledge graph index, which then auto-syncs on every file change. A single globalcodegraph installworks in every project you open — no need to re-run the installer per project.

That's it — your agent will use CodeGraph tools automatically when a.codegraph/directory exists.

{ "mcpServers": { "codegraph": { "type": "stdio", "command": "codegraph", "args": ["serve", "--mcp"] } } }

Add to~/.claude/settings.json(optional, for auto-allow):

{ "permissions": { "allow": [ "mcp__codegraph__" ] } }

One wildcard auto-approves every CodeGraph tool —codegraph_exploreis the only one listed by default, but if you re-enable others viaCODEGRAPH_MCP_TOOLSthey're already permitted, no prompt.

CodeGraph's MCP server delivers its usage guidance to your agentautomatically, in the MCPinitializeresponse. In short, it tells the agent to:

- Answer structural questions directly with CodeGraph— itisthe pre-built index, so a grep/read loop just repeats work it already did. Treat the returned source as already read.
- Reach forcodegraph_explorefor almost anything— "how does X work", a flow/"how does X reach Y", or surveying an area. One call returns the relevant symbols' verbatim source grouped by file, the call paths between them (dynamic-dispatch hops included), and a blast-radius summary. Name a file or symbol in the query to read its current line-numbered source.
- Trust the results — don't re-verify with grep, and check the staleness banner after edits.
- Worksper project: query any project that has a.codegraph/index by passingprojectPath— so a monorepo where only some services are indexed, or a second repo, works in one session. A path with no index returns clean guidance to use built-in tools; indexing stays your decision.

The exact text issrc/mcp/server-instructions.ts— the single source of truth for the main agent. Because subagents and non-MCP harnesses never see the MCP guidance, the installer also writes a short marker-fenced section into the agent's instructions file pointing at thecodegraph exploreCLI equivalent.

┌───────────────────────────────────────────────────────────────────┐ │ Claude Code │ │ │ │ "How does a request reach the database?" │ │ calls CodeGraph tools directly — no Explore sub-agent │ │ │ │ └─────────────────────────────────┬─────────────────────────────────┘ │ ▼ ┌───────────────────────────────────────────────────────────────────┐ │ CodeGraph MCP Server │ │ │ │ explore · one call → verbatim source + call flow + blast radius │ │ │ │ │ ▼ │ │ SQLite knowledge graph │ │ symbols · edges · files · FTS5 full-text search │ └───────────────────────────────────────────────────────────────────┘

- Extraction— a nativeRust kernelparses source withtree-sittergrammars compiled into it, extracting nodes (functions, classes, methods) and edges (calls, imports, extends, implements) for 20 languages; remaining languages and per-file fallbacks use the same extraction logic on the portable engine, producing identical graphs.
- Storage— Everything goes into a local SQLite database (.codegraph/codegraph.db) with FTS5 full-text search.
- Resolution— After extraction, references are resolved: function calls → definitions, imports → source files, class inheritance, and framework-specific patterns.
- Auto-Sync— The MCP server watches your project using native OS file events. Changes are debounced (2-second quiet window), filtered to source files only, and incrementally synced. The graph stays fresh as you code — no configuration needed.

codegraph # Run interactive installer codegraph install # Run installer (explicit) codegraph uninstall # Remove CodeGraph from your agents AND the CLI (--keep-cli for configs only) codegraph init [path] # Initialize a project + build its graph (one step) codegraph uninit [path] # Remove CodeGraph from a project (--force to skip prompt) codegraph index [path] # Full index (--force to re-index, --quiet for less output) codegraph sync [path] # Incremental update codegraph status [path] # Show statistics codegraph unlock [path] # Remove a stale lock file that's blocking indexing codegraph query <search> # Search symbols (--kind, --limit, --json) codegraph explore <query> # Relevant symbols' source + call paths in one shot (same output as the codegraph_explore MCP tool) codegraph node <symbol|file> # One symbol's source + callers, or read a file with line numbers (same output as codegraph_node) codegraph files [path] # Show file structure (--format, --filter, --max-depth, --json) codegraph callers <symbol> # Find what calls a function/method (--limit, --json) codegraph callees <symbol> # Find what a function/method calls (--limit, --json) codegraph impact <symbol> # Analyze what code is affected by changing a symbol (--depth, --json) codegraph affected [files...] # Find test files affected by changes (see below) codegraph daemon # Manage background daemons — pick one to stop (alias: daemons) codegraph telemetry [on|off] # Show or change anonymous usage telemetry codegraph upgrade [version] # Update to the latest release (--check, --force) codegraph version # Print the installed version (also -v, --version) codegraph help [command] # Show help, optionally for one command

Traces import dependencies transitively to find which test files are affected by changed source files.

codegraph affected src/utils.ts src/api.ts # Pass files as arguments git diff --name-only | codegraph affected --stdin # Pipe from git diff codegraph affected src/auth.ts --filter "e2e/" # Custom test file pattern
#!/usr/bin/env bash AFFECTED=$(git diff --name-only HEAD | codegraph affected --stdin --quiet) if [ -n "$AFFECTED" ]; then npx vitest run $AFFECTED fi

When running as an MCP server, CodeGraph exposes asingle toolcodegraph_explore. Measured agent behavior showed that one strong tool steers agents better than a menu of narrower ones — fewer mis-picks, and it saves context every session:

The other tools (codegraph_node,codegraph_search,codegraph_callers,codegraph_callees,codegraph_impact,codegraph_files,codegraph_status) stay fully functional butunlisted by default— everything they return already arrives inline oncodegraph_explore(its blast-radius section, the relationship map, a symbol's body as its callee list). Re-enable any of them for the MCP surface with theCODEGRAPH_MCP_TOOLSenvironment variable (e.g.CODEGRAPH_MCP_TOOLS=explore,node,search,callers), or use their CLI equivalents (codegraph node/query/callers/callees/impact/files/status).

Even when the server's own root has no.codegraph/index, the tools stay available: passprojectPathto query any indexed project — a sub-service in a monorepo, or a second repo — in the same session. A path that has no index returns clean guidance to use built-in tools instead, so nothing fails loudly, and indexing stays your decision.

CodeGraph can be embedded directly. The npm package re-exports its programmatic API, so bothimportandrequireresolve theCodeGraphclass in your own process — handy for embedding it in an app (e.g. an Electron main process).

import CodeGraph from '@colbymchenry/codegraph'; // CommonJS works too: // const { CodeGraph } = require('@colbymchenry/codegraph'); const cg = await CodeGraph.init('/path/to/project'); // Or: const cg = await CodeGraph.open('/path/to/project'); await cg.indexAll({ onProgress: (p) => console.log(\${p.phase}: ${p.current}/${p.total}\) }); const results = cg.searchNodes('UserService'); const callers = cg.getCallers(results[0].node.id); const context = await cg.buildContext('fix login bug', { maxNodes: 20, includeCode: true, format: 'markdown' }); const impact = cg.getImpactRadius(results[0].node.id, 2); cg.watch(); // auto-sync on file changes cg.unwatch(); // stop watching cg.close();

Lower-level building blocks are exported from the same entry point for callers that drive the graph directly:DatabaseConnection,QueryBuilder,getDatabasePath,initGrammars/loadGrammarsForLanguages, andFileLock.

- Install from npm (npm i @colbymchenry/codegraph) so the matching per-platform package — which carries the compiled library and its dependencies — is fetched alongside the shim.
- The API runs onyourruntime, so it needsNode 22.5+for the built-innode:sqlite(Electron qualifies when its bundled Node is 22.5+). The CLI and MCP server are unaffected — they run on the self-contained bundled runtime.
- TypeScript types ship with the package. As with any Node-targeting library, keep@types/nodeavailable andskipLibCheck: true(the common default).

Next to none — CodeGraph iszero-config by default, with nothing to write or keep in sync to get started. Language support is automatic from the file extension; there's nothing to wire up per language. The one optional file is for mappingcustom file extensions.

- Dependency, build, and cache directoriesnode_modules,vendor,dist,build,target,.venv,Pods,.next, and the like across everysupported stack— so the graph is your code, not third-party noise. This holds even with no.gitignore.
- Anything in your.gitignore— honored in git repos via git, and in non-git projects by reading.gitignoredirectly (root and nested).
- Files larger than 1 MB— generated bundles, minified JS, vendored blobs.

To keep something else out, add it to.gitignore. To pull a default-excluded directory backin(say you really do want a vendored dependency indexed), add a negation —!vendor/. The defaults apply uniformly, so committing a dependency or build directory doesn't force it into the graph; the.gitignorenegation is the explicit opt-in.

.gitignorecan't drop a directory you'vecommitted, though. For a vendored theme or SDK that's checked into the repo (e.g. a Metronic theme understatic/), list it underexcludeincodegraph.json— gitignore-style patterns, matched against repo-root-relative paths, honored on index, sync, and watch:

{ "exclude": ["static/", "/vendor/"] }

Conversely, when real source is gitignored on purpose — a project under a second VCS (SVN, Perforce) that.gitignores its own source so it stays out of Git — force it back in withinclude(the opposite ofexclude;includeIgnoredonly revives embedded git repos, not plain source):

{ "include": ["Tools/", "Local/typescript/"] }

CodeGraph discovers those files off disk, overriding.gitignore, on index, sync, and watch. An explicitexcludestill wins, and built-in skips (node_modules,dist,.git) are never re-included.

If your project uses a non-standard extension for asupported language— say.dota_luafor Lua, or.tplfor PHP — those files are skipped by default, because the extension isn't one CodeGraph recognizes. Map them with an optionalcodegraph.jsonat your project root:

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.