gograph
Give Go coding agents a compiler-aware map for safer refactors.
gograph builds a local structural graph of your Go repository, with optional
type-checked CHA/SSA enrichment. Its CLI and MCP workflows help coding agents
trace callers and interface implementations, plan change impact, and enforce
architecture without embeddings or a hosted code index.
Try the verified no-install demo · Review the reproducible benchmark

Static analysis; no target-code execution. Default indexing parses Go source locally and does not call application services. Descendant links and special files for extensions recognized by
go/buildare excluded, graph-directed source reads are confined to regular files beneath the analyzed repository, and linked/non-regular Go tool metadata (go.mod,go.sum,go.work,go.work.sum, andvendor/modules.txt) is rejected before toolchain invocation; an explicitly symlinked repository root remains supported. Applicablego.work usemembers must stay beneath the workspace directory, and each member directory,go.mod, and optionalgo.sumis validated beforecmd/gostarts. Gograph also reads project metadata such as.gitignore, graph/config JSON, and Git state. Indexing asks the installed Go toolchain for the effective build/module context; precise mode additionally performs package type loading, anddocrunsgo doc. Those operations follow your configured module/cache/network policy. Before repository package loading orgo doc, applicable local module/workspace source trees are preflighted for links thatcmd/gomay inspect;.gitand.gographsubtrees are excluded. Session telemetry is local under.gograph/sessions/; nothing is sent to gograph services.
Quick Start
# Install
brew install ozgurcd/tap/gograph
# or: go install github.com/ozgurcd/gograph/cmd/gograph@latest
# Build a fast AST graph, then verify it
gograph build .
gograph stats
# Start with repository-wide results that require no guessed symbol
gograph summary
gograph hotspot --top 5
gograph flow --no-tests
Homebrew and go install install the normal gograph CLI. MCP clients that
support MCP Bundles can instead discover the local stdio server in the
official MCP Registry as
io.github.ozgurcd/gograph. Registry/MCPB installation is a separate
distribution path; it does not install the Homebrew formula or configure the
Claude Code marketplace plugin. The Registry is currently in preview. See
Official MCP Registry and MCPB installation for client
support, target selection, and current limitations.
Choose a real function or method shown by summary, hotspot, or
gograph complexity, then substitute its name below:
gograph context "YourSymbol" # source + callers + callees + tests
# For compilable repositories, enrich the graph before a major refactor
gograph build . --precise
gograph plan "YourSymbol"
Build artifacts are written under the target .gograph/ directory. gograph
adds .gograph/ to the enclosing Git repository root .gitignore when
available, falls back to the build target .gitignore outside Git, and exits
without replacing artifacts if no Go files are found or no source file parses
successfully. The update accepts only an absent or regular .gitignore; a
repository-provided link is refused and its target is not modified. Go build
constraints, cmd/go package-directory rules, generated
sources, module-mode ignore directives, and Git ignores use the same scanner
policy for building, freshness checks, and change detection. Source-file
symlinks and other non-regular .go entries are reported and excluded;
linked/non-regular go.mod, go.sum, go.work, go.work.sum, and
vendor/modules.txt entries are rejected before gograph or the Go toolchain
reads them. Applicable go.work use members must remain beneath the workspace
directory; their directories, go.mod, and optional go.sum are validated
before cmd/go starts.
.gograph itself must be a real directory, and graph.json must be a regular
repository-confined file. Graphs with a missing or unsupported confinement
policy marker must be rebuilt with the current binary before graph-backed
commands use them. Older binaries do not enforce this boundary and should not
be used to analyze untrusted repositories.
MCP refreshes stay in memory by default. To publish each successful refresh for CLI consumers and later server processes, start the server explicitly with:
gograph mcp . --persist-refresh
This opt-in mode writes or overwrites .gograph/graph.json and the nine
Markdown reports after a confirmed-fresh refresh. It does not modify
.gitignore, so ignore .gograph/ yourself before enabling it when needed.
The directory holds only the latest published state; it is not a per-branch
cache. If no usable graph exists (including an unsafe or unsupported artifact),
the startup auto-build is published before serving;
a failure there prevents startup. A later tool-triggered publication failure
makes that tool return an error, and the server retries the pending publication
on another refresh-capable call without rebuilding the already-fresh in-memory
graph. Writers coordinate through a local .gograph/.artifacts.lock file; an
existing lock entry must be regular rather than a link or special file.
Reports are replaced first and graph.json is replaced last as the publication
commit marker; the complete ten-file bundle is not a single atomic filesystem
transaction. Same-directory replacement is atomic on Unix-like systems; Go
does not guarantee atomic rename semantics on non-Unix platforms. The lock
file remains as operational coordination state in addition to the ten outputs.
Why gograph?
Illustrative point-in-time output comparison from an earlier gograph revision (counts vary as the repository evolves; these commands return different kinds of evidence):
| Task | grep -rn | gograph | Observed output difference |
|---|---|---|---|
Find callers of loadGraph | 158 matching lines (comments, docs, vars) | 56 AST-derived call-site rows | ~65% fewer rows in that run |
| Locate symbol definitions | 842 lines matching "Symbol" | 83 true type/method declarations | ~90% noise eliminated |
| Read one function body | cat displays 180+ lines of the whole file | source extracts the 12-line function | ~93% fewer source lines in that run |
| Gather common symbol context | Separate node, source, caller, callee, and test queries | context bundles those fields | Five evidence types in one response |
Key Features
61 Query, Analysis, and Workflow Capabilities — callers, callees, impact, context, plan, review, flow, errorflow, orphans, hotspot, coupling, and more. The MCP server registers 65 endpoints including four session lifecycle tools. Full command reference →
Native MCP Server — query, analysis, and workflow capabilities have MCP equivalents for Claude, Cursor, Copilot, and other MCP clients. Host/build operations (build, gate, snapshot, plugin/hook installation, server startup, help, and version) intentionally remain CLI-only, and transport-specific presentation differs where appropriate.
Explicit Freshness Model — CLI graph-backed analysis reads the last trusted persisted graph. gograph stale is a tri-state predicate in text and JSON modes: exit 0 means current, 2 means stale, and 1 means an operational or JSON serialization error; a missing or unsupported source-policy marker is an explicit status-1 rebuild requirement. MCP source-analysis tools check freshness per call, adopt a newer persisted precise graph, and rebuild in memory after edits using the latest requested analysis mode. MCP stale, default changes, and stats inspect the trusted persisted snapshot, or the startup auto-build fallback when no usable artifact exists. With --persist-refresh, that snapshot advances after a successful refresh, so default changes compares against the newly published state and normally no longer reports that refresh's source edits.
Compact Composite Workflows — context, plan, and explain combine source and graph evidence that would otherwise require several separate queries. Actual tool-call and token savings depend on the repository and task.
Narrow by Design — never runs target repository binaries or tests and does not intentionally scan .env, key, certificate, or credential files. Descendant links and special files for recognized Go build inputs are excluded; on-demand source and snippet reads use a repository-rooted filesystem handle and accept only regular .go files without symlink components. Linked/non-regular Go module/workspace metadata, sums, and vendor/modules.txt are rejected before toolchain use. Applicable workspace members must stay beneath the workspace directory, and their directories plus module metadata are preflighted before cmd/go. Default/relative policy configs are project-confined; documented absolute config/output arguments are explicit operator-selected local locations. AI worktree directories (.claude/, .cursor/, .agents/) are excluded. The installed Go toolchain resolves effective build context during indexing; precise repository package loading and external go doc run only after a preflight that rejects source-tree links cmd/go may inspect across the selected root plus its effective module root, or the workspace root and member trees, excluding .git and .gograph. Dependency and toolchain resolution remain open-world under the user's Go environment.
Architecture Enforcement — boundary rules, API drift detection, complexity gates, dead code sweeps, god-object detection, coupling analysis. Run in CI with gograph gate.
Security Flow Analysis — flow follows potential HTTP request, decoded JSON, and environment data across assignments and function calls to SQL query text, process execution, filesystem paths, and outbound HTTP targets. Findings include severity, confidence, and source-to-sink path steps; MCP exposes the same analysis as gograph_flow.
Integrity-Aware Indexing — publication refuses a linked or non-directory .gograph; graph.json is staged and replaced last only after a successful parse (the same-directory rename is atomic on Unix-like systems), records complete/partial build health and ast/precise/precise_fallback analysis status, and exposes both through gograph stats. gate refuses to evaluate a stale graph.
Agent Compliance Auditing — session telemetry tracks whether agents run plan before edits and review after. Grades agent behavior A–F with actionable recommendations.
Command Reference
Query and composed-analysis commands support --json; the exact --files-only
surface is listed in the command reference. Operational commands such as
build, wiki, gate, snapshot, installation, help, and version use text
output; session audit additionally supports raw JSON. CLI --mermaid renders
callers, callees, impact, endpoint, dependents, deps, path, and
coupling as fenced Mermaid. Their MCP equivalents accept mermaid=true and
return the same Markdown-fenced Mermaid text; without it, each tool retains its
normal response format.
| Category | Commands | What it does |
|---|---|---|
| Indexing | build . [--precise], stale, stats | Parse AST, write graph. Check freshness. Index health. |
| Navigation | query, callers [--depth N], callees [--depth N], path, source, node | Find symbols, trace call chains, extract source. |
| Context | context, explain, focus, endpoint | Bundled structural data in one call. Token savers. |
| Change Analysis | plan, review, risk, impact [--uncommitted|--since], changes [--git], api --since | Pre-edit planning, post-edit review, risk analysis, blast radius, drift. |
| Architecture | boundaries, coupling, complexity, godobj, orphans, arity | Quality gates, dead code, coupling, god objects. |
| Types & Structs | fields, implementers [--test-only], interfaces, embeds, constructors, literals, usages, mutate, schema | Struct fields, interface satisfaction, type usage. |
| Infrastructure | routes, sql, envs, errors, concurrency, globals, httpcalls, deps [--transitive], dependents, imports | HTTP routes, SQL, env vars, concurrency, outbound HTTP calls, imports. |
| Security | flow [term] [--source kind] [--sink kind] [--config path] [--no-tests] | Potential untrusted-data paths to SQL, process, filesystem, and outbound HTTP sinks. |
| Testing | tests, fixtures, mocks | Test coverage map, helpers, mock implementations. |
| Error Tracing | errorflow [--no-tests], trace | Reverse-BFS from error strings to HTTP entry points. |
| Diagnostics | hotspot, returnusage, skeleton, diagram, changes, public | Hotspots, return usage, API signatures, Mermaid diagrams. |
| CI/CD | check [--since|--uncommitted], gate, snapshot save|diff|list|drop | Policy checks, threshold enforcement, metric snapshots. |
| Telemetry | session create|end|audit|cleanup | Agent compliance tracking and grading (A–F). |
| LLM-Wiki | wiki [--output dir] | Generate llm-wiki/ — machine-first markdown pages for zero-cost agent orientation (overview, architecture, hotspots, routes, env, errors, concurrency, per-package, API surface). |
| Summary | summary [--json] | Single-call codebase briefing: top 3 hotspots, worst instability package, highest complexity function, orphan count, god-object count. Replaces 5 separate calls. |
| Untested | untested [--pkg name] [--top N] [--json] | Functions with callers but zero test edges — coverage gaps invisible to orphans or per-symbol test queries. One sweep replaces N tests <sym> calls. |
| Doc | doc <pkg[.Symbol]> [--json] | go doc wrapper — signature + doc comment for any stdlib or third-party symbol. No graph required. Closes the gap when call chains leave the project. |
Full command reference with examples: gograph.identuum.ai/docs/command-reference
Architecture Boundary Enforcement
Define boundaries in .gograph/boundaries.json:
{
"layers": [
{ "name": "domain", "packages": ["internal/domain/**"], "may_import": [] },
{ "name": "handler", "packages": ["internal/handler/**"], "may_import": ["internal/service/**", "internal/domain/**"] }
]
}
Run gograph boundaries — exits with code 1 on violation. Works in CI/CD.
Security flow sanitizer policy
gograph flow includes test files by default; add --no-tests for production-only results. It automatically reads .gograph/flow.json when present, or accepts --config <path> for another JSON file inside the graph root. Sanitizers apply to a function's return value and can be scoped to selected sink kinds:
{
"sanitizers": [
{ "function": "security.CleanPath", "for": ["filesystem"] },
{ "function": "security.ValidateURL", "for": ["outbound_http"] }
]
}
Omit for to trust the return value for every sink kind. function accepts the call spelling or a fully-qualified symbol ID; use the fully-qualified form when names collide. A validator that returns only bool or error does not sanitize the original input; wrap validation in a function that returns the trusted value if that is the intended policy.
AI Agent Integration
Official MCP Registry (preview): MCPB-capable clients can discover
io.github.ozgurcd/gograph. The bundle asks for the root directory of the Go
project and launches the bundled executable with separate arguments equivalent
to gograph mcp <project-directory>. Releases provide macOS, Linux, and
Windows bundles for both amd64 and arm64. The current Registry package schema
cannot select by CPU architecture, so choose the asset whose filename matches
the host; do not assume a client will select it automatically. All analysis
still runs locally over stdio, with no hosted gograph service or remote
telemetry.
The Registry bundle and installer-generated MCP registrations intentionally omit
--persist-refresh, keeping disk publication off by default. Use a custom
local MCP command if you explicitly want that behavior.
Desktop config, shared rules, and Claude Code hook setup:
gograph add-claude-plugin
This registers the Claude Desktop MCP server, injects shared CLAUDE.md steering rules, and installs a Claude Code PreToolUse hook. For Claude Code MCP registration, also run the command printed by the installer: claude mcp add gograph -- gograph mcp .. The installer exits non-zero when any installation step fails.
Alternative — install via Claude Code plugin marketplace:
/plugin marketplace add ozgurcd/gograph
/plugin install gograph@gograph
Discovers gograph through Claude Code's plugin marketplace and ships a SKILL.md that auto-activates on Go work, teaching the agent the workflow (capabilities → stats → plan → context → edit → review), when a durable precise CLI build is useful, when to use structural queries, and when to verify with gopls or targeted text/source search.
You still need the gograph binary installed (brew install ozgurcd/tap/gograph or go install github.com/ozgurcd/gograph/cmd/gograph@latest). Use gograph add-claude-plugin for Claude Desktop MCP wiring plus shared rules and the Claude Code hook; register the Claude Code MCP server with the printed claude mcp add command. Use the plugin marketplace when you prefer discovery from Claude Code's plugin UI.
Other agents (Cursor, Copilot, Antigravity, etc.):
gograph mcp . # stdio server; refreshes stay in memory
gograph mcp . --persist-refresh # opt in to publishing refreshed artifacts
Add to your .cursorrules or AI system prompt:
Before answering architecture or repository questions, inspect the available
gograph_*MCP tools and rungograph capabilities. Prefer gograph for supported structural queries; usegoplsor targeted source/text search when results are ambiguous, precision fell back, or a known source call is missing.
Query and composed-analysis commands support --json for machine-readable output:
gograph callers "YourSymbol" --json
# → {"schema_version": "1", "command": "callers", "status": "ok", "count": 2, "results": [...]}
For full integration guides, see docs/coding-agent-usage.md.
Zero-cost orientation with llm-wiki/: Run gograph wiki once per session to generate a directory of machine-first markdown pages — overview, architecture diagram, hotspots, routes, env vars, error sites, concurrency, per-package docs, and the full API surface. Agents read these pages instead of issuing dozens of individual tool calls:
gograph build . --precise
gograph wiki # writes to ./llm-wiki/
# generated orientation starts at: llm-wiki/overview.md
# if maintained governance pages exist, read:
# llm-wiki/index.md → project.md → agent-rules.md → agent-contract.md
Add generated wiki output to .gitignore when it is disposable. Do not
overwrite a repository's maintained or Scrinium-protected agent-rules.md;
propose governed changes through that repository's documented workflow.
Example Output
When you run gograph build ., the generated GRAPH_REPORT.md gives your AI a condensed context map:
External Dependencies (Tech Stack)
| Module | Version |
|---|---|
github.com/gin-gonic/gin | v1.9.1 |
github.com/jackc/pgx/v5 | v5.5.5 |
Important Symbols (Top by outgoing calls)
| Symbol | Kind | File | Line | Calls out |
|---|---|---|---|---|
(Server).Start | method | server.go | 42 | 18 |
ValidateAuth | function | auth.go | 12 | 14 |
How does gograph complement gopls?
gopls is the Go project's
compiler-backed language server. It provides live workspace diagnostics,
navigation, references, implementations, refactoring support, and an
experimental MCP server. It should remain the first choice for editor and
compiler-aware workspace operations.
gograph adds a different layer for repository and agent workflows:
- Persisted snapshots — CLI analysis can inspect a stable graph artifact, while MCP refreshes source-analysis state and preserves the requested precision mode.
- Repository-level analyses — change impact, reachability, routes, SQL, environment reads, security-flow candidates, coupling, and policy gates are represented together.
- Composed responses —
context,plan,review, andsummarypackage related evidence for agent workflows rather than exposing only one language operation at a time.
Use gopls for live compiler-backed navigation and refactoring, rg for text
and non-Go searches, and gograph when a persisted repository graph or composed
change-analysis workflow is useful. See the benchmark guidance
for how to measure these different workflows without assuming one tool is a
drop-in replacement for another.
Correctness model
- Default mode uses Go AST parsing and best-effort heuristics. Tolerates incomplete or non-compiling repositories.
- Repository source boundary excludes descendant links and special files for recognized Go build inputs before build selection, supplies confined bytes to the AST parser, and confines later
source, caller/callee snippet, complexity, and changed-file reads to regular repository files. Linked/non-regulargo.mod,go.sum,go.work,go.work.sum, andvendor/modules.txtmetadata is rejected before gograph or the Go toolchain reads it. Applicablego.work usepaths must stay beneath their workspace directory; member directories,go.mod, and optionalgo.sumare validated beforecmd/go. Precise loading anddocpreflight the selected root plus its effective module root, or the workspace root and every member tree;.gitand.gographare excluded from that source-tree walk. Persistedgraph.jsonis also read through this boundary,.gographmust be a real directory, and an explicitly symlinked repository root is allowed. Missing or unsupported source-policy markers are rebuild-required, and serialized graph roots are never trusted. Saved baseline graphs must be regular non-linked files inside the selected project with the exact marker. Default/relative check and flow configs, boundaries, gate config, and repository-controlled session/snapshot/wiki mutations reject linked path components; documented absolute config/wiki locations are explicit operator selections. Use the current binary for untrusted repositories. - Precise mode attempts type-checked enrichment and needs compilable, build-selected packages for CHA/SSA results. If enrichment fails or omits an indexed non-test source file, the command warns, publishes the AST graph, and records
precise_fallback; if a fresh successful precise artifact already covers the same sources, a failed retry keeps that artifact instead. Successful and AST-only builds recordpreciseandastrespectively. - Each precise interface invocation is represented by one call edge per valid named in-repository CHA target.
callers Interface.Method(including methods inherited from embedded interfaces and concrete methods promoted from embedded fields) expands through the interface's implementers and reports a shared source expression once; concrete receiver notation and fully-qualified method IDs remain available for disambiguation. Compiler-generated promoted-method forwarding is stored as a traversal-only synthetic edge and is hidden from call-site output. - CHA is conservative rather than points-to precise: it may retain implementations that cannot occur in one runtime configuration. Reflection,
unsafe, plugins, unresolved function values, test-only packages, unnamed concrete types, and module-external implementations can still be incomplete. - Callback references are retained only when they resolve to repository callables, and exact call edges are deduplicated before serialization.
- Mutation queries ignore ordinary local assignments and retain owning type information when statically known, so
Type.Fielddisambiguates same-named fields. - Synchronization extraction requires a receiver tied to a known
synctype. Error messages come frompanic,errors.New, andfmt.Errorf, including import aliases. - Heuristic extractors (routes, SQL, tests, and error mapping) are navigation aids, not authoritative program analysis.
- Security flow analysis is interprocedural and path-insensitive, with call/return matching across up to 16 nested repository calls. Default graphs resolve direct local/imported functions;
build . --precisesupplies stronger method/interface targets. It does not model reflection, globals, arbitrary heap aliases, or every dynamic call. Unresolved external transformations are retained with low confidence; every finding requires source review.
Non-goals
- No multi-language parsing
- No AI/model API calls
- No embeddings or SaaS backend
- No remote telemetry or hosted analytics (optional audit sessions write local metadata only)
- No replacement for compiler/type-checker correctness
Contributing
Pull requests welcome! See CONTRIBUTING.md for build, test, and contribution guidelines.
Language Support:
gographcurrently parses Go only. The architecture is extensible — if you want to add Python, TypeScript, Rust, etc., please open an issue first.
License
MIT — see LICENSE.