Code Graph has three surfaces: a terminal IDE that opens when you run code_graph with no arguments, a CLI you run directly, and an MCP server your coding agent calls on your behalf. The CLI and MCP server share one on-disk graph snapshot.
Getting started
Install
Use the script installer. It installs two commands on your PATH: code_graph (CLI) and code_graph-mcp (MCP server).
Script installer
macOS, Linux, WSL, and other POSIX shells:
curl -fsSL https://cg.renso.ai/install.sh | sh
Windows PowerShell:
iwr -useb https://cg.renso.ai/install.ps1 | iex
The Windows script installs to %LOCALAPPDATA%\code-graph\bin by default and adds that directory to the user PATH. Open a new terminal after install.
First-run setup
After install, sign in from the CLI. The command opens the browser activation flow and stores the local token used by code_graph and code_graph-mcp.
code_graph auth login
Then register the MCP server with supported coding clients.
code_graph-mcp --register
The installer fetches the latest release directly. Use code_graph update to refresh the local commands; on Windows it stops running code_graph and code_graph-mcp processes before replacing the executable files.
First rebuild
From the root of any repository, build the graph:
code_graph rebuild
The first rebuild walks the whole tree. Subsequent rebuilds are incremental — only changed slices are re-indexed. Snapshots are written under .code_graph/snapshots/<id>/ with an atomic current.cg pointer.
To keep files out of rebuild input, add .codegraphignore (or its .cgignore shorthand) patterns using the same syntax as .gitignore, in any directory. Code Graph also combines .gitignore and honors all three in every directory of the workspace with the same precedence git applies — a nested file overrides a shallower one, sibling subtrees stay independent, and ! re-includes work at each level. It always excludes its own .code_graph/ storage directory, dependency caches, and secret-bearing files, and no nested rule can re-include them.
Changes to any ignore file — root or nested — and build-affecting profile settings invalidate reuse automatically, and the background updater picks up normal source changes without a local freshness command.
Tell your agent to use it
The rebuild makes the data; your agent still has to use it. Many tools handle this for you: the MCP server hands the client its own usage instructions on connect, so clients that surface those instructions need nothing more. But surfacing them is optional in the MCP spec — a server's instructions “MAY be added to the system prompt” — so whether your agent auto-loads Code Graph's guidance depends on the client, and can change between releases.
So this step is optional, and only needed if your tool doesn't surface MCP server instructions. When it doesn't, one line in your repo's AGENTS.md — the open standard every major coding agent reads — points the agent at the server instead. Rather than copying the usage steps in, it points at the MCP server's own instructions — the single source of truth — so the guidance stays current and there is no stale duplicate to maintain:
This repository uses Code Graph. Use its MCP server as the primary way to
navigate the code, assess the impact of changes, and validate them, and follow
the usage guidance the server itself provides.
Which tools actually need the line? We checked each major agent's public MCP docs. Tools that surface server instructions auto-load Code Graph's guidance the moment they connect; the rest still get its tools and slash-commands either way — the line just makes the agent prefer Code Graph from the first turn instead of discovering it mid-task.
Tool
Surfaces MCP server instructions?
This AGENTS.md line
Claude Code & Claude Desktop
Yes — loaded into context on connect
Not needed
VS Code + Copilot
Yes — a listed MCP capability
Not needed
OpenAI Codex
Yes — read at initialization
Not needed
Cursor, Windsurf, Zed, Continue
Not among their documented MCP capabilities
Optional booster
Any other tool
Run the test below
Add it if the test comes back blank
Not sure which case you're in? With Code Graph connected and no AGENTS.md line, open a fresh chat and ask the agent: "What standing instructions did the Code Graph MCP server give you?" If it can describe the start/finish dev cycle without being told, your tool surfaces server instructions and the line is optional. If it draws a blank, add the line.
Where this file lives depends on your client, but most coding agents also read a root AGENTS.md. See How agents use it for the per-tool table and extra standing-instruction snippets (such as the maintenance gate).
What gets stored
One graph holds everything Code Graph found in the repo:
Each snapshot also stores search data built from the same graph, including exact identifiers, signatures, doc text, and local recall records. See search.
Languages & formats
Code Graph indexes source in eleven languages and reads text from five document formats. Source files contribute symbols, imports, tests, and local relationships where confidence is high enough; documents contribute headings, prose, and cross-references to DocTree and search data. Files with an unrecognised extension are skipped, never guessed at.
Language
Extensions
Coverage
Rust
.rs
Deep workspace graph: modules, types, traits, functions, imports, re-exports, calls, dispatch, and tests.
Python
.py.pyw
Modules, classes, functions, imports, common tests, and local relationships where clear.
TypeScript
.ts.tsx
Modules, exported symbols, imports, UI components, common tests, and local relationships where clear.
JavaScript
.js.jsx.mjs.cjs
Modules, exported symbols, imports/requires, UI components, common tests, and local relationships where clear.
HTML
.html.htm
Page elements, linked styles, scripts, images, forms, and media.
CSS
.css.scss
Selectors, style rules, imports, custom properties, and asset URLs.
Go
.go
Packages, functions, methods, types, tests, examples, imports, and local relationships where clear.
Java
.java
Packages, classes, interfaces, enums, methods, common tests, imports, and local relationships where clear.
C / C++
.c.h.cc.cpp.cxx.hh.hpp.hxx
Namespaces, functions, methods, types, includes, and local relationships where clear.
Zig
.zig
Functions, public declarations, tests, imports, and local relationships where clear.
Clojure
.clj.cljs.cljc.bb
Namespaces, vars, functions, macros, records, protocols, tests, and imports.
Documents carry no symbols, but their headings, prose, and links join the DocTree and search index.
Format
Extensions
Coverage
Markdown
.md
Heading hierarchy, prose, code fences, and cross-references.
Jupyter notebook
.ipynb
Markdown/code cell sections and declared cell languages.
PDF
.pdf
Best-effort text by page; scanned files may be file-level only.
Word
.docx.doc
DOCX headings, paragraphs, and tables; legacy .doc may be file-level only.
Plain text
.txt.text.rst.adoc.log
Document sections and headings when detectable.
HTML is read twice: as a source language for its markup and resource references, and as documentation for prose and headings when it stands in for a written page.
Terminal IDE
Run code_graph with no arguments and it opens a full IDE inside your terminal — keyboard- and mouse-driven, with no desktop app and no tmux/screen/zellij multiplexer required. Every explicit command (rebuild, search, blast-radius, --help, …) keeps its exact behavior; only the bare invocation opens the IDE.
code_graph # open the IDE for the current directory
code_graph --workspace . # open the IDE for a specific workspace
The IDE needs an interactive terminal. If output is piped or redirected, code_graph does not fall back to printing help — it writes a one-line diagnostic that Terminal IDE Mode requires an interactive terminal and exits with code 2, without emitting a single alternate-screen control sequence into your pipe.
code_graph > out.log # error: Terminal IDE Mode requires an interactive terminal
Windows, macOS, and Linux are first-class — including SSH, WSL, and containers. The terminal is restored on a normal quit, on Ctrl+C, on transient terminal I/O failures, and even on a panic.
Columns & dock
The workspace is four mouse-resizable columns — threads, chat, code, and files — under a dock bar that toggles each one and opens a terminal or Settings. Drag any divider to resize; column visibility and sizes persist per workspace under .code_graph/ide/. The status surface stays deliberately small: an error/warning count and the current Git branch.
Files — an expandable directory tree with lazy loading; click or Enter to open a file.
Threads — one row per agent run, each with a single status icon and a live spinner while it works.
Chat — the agent transcript and the composer.
Code — editor, terminal, diff, and Settings tabs, all in one panel.
In Files, drag a file or folder row onto a folder to move it; hold Ctrl while dragging to copy. Dropping on a file row targets that file's parent folder, invalid drops are refused before any filesystem write, and name collisions open an Overwrite / Keep both / Cancel prompt. The same Move and Copy actions are available from the file context menu and from the focused Files column with m and c.
Every mouse action has a keyboard equivalent: Ctrl+1–Ctrl+4 toggle the four columns and Alt+← / Alt+→ resize the focused divider.
Editor & terminals
The code panel owns every tab. Files open as editor tabs; terminals run as tabs in the same panel — no separate pane, no multiplexer. The editor is a true editor core, not a wrapped text box:
When the code-panel tab row overflows, scroll over the tab row or use a horizontal trackpad wheel gesture to reveal more open tabs. Alt+Shift+← / Alt+Shift+→ switches to the previous or next tab from the keyboard. Visible tabs and close buttons remain clickable.
Editing — multiple open buffers, grouped undo/redo, mouse and keyboard selection, copy/paste, and find-in-file.
Highlighting & diagnostics — fast syntax highlighting that never waits on a language server, gutter marks, and the error/warning count in the status bar.
Never loses work — external-change detection offers reload, keep, or diff, and a dirty buffer is never silently overwritten by a change on disk; unsaved buffers are snapshotted to a recovery store under .code_graph/ide/.
Safe by default — large or binary files open read-only with an explicit reason instead of hanging the UI.
Terminals — real shell, command, and test sessions with bounded scrollback, resize propagation, and cancellation; open one from the dock or with Ctrl+5.
Settings opens as its own code-panel tab — theme (the Renso light palette, with a dark toggle), keymap reference, mouse mode, editor basics, and AI integrations — so configuration never sends you out of the workspace.
Composer & agents
The chat composer auto-expands from one line to six (then scrolls), and carries inline pickers for provider, model, reasoning strength — low, medium, high, max — and pipeline. Enter sends, Shift+Enter inserts a newline, and Esc cancels a running agent.
The pipeline picker defaults to No pipeline. Selecting the built-in default arms the IDE-hosted plan-to-verify skill pipeline for the next run; skill definitions stay in the IDE and are not written into the project tree or .code_graph/.
Run one or more agent threads from the chat, each using the provider and model you pick in the composer. Because the IDE is Code Graph, every thread works against the same repo map it builds for the CLI and MCP server — search, dependencies, and blast radius — so an agent can see what a change would touch, just as you can from the command line.
For Claude Code CLI sessions, the IDE passes per-run settings that refuse detached run_in_background: true Bash/Agent tool calls. Headless runs wait in the foreground instead of leaving background work behind; use Esc or Stop to cancel the running agent.
When available for the selected CLI provider, Terminal IDE can keep one live provider process per thread instead of launching a fresh CLI for every message. Providers without live-session support continue in one-shot mode. The chat header shows a ● connected indicator once a CLI-backed thread is using a live stateful session (click it for details); one-shot providers show no indicator. The dock status bar carries concise notes for session start, fallback, setting changes, and transcript restore after a crash or idle timeout.
Stateful continuity is best-effort runtime state inside the IDE — it does not survive IDE restart. After a crash, idle timeout, or provider-setting change, the next turn restores from the persisted transcript (with the same compaction path one-shot mode uses), not from the previous live process. Idle sessions close after 30 minutes by default; override with CODE_GRAPH_IDE_CLI_SESSION_IDLE_SECS (seconds), and cap live sessions with CODE_GRAPH_IDE_CLI_SESSION_MAX (default 8).
For Codex, Terminal IDE includes a live Codex connection path for CLIs with a compatible app-server command. When feature detection succeeds, Codex uses that live connection by default and can steer mid-turn follow-ups into the active turn; if app-server is unavailable or unhealthy, Codex falls back automatically to the existing one-shot path and queues mid-run follow-ups for the next turn. Detection runs in the background at IDE startup so sending a message never blocks the UI. Set CODE_GRAPH_IDE_CODEX_APP_SERVER_ROLLOUT=0 to force one-shot mode temporarily while investigating provider issues.
Skill execution uses the same contract on API and CLI providers. Direct API providers use structured skill tools, live CLI sessions run one skill per turn, one-shot CLIs run one process per skill, and prompt-only fallback is labeled as approximated. Settings → AI Providers shows the mode and delivery channel for each connected provider from the same capability snapshot the dispatcher uses.
AI integrations
Settings separates two kinds of integration and discovers both for you:
Auto-detected CLI tools — Claude Code, Cursor, Codex, and Grok are found on your PATH when installed.
Paste-a-key API providers — paste a key and the provider is ready; Cursor is available as a provider too.
Model lists come from the selected tool or provider automatically — there is no model catalog to hand-edit. Provider keys are written with the safest platform-local credential store available and live in your user config directory, never inside the project tree or .code_graph/ — so a key can't leak into a file your VCS or a coding agent would read.
Language-server diagnostics are runtime-auto: when you open a supported file, the IDE starts the matching local language server if the command is available on that machine (for example rust-analyzer). Set CODE_GRAPH_IDE_LSP=0 to disable this, or =1 to force the same runtime path.
Key bindings
The in-app Settings → Keyboard Commands list is the source of truth; these are the essentials. A keyboard equivalent exists for every mouse action.
Action
Keys
Toggle Threads / Chat / Code / Files
Ctrl+1 … Ctrl+4
Open the terminal
Ctrl+5
Resize the focused column
Alt+← / Alt+→
New file · close tab
Ctrl+N · Ctrl+W
Previous / next code-panel tab
Alt+Shift+← / Alt+Shift+→
Save / save all
Ctrl+S / Ctrl+Shift+S
Undo / redo
Ctrl+Z / Ctrl+Y
Copy / paste / cut a selection
Ctrl+C / Ctrl+V / Ctrl+X
Move / copy the selected file-row item
m / c in Files
Select all
Ctrl+A
Find in file
Ctrl+F
Command palette
Ctrl+K
Open Settings
Ctrl+,
New chat thread
Ctrl+T
Cancel the running agent
Esc
Quit
Ctrl+Q
On macOS the ⌘ (Command) key works in place of Ctrl for these shortcuts, so ⌘C / ⌘V / ⌘X / ⌘A copy, paste, cut, and select all — copy a chat-history or editor selection with the standard Mac shortcut (⌘C only ever copies; it never quits). The ⌘ shortcuts need a terminal that supports the keyboard-enhancement protocol — iTerm2, kitty, WezTerm, Alacritty, and Ghostty all do — which code_graph turns on automatically when the terminal advertises support.
MCP server
code_graph-mcp speaks Model Context Protocol over JSON-RPC stdio. Most tools are read-only. The managed-policy tool also mutates — every write is atomic, dry-run-aware, and routes through the same writer the CLI uses.
Client setup
On first run, code_graph-mcp --register adds the server to the global (user-level) launcher config of whichever clients it finds on the machine — so it works in every repo, not just one. The registered command uses --workspace ., so each launch scopes itself to that client process's current project directory.
To remove it later, code_graph-mcp --unregister deletes the code_graph entry from those same clients, leaving every other server untouched. Add --dry-run to preview either command before it writes anything.
Detect installed clients and merge the standard code_graph server entry.
code_graph-mcp --register
Claude Code (the CLI agent) keeps user-scoped MCP servers in ~/.claude.json. Auto-register adds it through Claude Code's own CLI at user scope — global, across all your projects — when Claude Code is installed. To do it by hand:
claude mcp add --scope user --transport stdio cg -- code_graph-mcp --workspace .
Claude Desktop uses claude_desktop_config.json. The auto-register command writes this entry when Claude is installed.
Cline stores MCP servers in cline_mcp_settings.json under the VS Code extension's globalStorage (…/globalStorage/saoudrizwan.claude-dev/settings/), with servers under mcpServers. Auto-register merges this entry when the Cline extension is present.
Codex reads MCP servers from ~/.codex/config.toml as a [mcp_servers.cg] table — not a JSON file. Auto-register merges this table (keeping your other servers and settings) when ~/.codex exists.
Zed stores MCP servers in settings.json under context_servers (~/.config/zed/ on macOS and Linux, %APPDATA%\Zed\ on Windows). Auto-register merges this entry when Zed is installed.
VS Code reads mcp.json from your user profile (Code/User/mcp.json), with servers under servers and an explicit "type": "stdio". Auto-register writes it when VS Code is installed.
Continue uses a YAML config at ~/.continue/config.yaml, where mcpServers is a list (each entry has a name). Auto-register appends the block to that file when it already exists, without touching your existing settings or comments — it won't create a config from scratch, so Continue must already be set up. If you already keep an mcpServers list (or only a legacy config.json), it's left untouched; add this entry yourself. MCP servers are only used in Continue's agent mode.
Grok Build (xAI's terminal coding agent) reads MCP servers from ~/.grok/config.toml. Auto-register adds this table when that config file already exists — it won't create one from scratch. Grok Build also imports Claude Code's MCP config, so a Claude Code registration is picked up there too.
Most Code Graph tools are read-only — navigation, impact, and validation never change your code. They advertise the MCP readOnlyHint annotation, so clients that honour it can run them without an approval prompt. The fewer prompts an agent hits, the more it actually uses the tools. In Claude Code you can opt in explicitly by allow-listing the read-only tools in .claude/settings.json (per project) or your user settings:
These six are read-only. The tools that can write — rebuild, plan, feature, and the managed-policy registries — are intentionally left off so writes still prompt; each also accepts dry_run for a no-write preview. Cursor, Cline, and other clients have their own auto-approve settings.
The server resolves the analyzed workspace from --workspace <path>, falling back to the process working directory when the flag is omitted. The standard entry uses --workspace ., so the current project directory is explicit without hardcoding an absolute path. Launch from the intended project directory or pass an explicit workspace path; don't inject environment variables. Known CODE_GRAPH_* and RDB_* variables are scrubbed before each child code_graph call.
The sixteen tools
plan adds local execution plans and ordered to-dos for resumable development tasks; dev_cycle can use a plan_id at phase=start to read persisted to-do decisions when resuming work. Execution-plan guidance appears only when the scope is multi-step, public, shared, resumable, or otherwise high-risk.
Each tool takes an action field plus whatever that action needs, and its description carries per-action when/why guidance so an agent can pick the right endpoint from the tool list alone. dev_cycle leads the catalog as the lifecycle entrypoint; context also exposes workflow_guide, a structured roadmap for common MCP flows. Successful calls return a short text status and parsed JSON in structuredContent; large drillable views such as blast-radius return the selected summary, focus page, or path slice unless full detail is requested. The authoritative CLI⇄MCP map is in the MCP server guide.
One server per workspace.code_graph-mcp runs one shared server per canonical workspace, shared by every agent on that project. The first launch wins a cooperative lease and serves every agent over a local socket; later launches for the same workspace bridge to it instead of starting another process. Launches for different project directories get different main servers and endpoints. Each connection still gets its own isolated session; runtime scoped-context handles are cached for the workspace so follow-up traversal works after a reconnect or MCP process restart. The server stays up while at least one connection remains open, then exits after a short grace once every connection has closed and no rebuild is running or queued. A crashed server is reclaimed automatically by the next launch, and code_graph --workspace . mcp status reports whether one is running.
Call phase=start before beginning a task to get the right pre-work for the chosen intent. Use code_graph as your guide for everything — it is opt-out, not opt-in, so lean on it by default for every code change: check for code to reuse (search/context) and what depends on your target (blast_radius) before editing, and only skip a self-contained edit. Guidance is tailored to what the user is asking for — feedback (review), plan (approach), research (investigation), question (answer), or software development work (change the repo); pass intent to set it, or it is inferred from task_summary. Advisory modal change questions such as "would you change anything?" or "should we change this?" are treated as feedback. It composes task routing and workflow recipes and never runs commands or edits files. dev_cycle is start-only: it does not offer phase=finish and does not return context-window closure gates (continue_if / required_before_final). Run recipe tool calls such as preflight, affected_tests, and validate directly when you need them.
Ask for workflow recipes, search code/docs before grep/ripgrep, build a bounded context pack for one entity or file, outline one file's entities, or walk DocTree structure. Query context promotes matching document sections into entries and avoids repeating them again in the search-hit list. search and context use the available search data by default, so intent phrased differently than the code can still surface relevant records. Nothing to enable: no flag, no extra tool.
Walk the graph from a change to everything it touches, check whether one entity sits on an entry-point path with direct test coverage, request a bounded call path, or ask for dependency rows with bounded provenance. Blast-radius structured responses are view-scoped and include concrete focus, path, tree, and cursor drill guidance in the text preview. Stale search data is reported as guidance to wait for background refresh and retry, not as a rebuild command.
Read the feature catalog, validate @feature tags, see the resolved tagging guide, and mutate the committed feature registry (deterministic and byte-identical to the CLI).
Run the trust verdict, validators, and report cards: index health, chunk health, contracts, missing links, and a bounded quality-dashboard summary. With write, the full dashboard is persisted and the summary returns its path. Stale trust next-actions point agents at background refresh/retry rather than forced rebuilds.
rebuild remains available as a compatibility snapshot operation surface and for inspecting partial rebuild plans. Agent development workflows should rely on the shared server's background updates for freshness rather than calling it as a local refresh step. partial_rebuild_plan is read-only and explains what would be reused or updated before writing a new snapshot.
sessionpin a snapshot · anchor a task · check drift
Keep an agent's "search → context → impact → edit" loop on one snapshot even when a parallel rebuild swaps the active one (see session pinning). It also records the task you're working on, so search data can flag when the code you're touching has drifted off-task — a hint, never a block.
planlocal execution plans · ordered to-dos · resume work
Record development execution plans, peer-review feedback, ordered to-dos, evidence, command summaries, and remaining work. This is task execution memory, not generic project management. Read actions return structured content; mutating actions support dry_run. add can set seed_todos with known targets to create an initial ordered to-do list from current search data. list and search support status/date filters and return newest-first results. check reports stale plan links without deleting them, and inactive plans are pruned oldest-first above the retention cap while active work is preserved.
Slim read-only aggregator over the six managed policy surfaces. Two actions: status (which surfaces are configured in this workspace) and list (surfaces + the verbs each supports). To read or change a specific surface, use its own tool below.
{ "action": "status" }
{ "action": "list" }
coordinationread-only write-coordination diagnostics · no acquire/release
Inspect inline write coordination. Coordination is automatic and inline — every code_graph-owned mutation locks, re-reads, commits atomically, and releases inside the operation, so permission to write is never delegated to the caller and there is no acquire/release/lock action. status reports held internal locks and recorded resource versions; conflicts reports active write contention; explain reports the write scope for a registry surface or generated doc path; check reports possibly-stale internal locks. When a mutating tool hits contention it returns a structured { "kind": "write_conflict" | "stale_write" | … , "retryable": … } object as content, not a transport error.
Six per-surface registry tools, all the same shape as feature: read + validate + mutate, with dry_run on every mutating action. Lifecycle transitions are named verbs, never --status: accept/reject/deprecate/supersede on ADRs; deprecate/reactivate on invariants. Attach/detach is always link/unlink. Delete is remove. The record id is the first positional argument.
Landmines are tripwires, not tickets — there is no resolved status. A landmine is addressed by link-ing its recurrence guard (invariant/test/ADR) and stays in place as the institutional-memory signal. It leaves the registry only via remove, and only when invalid or obsolete.
When an MCP session first reads the graph, the server writes a pin file under .code_graph/snapshots/sessions/<session_id>.json. index-prune won't garbage-collect a fresh pinned snapshot, so the agent keeps reading the same view even when a concurrent rebuild moves current.cg.
Background updates and compatibility rebuild operations repin the calling session when applicable. Call {"action": "repin"} manually when a session intentionally needs to move to a newer active snapshot. Pins are per connection and expire with the MCP session TTL; stale pins are removed by server cleanup or ignored by snapshot pruning.
Managed policy registries
Each of the six committed policy surfaces Code Graph already validates — ADRs, layer policy, the quality baseline, landmines, invariants, the doc-symbol allowlist — gets its own MCP tool, all the same shape as feature: read + validate + mutate, with dry_run on every mutating action. manage is the slim read-only cross-surface aggregator (status/list only).
Lifecycle transitions are named verbs, never a --status flag. ADRs flow proposed → accepted → deprecated (or superseded); invariants flow active ↔ deprecated via deprecate/reactivate. Landmines have no resolved status — they are tripwires, addressed by link-ing their recurrence guard (an invariant/test/ADR) and kept as institutional memory.
// Cross-surface read-only aggregator
{ "tool": "manage", "action": "status" }
// One tool per surface — bare verbs (the tool name carries the surface)
{ "tool": "adr", "action": "add",
"title": "Snapshot Activation Is Atomic", "dry_run": true }
{ "tool": "adr", "action": "accept", "id": "ADR-0007" }
{ "tool": "invariants", "action": "add",
"statement": "snapshot activation is atomic" }
{ "tool": "invariants", "action": "link", "id": "CG-INV-001",
"sites": ["crates/code_graph/src/platform/snapshot.rs"],
"tests": ["snap_atomic"] }
{ "tool": "landmines", "action": "link", "id": "LM-0001",
"related_invariants": ["CG-INV-001"] } // address by linking its guard
{ "tool": "landmines", "action": "remove",
"id": "LM-0099", "dry_run": true } // preview-then-write
All writes route through the same atomic, deterministic registry writer the CLI uses, so an MCP-originated change is byte-identical to its CLI equivalent. The files are committed — git is the audit trail. Records are targeted by id only (no fuzzy match); every mutating call accepts dry_run to preview the diff and write nothing.
CLI
The CLI builds the graph and is also a perfectly good way to query it directly. Run code_graph --help for the full flag list.
rebuild
Build (or incrementally update) the snapshot. Pick a profile to tune rebuild speed, memory, and response budgets.
Repos with many documents (PRDs, ADRs, notebooks).
large-monorepo
Huge repos: bounds rebuild memory, enables workspace-hygiene guidance, defers optional search data under pressure.
mcp-low-token
Tighter response budgets for token-constrained agents.
secure
Aggressive redaction.
Flag
Effect
--diagnostics
Print a bounded report after the rebuild: per-stage wall time and peak resident memory, the slowest stage, input census by category, artifact sizes, reuse outcomes, parser/slice/revision-cache counters, search data details including reused/computed record counts, carried-forward semantic records, bounded timing buckets, sharded payload counts and physical-write accounting when an internal sharded snapshot is used, and top cache-miss reasons. The source-free structured form is always written to rebuild-diagnostics.cg.
--quick
Low-latency local mode: always publishes graph + DocTree, reuses search data when safe, and defers optional search data until a later rebuild.
--memory-budget-mb N
Cap rebuild memory. Lowers the search-writer buffer and worker count and defers optional search data under pressure. Overrides CODE_GRAPH_REBUILD_MEMORY_MB and the profile default; a conservative system-memory default applies otherwise.
Ignore files — root or nested — and build-affecting profile settings are part of rebuild input. When they change, Code Graph bypasses stale reuse automatically. Performance Pass 1 reuse and diagnostics are enabled by default; set CODE_GRAPH_PERF_PASS_1=0 to roll back the full pass, or CODE_GRAPH_PERF_PASS_1_PARSER=0, CODE_GRAPH_PERF_PASS_1_SLICES=0, or CODE_GRAPH_PERF_PASS_1_REVISION_CACHE=0 for a narrower opt-out. Performance Pass 2 extends rebuild diagnostics with dirty-set attribution, changed-key search and semantic counters, graph publishing sub-stage timing, dashboard refresh metadata, and memory attribution; set CODE_GRAPH_PERF_PASS_2=0 to roll back the full pass or disable individual sub-gates such as CODE_GRAPH_PERF_PASS_2_SEARCH_DELTA=0. A deferred dashboard is stamped freshness=stale; run a full rebuild or quality-dashboard --write before trusting floor verdicts. If another rebuild already holds the workspace lock, rebuild queues one follow-up rebuild and exits successfully; additional requests return success while that follow-up is already queued. Full-slice rebuild is an explicit maintenance override; agent freshness should come from background updates. Under --diagnostics or the large-monorepo profile, the rebuild also prints workspace-hygiene guidance — the top avoidable input categories (generated, vendored, fixtures, coverage, build output, large docs) and suggested .codegraphignore entries. Hygiene suggestions are local-only and never sent as telemetry.
When default-profile inputs are proven stable, the dashboard can be carried forward as mode=carried_forward freshness=current.
search
Search across code, docs, features, sections, and supported-language symbols. Results use the available search data and keep exact matches first-class. Additional candidates are not treated as source-of-truth evidence.
Intents: general, implementation, tests, docs, feature, endpoint, config. Entity hits include bounded signatures when available. Empty results include suggestions for filters to relax, simpler identifier fragments, nearby IDs when a relaxed lookup finds candidates, and a DocTree search follow-up. Hits also include compact retrieved_by and exact_id_match fields. Add --explain to see match reasons, the active rebuild profile, and which search data contributed each hit.
blast-radius, reachability, and path
Walk downstream from any entity or file, starting with a summary by default: severity, roll-ups, public surfaces, tests, bottlenecks, and capped sections. Use --detail full for the complete listing, or drill with --focus, --path-to, --tree, --depth, --page-size, --cursor, and --covered. JSON output is view-scoped: summary JSON contains rollups and cutoff guidance, focus JSON contains only the requested page, path JSON contains only the requested path, and --detail full --format json returns the full parsed blast-radius payload. Pair blast-radius with --explain when you need per-edge provenance and confidence. Use path --from <id> --to <id> for bounded forward call paths with relation kinds and available provenance. Reachability coverage uses tiered test attribution.
Bounded LLM context for one entity, file, or query. Includes direct deps, reverse deps, affected crates and tests, endpoints, features, docs, and small source snippets. file-outline returns a line-sorted bounded summary of entities defined in one file.
Walk entities by kind, then trace forward or reverse dependencies. Add --with-provenance for bounded relation evidence with file/line snippets.
code_graph list --kind function --limit 20
code_graph list --kind cli --format json
code_graph deps StorageEngine
code_graph deps StorageEngine --with-provenance --limit 10
code_graph rdeps StorageEngine --with-provenance --limit 10
Accepted kinds include crate, module, file, trait, struct, enum, function, test, endpoint, config, cli, env, doc, section, feature, and schemafield.
preflight · affected-tests
Run before opening a PR. preflight rolls up impact across a set of changed files; affected-tests prints the test command that covers them, using tiered test attribution by default. Set CODE_GRAPH_BROAD_TEST_EDGES=1 only when comparing against legacy broad coverage. change-summary --format both returns review Markdown and the structured summary from one command execution.
trust gives agents a compact ok/stale/inconsistent/drift verdict before they rely on other generated-data reads. Stale verdicts tell agents to wait for background refresh and retry, not to force a rebuild. findings-baseline records known advisory findings so follow-up runs can show only new work.
A clean absence-based report is useful evidence, not proof of runtime wiring. Pair it with trust, reachability, and focused tests.
plan
Record local execution plans for development tasks: task summary, selected recipe, ordered to-dos, review feedback, evidence, command summaries, and remaining work. Plans are for task resume and finish verification, not generic project management.
code_graph plan add --title "Implement plan-driven dev cycle" \
--task-summary "implement the plan-driven dev cycle PRD" \
--selected-recipe mcp_surface_change \
--target-file crates/code_graph_mcp_core/src/lib.rs \
--status reviewing --dry-run
code_graph plan add --title "Update impacted surfaces" \
--target-file crates/code_graph_mcp_core/src/lib.rs \
--seed-todos
code_graph plan todo-add PLAN-0001 --title "Wire plan MCP tool"
code_graph plan review PLAN-0001 --feedback "required: add docs-sync coverage"
code_graph plan todo-done PLAN-0001-TODO-0001 \
--evidence "cargo test -p code_graph_mcp_core dev_cycle" \
--decision preflight=done
code_graph plan check --format json
plan add --seed-todos creates an initial ordered to-do list from known targets and current search data. plan list and plan search support status/date filters and return newest-first results. Inactive plans are pruned oldest-first above the retention cap; active work is preserved.
manage
Manage the project-local policy surfaces from the CLI. The same atomic writer used by the MCP manage tool.
code_graph manage status
code_graph adr add --title "Snapshot activation is atomic"
code_graph invariants add --id CG-INV-001 \
--statement "snapshot activation is atomic"
code_graph invariants site CG-INV-001 --path crates/code_graph/src/platform/snapshot.rs
code_graph landmines import design/landmines.md
code_graph quality-baseline accept --reason "new language coverage"
feature tagging
A feature tag ties code and docs to a named product feature. You annotate a surface with @feature(prefix::slug); on rebuild Code Graph resolves each tag to the nearest entity and adds FeatureTaggedBy edges — so a feature maps back to exactly the code and docs that implement it, and that mapping shows up in search, context packs, and the Features dashboard.
Tag a surface
Put the tag in a comment just above the surface it describes. The prefix is usually a phase (phase-9::search) but can be any domain prefix (billing::licenses).
// @feature(phase-9::search) Rust item — within 5 lines of the item
//! @feature(phase-9::search) Rust module (inner doc comment)
# @feature(phase-9::search) other languages — native comment above the surface
<!-- @feature(phase-9::search) --> Markdown — near the documented feature
Tag primary public surfaces — functions, structs, enums, traits, frontend modules, style rules, markup elements, config keys, CLI commands, env vars — not every helper. In non-Rust files the tag binds to the nearest supported entity within ten lines, then falls back to the file.
Declare the valid tags
Tags are validated against a committed registry — the source of truth — in .code_graph/registry.cg (or a checklist heading marked <!-- code_graph: feature -->). A declared tag is an explicit feature; a tag that isn't declared anywhere surfaces as an inferred candidate so a typo never silently mints a feature. New features default to status planned.
The MCP equivalent is the feature tool (catalog to read, check_tags to validate, catalog_add to declare) — your agent can keep the registry in sync without leaving the editor.
How it maps back
Once resolved, features are first-class graph entities and surface everywhere:
Context packs — context-pack --intent feature pulls a feature's code, docs, and tests together.
Features dashboard — checklist, status, evidence, and the code/docs each feature is tagged on.
DocTree & chunks — generated code nodes carry feature_ids / feature_tags so retrieval is feature-aware.
The feature index is a registry under .code_graph/; Code Graph never writes a copy into your source tree.
How your coding agent uses tags
Feature tags are one of the highest-leverage signals an LLM agent has, because they record intent the call graph can't recover on its own. Through the MCP server your agent will:
Scope a task to a feature — feature (action=dashboard / catalog) lists features and the exact code, docs, and tests tagged to each, so the agent loads just the relevant working set instead of grepping blind.
Retrieve feature-aware — context with intent=feature (search and context packs) ranks by feature membership, and generated nodes carry feature_ids / feature_tags so retrieval follows the feature, not just the text.
Keep tags honest — the agent runs feature action=check_tags to catch unknown tags, likely typos, inferred candidates, and untagged explicit features, then action=catalog_add to declare a new feature. The action=tagging_guide response hands it the exact syntax and placement rules, so it tags new surfaces correctly without a human spelling them out.
Every one of these reads or writes the committed .code_graph/registry.cg registry deterministically (byte-identical to the CLI) — the agent never mints a parallel source of truth or writes outside .code_graph/.
Tags make runtime-wired code first-class
Code Graph resolves structure statically — it never runs your code. It now records the decorators a Python symbol carries, but it still can't know that a web framework will dispatch requests to a @app.route handler, that a plugin is loaded by name, or that a method is conjured by metaprogramming — those bindings only exist at runtime. A feature tag is the escape hatch: annotate the surface with @feature(prefix::slug) and it becomes first-class in search, context packs, and impact analysis, so both you and your agent can find it even when no static edge points at it.
snapshots & rollback
Every rebuild writes a new snapshot directory and atomically swaps the current.cg pointer. Concurrent rebuild requests coalesce into one queued follow-up rebuild and return success instead of racing. Large generated snapshot artifacts are stored as opaque payload bundles under generic d/<hex>/<digest>.cg paths when they exceed the sharding threshold, while logical artifact names continue to resolve through the manifest. You can list, diff, prune, or roll back without touching the build cache.
index-prune reports stale session pin files it sweeps while evaluating retention; JSON output exposes the same list as stale_session_pins. Search data writes retry transient filesystem or index-writer failures with exponential backoff; use CODE_GRAPH_SEARCH_BUILD_RETRIES and CODE_GRAPH_SEARCH_BUILD_RETRY_BASE_MS to tune the retry policy.
Trend history is kept outside snapshot directories under .code_graph/trends/trends.jsonl, so rollback never loses it.
How agents use it
The agent loop
The terse way to begin a task is dev_cycle: call phase=start at the top and follow its recommended_next_actions. Under the hood it composes the same primitives below — a coding agent can also call them directly, starting with context action workflow_guide to get structured recipes such as endpoint_impact, entity_impact, pre_edit, diff_impact, post_edit_validation, and maintenance. The usual edit loop then maps to MCP tools before shell grep/ripgrep.
1
Plan and search
context with action: "workflow_guide" picks the workflow; action: "search" finds the entry points relevant to the user's request.
2
Context
context with action: "context_pack" returns a bounded set of related entities, tests, docs, and source snippets.
3
Impact
Before proposing an edit, impact with action: "blast_radius" tells the agent which parts of the system would be affected. Pass start_line/end_line when the target line range is known, or worktree/since to seed from changed diff hunks (workflow_guide topic diff_impact).
4
Verify
After the edit, impact with action: "affected_tests" gives the agent the exact test command to run.
Across the whole loop, the agent calls session with action: "current" once to pin a snapshot, so reads stay consistent.
Maintenance gate
One workflow_guide topic is built for your dev cycle rather than a single edit: maintenance (see the sixteen tools). It returns a read-only validation recipe that keeps Code Graph's registries, ADRs, and feature tags reconciled with the code while background updates handle search-data freshness. Rather than relying on a human to remember it, add a standing instruction to your agent's rules file so the agent fetches and runs the guide itself, the same way it runs the edit loop above.
Drop one of these into that file — phrased as a recurring step in your dev cycle:
## Code Graph maintenance
This repo is indexed by Code Graph. Keep that index reconciled with the
code: periodically — and always after a large refactor or before a release —
call the `context` MCP tool with:
{ "action": "workflow_guide", "topic": "maintenance" }
Then carry out the read-only validation recipe it returns and remediate any
findings with the per-surface tools the guide names before moving on.
…or as a final gate check, before work is reported done:
## Definition of done: Code Graph maintenance gate
Before reporting any task complete, call the `context` MCP tool
with:
{ "action": "workflow_guide", "topic": "maintenance" }
Follow the returned recipe end to end and treat every unresolved gate finding
as blocking — fix it with the per-surface tool the guide names, or state why
it is acceptable, before you consider the work done.
Where that file lives depends on your client. Most coding agents read a root AGENTS.md, so writing it once there covers every tool below:
Platform
Where it reads standing instructions
Their docs
Any (recommended)
root AGENTS.md — the open standard every tool below reads
its custom-instructions / rules / system-prompt file
the tool's own docs
Editors change these paths and their precedence often, so we link each tool's own docs rather than mirror them here. Put the instruction wherever your agent reads standing project instructions — and when in doubt, a root AGENTS.md is the most portable choice, since every tool above already reads it.
Local-only mode
Indexing, search, blast radius, and MCP serving all run locally against the on-disk snapshot. Source code never leaves the machine. The control plane only sees:
License heartbeats — to confirm the seat is still paid.
Anonymous, hashed snapshot fingerprints — to power optional cross-machine pinning.
Numeric aggregates (node count, edge count, rebuild duration) — for quota and trend reporting.
That's the full surface. No file contents, no symbol names, no commit messages.