loading…
Search for a command to run...
loading…
A local AST and type-aware Go repository context indexer that uses CHA to map symbols, call graphs, dependencies, and architecture patterns. Built for AI coding
A local AST and type-aware Go repository context indexer that uses CHA to map symbols, call graphs, dependencies, and architecture patterns. Built for AI coding agents that need to navigate and reason about large Go codebases without reading raw files.
gograph is a local AST/type-aware Go repository context indexer for AI coding agents.

It builds a compact graph of packages, symbols, calls, routes, config reads, tests, and code-quality signals so agents can navigate Go repositories with fewer raw file reads.
Note on Language Support: I originally built
gographspecifically for Golang because that is what I needed for my own workflows. It currently only parses and maps Go codebases. However, the architecture is extensible! If you want to add support for other languages (Python, TypeScript, Rust, etc.), contributions are more than welcome. Please see the Contributing Guide to get started.
gopls)?While gopls has access to similar AST and type data, connecting an AI coding agent to a Language Server is notoriously difficult and inefficient:
gopls communicates via JSON-RPC over stdin/stdout. While you can invoke some gopls CLI commands, it usually returns raw file coordinates (file:line:col). This forces the agent to burn tokens running cat or sed to actually read the referenced code.gograph doesn't just find coordinates; it physically extracts the exact structural slice (the struct body, the interface, the method) and formats it natively in Markdown. The AI reads exactly what it needs in one shot with zero surrounding file noise.gograph is built for systemic graph traversal. For example, gograph trace "parse failed" performs a reverse-BFS from an error string all the way up the call stack to the HTTP entry point. gograph impact calculates the full blast radius of a code change. gopls doesn't natively perform graph-traversal diagnostics like this out of the box.In short: gopls is optimized for human IDEs. gograph is optimized for terminal-based LLMs trying to save context tokens.
focus to save LLM tokens.context <symbol> replaces 4–5 separate tool calls — returns node, source, callers, callees, and tests in one response.hotspot ranks functions by incoming call count so agents know which functions to study first.complexity), god-object detection (godobj), and package coupling/instability (coupling).changes surfaces new/modified/deleted symbols since the last build without re-reading source files. changes --git <ref> scopes the same output to files changed since any git ref (branch, tag, or commit).deps <pkg> [--transitive] shows direct or full transitive import closures for any package.go.mod to summarize your external dependencies (like gin or pgx) so agents instantly understand your stack.sync.Once.Do calls across the entire codebase.Test* functions to the production symbols they likely exercise.os.Getenv / viper.Get* read with file, line, and enclosing function.path <from> <to> finds the shortest call chain between any two symbols via BFS.orphans uses full reachability analysis from entry points — stricter than simple 0-call-count checks.# MacOS / Linux (via Homebrew)
brew install ozgurcd/tap/gograph
# Or using Go:
go install github.com/ozgurcd/gograph/cmd/gograph@latest
1. Generate the Graph (Run this after every major code change):
gograph build .
# OR for more precise type-checked analysis (slower, but provides exact dynamic dispatch & interface satisfaction proofs):
gograph build . --precise
This instantly generates .gograph/graph.json and .gograph/GRAPH_REPORT.md.
2. Query the Graph (Lightning fast, no re-parsing):
gograph boundaries [--config] # Verify package architecture constraints using boundaries.json
gograph callees "InitServer" # See what InitServer calls (direct, depth 1)
gograph callees "InitServer" --depth 2 # 2 hops down (callees of callees)
gograph callers "ValidateToken" # See what functions call ValidateToken (direct)
gograph callers "ValidateToken" --depth 3 # 3 hops up (callers-of-callers-of-callers)
gograph callers 'github.com/me/app/internal/auth::(*Service).Validate' # Pass a fully-qualified symbol ID for exact match (no same-name conflation). Works for callees/impact/path too. Requires --precise build.
gograph complexity # Cyclomatic complexity for all functions (highest first)
gograph complexity "Run" # Complexity for a specific function
gograph concurrency # Map all goroutines, channels, mutexes, and sync primitives
gograph coupling # Package fan-in, fan-out, instability table
gograph coupling "internal/auth" # Filter to a specific package
gograph embeds "Mutex" # See which structs embed a target struct
gograph envs # List every environment variable read in the codebase
gograph errors # Map every custom error and panic to its function
gograph fields "User" # Extract all fields and types of a struct
gograph focus "internal/auth" # Generate a highly targeted context for one package
gograph godobj # Find god-object struct candidates
gograph godobj --methods 10 --fields 12 --calls 30 --top 5 # Custom thresholds
gograph impact "ValidateToken" # View the full blast radius (all downstream callers)
gograph impact --uncommitted # Calculate the blast radius of all your uncommitted code changes
gograph impact --since main # Blast radius of all symbols changed since main (PR-level)
gograph implementers "AuthService" # See which structs implement an interface
gograph implementers "AuthService" --test-only # Limit to test/mock files (replaces gograph mocks)
gograph imports "redis" # Find all files that import a specific external package
gograph interfaces "UserService" # See which interfaces a struct satisfies (type-checked if --precise was used)
gograph node "UserStruct" # Get detailed AST info about a specific node
gograph orphans # List functions and methods with 0 explicit incoming calls (dead code)
gograph path "CreateUser" "sql" # Shortest call chain between two symbols
gograph public "internal/auth" # Filter graph to only show exported public symbols
gograph query "Auth" # Search for symbols, files, or packages
gograph routes # Extract all HTTP REST API routes (e.g. GET /api)
gograph endpoint "CreateUser" # Full vertical slice: handler → call chain → SQL → env reads (PREFERRED: use handler name)
gograph endpoint "POST /api/users" # Same but via route pattern (ONLY works for flat routers — fails with Gin/Echo/Chi groups)
gograph source "ValidateToken" # Extract the source code for a specific symbol
gograph sql # Extract database SQL queries from the AST
gograph stale # Check if graph.json is out of date vs source files
gograph stats # Compact index health summary: schema version, build timestamp, counts
gograph tests "ValidateToken" # Find which test functions exercise a named symbol
# --- STATIC GUARDS & CI ENFORCEMENT ---
gograph check # Run static policy checks using .gograph/checks.json
gograph check --uncommitted # Run checks, including uncommitted code
gograph check --since main # Run checks, including API drift against main
gograph boundaries # Verify package architecture constraints against boundaries.json
gograph gate # Fail CI if any .gograph.yml threshold is violated (complexity, instability, orphans, coupling)
# --- SNAPSHOTS ---
gograph snapshot save v1 # Capture current architectural metrics under label v1
gograph snapshot diff v1 # Compare current graph against snapshot v1
gograph snapshot list # List all saved snapshots
gograph snapshot drop v1 # Delete snapshot v1
# --- TOKEN SAVERS ---
gograph api --since main # Identify breaking API and contract changes since a git reference
gograph arity --min 5 # Find functions with many arguments (long parameter list smell)
gograph changes # New/modified/deleted symbols since last build
gograph changes --git main # Symbols in files changed since main (git-ref mode)
gograph changes --git v1.4.50 # Same, scoped to a release tag
gograph constructors "User" # Find factory functions returning the named struct
gograph literals "User" # All Foo{...} composite literal sites (run before adding a required field)
gograph usages "AuthService" # Every place a type appears in signatures and fields (run before changing an interface)
gograph returnusage "ValidateToken" # How each caller uses the return value (discarded/assigned/returned/passed)
gograph context "ValidateToken" # Node + source + callers + callees + tests + role in ONE call
gograph context --uncommitted # Context for ALL uncommitted symbols bundled (replaces 5-8 sequential calls)
gograph explain "ValidateToken" # LLM-ready architectural narrative: role, callers, callees, complexity, SQL, env, tests
gograph deps "internal/auth" # Direct import dependencies of a package
gograph deps "internal/auth" --transitive # Full transitive closure
gograph dependents "internal/auth" # All packages that import this package (inverse of deps)
gograph fixtures "internal/auth" # Find test helper structs and functions in test files
gograph globals "internal/auth" # Find pkg-level vars, consts, and functions mutating them
gograph hotspot # Top 10 most-called functions (where to focus first)
gograph hotspot --top 20 # Expand to top 20
gograph mocks "AuthService" # Alias for: gograph implementers "AuthService" --test-only
gograph mutate "User.Status" # Find functions that mutate a specific struct field (direct assignments, ++/+=, and indirect mutations via atomic.*, sync.Map, sync.Mutex, channel sends, and user-defined wrapper methods. Requires --precise build for indirect detection.)
gograph plan "ValidateToken" # Generate an operational change plan (callers, tests, risk profile) before editing a symbol
gograph plan "ValidateToken" --with-context # Plan + full context for every inspect_first symbol (replaces plan + N×context)
gograph plan --uncommitted # Generate a change plan for all currently uncommitted modified symbols
gograph review "ValidateToken" # Generate a post-edit final review report for a modified symbol
gograph review --uncommitted # Generate a post-edit final review report for all uncommitted changes
gograph schema "users" # Find structs mapped to a database table/schema via tags
gograph skeleton # Output the whole repository's API signatures (bodies stripped)
gograph errorflow "invalid token" # Trace an error's path from definition up to HTTP handlers (heuristic, NO SSA)
gograph errorflow "invalid token" --no-tests # Same, excluding test-file references
gograph trace "parse failed" # Alias for errorflow (kept for compatibility)
# endpoint: full vertical slice for one HTTP endpoint. IMPORTANT: route patterns only work with flat routers.
# With Gin/Echo/Chi Group() routing, the prefix is lost in the AST. Use handler symbol name instead.
gograph endpoint "CreateUser" # RECOMMENDED: always works regardless of routing style [--depth N] [--json]
gograph endpoint "POST /api/users" # route pattern: only works if path is a flat string literal (no Group() prefix)
3. Architecture Boundary Enforcement:
You can configure gograph to actively enforce clean architecture by defining boundaries. Create a .gograph/boundaries.json file in your root directory:
{
"layers": [
{
"name": "domain",
"packages": ["internal/domain/**"],
"may_import": []
},
{
"name": "handler",
"packages": ["internal/handler/**"],
"may_import": [
"internal/service/**",
"internal/domain/**"
]
}
]
}
Note: Standard library imports are implicitly allowed. Imports within the same layer are also implicitly allowed.
Run the enforcement check:
gograph boundaries
If a violation is found (e.g., handler imports internal/repository directly), it will exit with code 1 and print the exact file that violated the rule. Extremely useful for CI/CD or Agent CLAUDE.md instructions!
4. Agent JSON Integration:
All search and query commands support the --json flag to emit strictly formatted, machine-parseable JSON envelopes.
For specific instructions on how to configure agents to use gograph, read the Claude Code Integration Guide.
gograph callers "ValidateToken" --json
Returns: {"schema_version": "1", "command": "callers", "status": "ok", "count": 2, "results": [...]}
5. Run as an MCP Server (For AI Agents):
If you want to give your AI agent native tool execution capabilities, gograph has a built-in Model Context Protocol (MCP) server.
To install the plugin automatically on macOS, Windows, or Linux, run:
gograph add-claude-plugin
This single command does three things:
claude_desktop_config.json (Claude Desktop) so gograph tools are available to Claude natively.~/.claude/CLAUDE.md — Claude reads this automatically and knows to use gograph_query instead of grep for Go symbol searches.PreToolUse hook at ~/.claude/hooks/gograph-guard.sh — this intercepts grep/rg calls targeting Go symbols and redirects Claude to the appropriate gograph MCP tool, saving tokens and improving precision.The hook is smart: it only blocks grep when the search pattern looks like a Go identifier (PascalCase/camelCase, 3+ chars). Legitimate raw-text searches in YAML, Markdown, SQL, or comment files are allowed through unchanged.
For Claude Code (CLI) users, also run:
claude mcp add gograph -- gograph mcp .
You can also run the MCP server manually over stdio:
gograph mcp .
To get the best results from your AI coding assistant, run gograph add-claude-plugin. It automatically configures everything:
CLAUDE.md rules that steer Claude to use gograph instead of grepPreToolUse hook that enforces Go symbol lookups go through gographIf you prefer manual setup, add this to your .cursorrules, CLAUDE.md, or AI system instructions:
System Prompt: Before answering architecture or repository questions, inspect the available
gograph_*MCP tools for the current project and use them instead of grep/find. Each project ships its own gograph MCP server; pick the matching one. If using the CLI directly, rungograph capabilitiesfirst.
When you run gograph build ., the generated GRAPH_REPORT.md gives your AI a condensed, highly-dense context map that looks like this:
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 |
We love pull requests! See the CONTRIBUTING.md file for guidelines on how to build, test, and contribute to the project. If you are adding support for a new language, please open an issue first to discuss the design.
This project is licensed under the MIT License - see the LICENSE file for details.
Run in your terminal:
claude mcp add gograph -- npx Security
Low riskAutomated heuristic from public metadata — not a security guarantee.