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

~35% cheaper · ~70% fewer tool calls · 100% local

Documentation & Website →

Get Started

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):

npx @colbymchenry/codegraph        # zero-install, or:
npm i -g @colbymchenry/codegraph

CodeGraph bundles its own runtime — nothing to compile, no native build, works the same everywhere. The interactive installer auto-configures your agent(s) — Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, Kiro.

Initialize Projects
cd your-project
codegraph init -i

Uninstall

Changed your mind? One command removes CodeGraph from every agent it configured:

codegraph uninstall

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 with codegraph uninit. Use --target to remove from specific agents, or --yes to run non-interactively.

Why CodeGraph?

When Claude Code explores a codebase, it spawns Explore agents that scan files with grep, glob, and Read — consuming tokens on every tool call.

CodeGraph gives those agents a pre-indexed knowledge graph — symbol relationships, call graphs, and code structure. Agents query the graph instantly instead of scanning files.

Benchmark Results

Tested across 7 real-world open-source codebases spanning 7 languages, comparing an agent (Claude Code, headless) answering one architecture question with and without CodeGraph. Each cell is the savings at the median of 4 runs per arm. Re-validated on v0.9.4 (2026-05-24).

Average: 35% cheaper · 57% fewer tokens · 46% faster · 71% fewer tool calls

Codebase	Language	Cost	Tokens	Time	Tool calls
VS Code	TypeScript · ~10k files	26% cheaper	78% fewer	52% faster	85% fewer
Excalidraw	TypeScript · ~640	52% cheaper	90% fewer	73% faster	96% fewer
Django	Python · ~3k	12% cheaper	36% fewer	19% faster	53% fewer
Tokio	Rust · ~790	82% cheaper	86% fewer	71% faster	92% fewer
OkHttp	Java · ~645	2% cheaper	13% fewer	31% faster	45% fewer
Gin	Go · ~110	21% cheaper	34% fewer	27% faster	40% fewer
Alamofire	Swift · ~110	47% cheaper	64% fewer	48% faster	83% fewer

The gains scale with codebase size: on large repos the agent answers from the index in a handful of calls with zero file reads, while the no-CodeGraph agent fans out across grep/find/Read (and the sub-agents it spawns). On a small repo like Gin (~150 files) native search is already cheap, so the margin narrows.

Full benchmark details
Key Features

Smart Context Building	One tool call returns entry points, related symbols, and code snippets — no expensive exploration agents
Full-Text Search	Find code by name instantly across your entire codebase, powered by FTS5
Impact Analysis	Trace callers, callees, and the full impact radius of any symbol before making changes
Always Fresh	File watcher uses native OS events (FSEvents/inotify/ReadDirectoryChangesW) with debounced auto-sync — the graph stays current as you code, zero config
20+ Languages	TypeScript, JavaScript, Python, Go, Rust, Java, C#, PHP, Ruby, C, C++, Objective-C, Swift, Kotlin, Dart, Lua, Luau, Svelte, Liquid, Pascal/Delphi
Framework-aware Routes	Recognizes web-framework routing files and links URL patterns to their handlers across 14 frameworks
Mixed iOS / React Native / Expo	Closes cross-language flows that static parsing misses: Swift ↔ ObjC bridging, React Native legacy bridge + TurboModules + Fabric view components, native → JS event emitters, Expo Modules
100% Local	No data leaves your machine. No API keys. No external services. SQLite database only
How auto-syncing works — and why you don't need to run codegraph sync manually
Framework-aware Routes

CodeGraph detects web-framework routing files and emits route nodes linked by references edges to their handler classes or functions. Querying callers of a view/controller now surfaces the URL pattern that binds it.

Framework	Shapes recognized
Django	path(), re_path(), url(), include() in urls.py (CBV .as_view(), dotted paths)
Flask	@app.route('/path', methods=[...]), blueprint routes
FastAPI	@app.get(...), @router.post(...), all standard methods
Express	app.get(...), router.post(...) with middleware chains
NestJS	@Controller + @Get/@Post/..., GraphQL @Resolver + @Query/@Mutation, @MessagePattern/@EventPattern, @SubscribeMessage
Laravel	Route::get(), Route::resource(), Controller@action, tuple syntax
Drupal	*.routing.yml routes (_controller, _form, entity handlers); hook_* implementations in .module/.theme/.install/.inc
Rails	get '/x', to: 'users#index', hash-rocket => syntax
Spring	@GetMapping, @PostMapping, @RequestMapping on methods
Gin / chi / gorilla / mux	r.GET(...), router.HandleFunc(...)
Axum / actix / Rocket	.route("/x", get(handler))
ASP.NET	[HttpGet("/x")] attributes on action methods
Vapor	app.get("x", use: handler)
React Router / SvelteKit	Route component nodes
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 so trace, callers, callees, and impact connect end-to-end across the gap.

Boundary	JS / Swift side	Native side	How
Swift → ObjC	Swift obj.foo(bar:)	ObjC selector -fooWithBar:	@objc auto-bridging rules (including init/property/protocol forms) + Cocoa preposition prefixes (With/For/By/In/On/At/…)
ObjC → Swift	ObjC [obj fooWithBar:]	Swift @objc func foo(bar:)	Reverse-bridge name candidates; verifies @objc exposure from source
React Native legacy bridge	JS NativeModules.X.fn(...)	ObjC RCT_EXPORT_METHOD / RCT_REMAP_METHOD · Java/Kotlin @ReactMethod	Parses macro/annotation declarations to build a JS-name → native-method map
React Native TurboModules	JS import M from './NativeM'; M.fn(...)	Native impl matching the Codegen spec	Treats the Native<X>.ts spec interface as ground truth
RN native → JS events	JS new NativeEventEmitter(...).addListener('e', cb)	ObjC [self sendEventWithName:@"e" body:...] · Swift sendEvent(withName: "e", ...) · Java/Kotlin .emit("e", ...)	Synthesized cross-language event channel keyed by literal event name
Expo Modules	JS requireNativeModule('X').fn(...)	Swift / Kotlin Module { Name("X"); AsyncFunction("fn") { ... } }	Parses the Expo DSL literals; synthetic method nodes resolve via existing name-match
Fabric view components	JSX <MyView prop={v}/>	TS Codegen spec + native impl class	Spec → component node; convention-based name+suffix lookup (View/ComponentView/Manager/ViewManager) bridges to native
Legacy Paper view managers	JSX <MyView prop={v}/>	ObjC RCT_EXPORT_VIEW_PROPERTY · Java/Kotlin @ReactProp	Same as Fabric — Paper-era declarations also produce component + property nodes

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

Bridge	Small	Medium	Large
Swift ↔ ObjC	Charts	realm-swift	Wikipedia-iOS
RN legacy bridge	AsyncStorage	react-native-svg	react-native-firebase
RN native → JS events	RNGeolocation	—	react-native-firebase
Expo Modules	expo-haptics	expo-camera	expo SDK sweep (7 packages)
Fabric / Paper views	react-native-segmented-control	react-native-screens	react-native-skia

Each bridge emits edges tagged provenance:'heuristic' with metadata.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.

Quick Start
1. Run the Installer
npx @colbymchenry/codegraph

The installer will:

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 install codegraph on 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 + an instructions file (e.g. CLAUDE.md, .cursor/rules/codegraph.mdc, ~/.codex/AGENTS.md, ~/.gemini/GEMINI.md)
Set up auto-allow permissions when Claude Code is one of the targets
Initialize your current project (local installs only)

Non-interactive (scripting / CI):

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
Flag	Values	Default
--target	auto, all, none, or csv (claude,cursor,...)	prompt
--location	global, local	prompt
--yes	(boolean)	prompt every step
--no-permissions	(boolean) skip Claude auto-allow list	permissions on
--print-config <id>	dump snippet for one agent and exit	—
2. Restart Your Agent

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

3. Initialize Projects
cd your-project
codegraph init -i

Builds the per-project knowledge graph index. Also wires up any project-local agent surfaces (e.g. Cursor's .cursor/rules/codegraph.mdc) so a single global codegraph install works 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.

Manual Setup (Alternative)
Global Instructions Reference
How It Works
┌───────────────────────────────────────────────────────────────────┐
│                            Claude Code                            │
│                                                                   │
│   "How does a request reach the database?"                        │
│       calls CodeGraph tools directly — no Explore sub-agent       │
│                                 │                                 │
└─────────────────────────────────┬─────────────────────────────────┘
                                  │
                                  ▼
┌───────────────────────────────────────────────────────────────────┐
│                        CodeGraph MCP Server                       │
│                                                                   │
│       context · trace · explore · callers · callees · impact      │
│                                 │                                 │
│                                 ▼                                 │
│                       SQLite knowledge graph                      │
│          symbols · edges · files · FTS5 full-text search          │
└───────────────────────────────────────────────────────────────────┘

Extraction — tree-sitter parses source code into ASTs. Language-specific queries extract nodes (functions, classes, methods) and edges (calls, imports, extends, implements).

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.

CLI Reference
codegraph                         # Run interactive installer
codegraph install                 # Run installer (explicit)
codegraph uninstall               # Remove CodeGraph from your agents (inverse of install)
codegraph init [path]             # Initialize in a project (--index to also index)
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 query <search>          # Search symbols (--kind, --limit, --json)
codegraph files [path]            # Show file structure (--format, --filter, --max-depth, --json)
codegraph context <task>          # Build context for AI (--format, --max-nodes)
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 serve --mcp             # Start MCP server
codegraph affected

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
Option	Description	Default
--stdin	Read file list from stdin	false
-d, --depth <n>	Max dependency traversal depth	5
-f, --filter <glob>	Custom glob to identify test files	auto-detect
-j, --json	Output as JSON	false
-q, --quiet	Output file paths only	false

CI/hook example:

#!/usr/bin/env bash
AFFECTED=$(git diff --name-only HEAD | codegraph affected --stdin --quiet)
if [ -n "$AFFECTED" ]; then
  npx vitest run $AFFECTED
fi
MCP Tools

When running as an MCP server, CodeGraph exposes these tools to Claude Code:

Tool	Purpose
codegraph_search	Find symbols by name across the codebase
codegraph_context	Build relevant code context for a task
codegraph_trace	Trace the call path between two symbols ("how does X reach Y") in one call — each hop with its body inline, following dynamic-dispatch hops (callbacks, React re-render, interface→impl) that grep can't
codegraph_callers	Find what calls a function
codegraph_callees	Find what a function calls
codegraph_impact	Analyze what code is affected by changing a symbol
codegraph_node	Get details about a specific symbol (optionally with source code)
codegraph_explore	Return source for several related symbols grouped by file, plus a relationship map, in one call
codegraph_files	Get indexed file structure (faster than filesystem scanning)
codegraph_status	Check index health and statistics
Library Usage
import CodeGraph from '@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();
Configuration

There isn't any — CodeGraph is zero-config, with no config file to write or keep in sync. Language support is automatic from the file extension; there's nothing to wire up per language.

What it skips out of the box:

Dependency, build, and cache directories — node_modules, vendor, dist, build, target, .venv, Pods, .next, and the like across every supported 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 .gitignore directly (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 back in (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 .gitignore negation is the explicit opt-in.

Supported Platforms

Every release ships a self-contained build (bundled Node runtime — nothing to compile) for all three desktop OSes, on both Intel/AMD (x64) and ARM (arm64):

Platform	Architectures	Install
Windows	x64, arm64	PowerShell installer or npm
macOS	x64, arm64	shell installer or npm
Linux	x64, arm64	shell installer or npm

See Get Started for the one-line install commands.

Supported Agents

The interactive installer auto-detects and configures each of these — wiring up the MCP server and writing its instructions file:

Claude Code
Cursor
Codex CLI
opencode
Hermes Agent
Gemini CLI
Antigravity IDE
Kiro
Supported Languages
Language	Extension	Status
TypeScript	.ts, .tsx	Full support
JavaScript	.js, .jsx, .mjs	Full support
Python	.py	Full support
Go	.go	Full support
Rust	.rs	Full support
Java	.java	Full support
C#	.cs	Full support
PHP	.php	Full support
Ruby	.rb	Full support
C	.c, .h	Full support
C++	.cpp, .hpp, .cc	Full support
Objective-C	.m, .mm, .h	Partial support (classes, protocols, methods, @property, #import, message sends; .mm ObjC++ may parse incompletely)
Swift	.swift	Full support
Kotlin	.kt, .kts	Full support
Scala	.scala, .sc	Full support (classes, traits, methods, type aliases, Scala 3 enums)
Dart	.dart	Full support
Svelte	.svelte	Full support (script extraction, Svelte 5 runes, SvelteKit routes)
Vue	.vue	Full support (script + script-setup extraction, Nuxt page/API/middleware routes)
Liquid	.liquid	Full support
Pascal / Delphi	.pas, .dpr, .dpk, .lpr	Full support (classes, records, interfaces, enums, DFM/FMX form files)
Lua	.lua	Full support (functions, methods with receivers, local variables, require imports, call edges)
Luau	.luau	Full support (everything in Lua, plus type/export type aliases, typed signatures, and Roblox instance-path require)
Troubleshooting

"CodeGraph not initialized" — Run codegraph init in your project directory first.

Indexing is slow — Check that node_modules and other large directories are excluded. Use --quiet to reduce output overhead.

MCP hits database is locked — current builds shouldn't: CodeGraph bundles its own Node runtime and uses Node's built-in node:sqlite in WAL mode, where concurrent reads never block on a writer. If you still see it:

You're on an old (pre-0.9) install. Reinstall to get the bundled runtime — curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh (macOS/Linux), irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex (Windows), or npm i -g @colbymchenry/codegraph@latest.
codegraph status shows Journal: other than wal — WAL couldn't be enabled on this filesystem (common on network shares and WSL2 /mnt), so reads can block on writes. Move the project (with its .codegraph/ folder) onto a local disk.

MCP server not connecting — Ensure the project is initialized/indexed, verify the path in your MCP config, and check that codegraph serve --mcp works from the command line.

Missing symbols — The MCP server auto-syncs on save (wait a couple seconds). Run codegraph sync manually if needed. Check that the file's language is supported and isn't inside a .gitignored or default-excluded directory (e.g. node_modules, dist).

Star History
License

MIT

Made for AI coding agents — Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, and Kiro

Report Bug · Request Feature


主公，此项目颇为有趣，今为君剖析。

---

## 📊 CodeGraph 项目分析

---

### 一、项目定位

**CodeGraph** 是一个为 AI 编码代理（Agent）提供代码语义索引的工具，使 Agent 能够用极少的 token 和工具调用理解代码库结构。

> **Slogan：** "Fewer tokens, fewer tool calls, 100% local"

---

### 二、解决什么问题

#### 传统 AI Agent 的困境

当 Claude Code（或其他 Agent）探索代码库时，它会：
1. 启动 **Explore 子代理**
2. 用 `grep/find/Read` 扫描文件
3. 每一步都消耗大量 token 和工具调用

**问题：** 在大型代码库中，一次架构问题问答可能触发数百次工具调用，消耗海量 token。

#### CodeGraph 的解法

预先构建代码的**知识图谱**——符号关系、调用图、代码结构。

Agent 查询图谱即可获得答案，**无需扫描文件**。

---

### 三、性能数据

| 代码库 | 语言 | 费用节省 | Token 节省 | 时间节省 | 工具调用减少 |
|--------|------|---------|-----------|---------|-------------|
| VS Code | TypeScript (~10k文件) | 26% | 78% | 52% | 85% |
| Excalidraw | TypeScript (~640) | 52% | 90% | 73% | 96% |
| Tokio | Rust (~790) | 82% | 86% | 71% | 92% |
| Alamofire | Swift (~110) | 47% | 64% | 48% | 83% |
| Django | Python (~3k) | 12% | 36% | 19% | 53% |

**平均提升：** 35% 更便宜、57% 更少 token、46% 更快、71% 更少工具调用

---

### 四、核心技术架构

```
┌─────────────────────────────────────────┐
│              Claude Code                │
│   "How does a request reach DB?"       │
│         直接调用 CodeGraph 工具          │
└──────────────────┬──────────────────────┘
                   │
                   ▼
┌─────────────────────────────────────────┐
│         CodeGraph MCP Server            │
│  context · trace · callers · callees   │
│  impact · explore                       │
└──────────────────┬──────────────────────┘
                   │
                   ▼
┌─────────────────────────────────────────┐
│          SQLite 知识图谱                 │
│  symbols · edges · files · FTS5全文搜索 │
└─────────────────────────────────────────┘
```

**三层架构：**
1. **提取（Extraction）**：tree-sitter 解析源码为 AST，提取节点和边
2. **存储（Storage）**：本地 SQLite 数据库
3. **解析（Resolution）**：将函数调用链接到定义、导入到源文件
4. **自动同步**：文件系统监视器（FSEvents/inotify）增量更新

---

### 五、核心功能

#### 1. 智能上下文构建
一个工具调用返回：入口点、相关符号、代码片段

#### 2. FTS5 全文搜索
按名称即时搜索整个代码库

#### 3. 影响分析
追踪任何符号的调用者、被调用者以及完整影响半径

#### 4. 框架感知路由
识别 14 种 Web 框架的路由文件，自动关联 URL 模式到处理器

| 框架 | 路由语法 |
|------|---------|
| Django | path(), re_path(), include() |
| Flask | @app.route() |
| FastAPI | @app.get() |
| Express | app.get() |
| NestJS | @Controller + @Get |
| Laravel | Route::get() |
| Spring | @GetMapping |

#### 5. 跨语言桥接
| 边界 | 桥接内容 |
|------|---------|
| Swift ↔ ObjC | @objc 自动桥接规则 |
| React Native 传统桥接 | JS NativeModules → ObjC RCT_EXPORT_METHOD |
| RN TurboModules | TS Codegen spec → Native 实现 |
| RN native → JS 事件 | 事件名通道 |
| Expo Modules | Swift/Kotlin Module DSL |
| Fabric/Paper 视图 | JSX → Codegen spec → 原生实现 |

---

### 六、安装使用

```bash
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/.../install.sh | sh

# 初始化项目
cd your-project
codegraph init -i
```

支持代理：**Claude Code, Cursor, Codex, OpenCode, Hermes Agent, Gemini CLI, Antigravity, Kiro**

---

### 七、关键特性

| 特性 | 说明 |
|------|------|
| **零配置** | 无需配置文件 |
| **100% 本地** | 数据不离机器，无需 API Key |
| **自动同步** | 文件监视器自动增量更新 |
| **20+ 语言** | TS/JS/Python/Go/Rust/Java/C#/PHP/Ruby/C/C++/ObjC/Swift/Kotlin/Dart 等 |
| **智能过滤** | 自动跳过 node_modules/vendor/dist 等第三方代码 |

---

### 八、MCP 工具一览

| 工具 | 用途 |
|------|------|
| `codegraph_search` | 按名称搜索符号 |
| `codegraph_context` | 为任务构建相关代码上下文 |
| `codegraph_trace` | 追踪两个符号之间的调用路径（含回调、接口动态派发） |
| `codegraph_callers` | 查找调用某函数的代码 |
| `codegraph_callees` | 查找某函数调用的代码 |
| `codegraph_impact` | 分析更改符号会影响哪些代码 |
| `codegraph_explore` | 返回按文件分组的多个相关符号 |
| `codegraph_files` | 获取索引的文件结构 |

---

### 九、亮之评述

#### 价值所在

1. **降低 AI 成本**：Token 和调用次数大幅减少，经济效益显著
2. **提升理解质量**：预索引的结构化知识比 Agent 自由探索更准确
3. **本地化优先**：隐私敏感场景下数据不离本地

#### 潜在局限

1. **维护成本**：需随代码变化保持索引新鲜
2. **增量挑战**：大型代码库的增量索引仍需时间
3. **跨语言桥接精度**：依赖启发式规则，极端情况下可能失效

---

臣等正欲死战，陛下何故先降！？

Explanation: Now I have a comprehensive understanding of CodeGraph. Let me analyze this project thoroughly.