Skip to main content

Graph-intelligent, token-efficient code navigation for AI assistants. Surgical reading, execution flows, risk scoring, and micro-metadata rendering.

Project description

MCP 1.0+ Python 3.10+ MIT License Version 0.4.1 20 MCP Tools

codegraph-nav

Graph-intelligent, token-efficient code navigation for AI assistants

Surgical reading, execution flows, blast radius, risk scoring — 97% fewer tokens


What is codegraph-nav?

codegraph-nav is an MCP server that helps AI assistants explore codebases efficiently. Beyond basic search and read, it adds graph intelligence: blast radius analysis, execution flow tracing, risk-scored diffs, and community detection.

┌─────────────────────────────────────────────────────────────┐
│                    WITHOUT CODEGRAPH-NAV                    │
├─────────────────────────────────────────────────────────────┤
│  User: "Fix the payment bug"                                │
│                                                             │
│  Claude reads:                                              │
│  • payments.py      (500 lines)  → 7,500 tokens             │
│  • billing.py       (300 lines)  → 4,500 tokens             │
│  • models/order.py  (200 lines)  → 3,000 tokens             │
│  ─────────────────────────────────────────────              │
│  Total:                            15,000 tokens            │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                     WITH CODEGRAPH-NAV                      │
├─────────────────────────────────────────────────────────────┤
│  User: "Fix the payment bug"                                │
│                                                             │
│  1. codegraph_get_minimal_context → 100 tokens              │
│  2. codegraph_search("payment")  → 100 tokens              │
│  3. codegraph_read(payments.py, 45, 89) → 400 tokens        │
│  4. codegraph_blast_radius → 100 tokens                     │
│  ─────────────────────────────────────────────              │
│  Total:                               700 tokens            │
│                                                             │
│  SAVINGS: 95% fewer tokens + impact analysis!               │
└─────────────────────────────────────────────────────────────┘

Quick Start

1. Install

pip install codegraph-nav[mcp]    # MCP server + core
pip install codegraph-nav[all]    # Everything (tree-sitter, networkx, ast-grep)

2. Configure Claude Code (CLI)

Add to ~/.claude/mcp.json:

{
  "mcpServers": {
    "codegraph-nav": {
      "command": "codegraph-nav-mcp"
    }
  }
}

3. Configure Claude Desktop

Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "codegraph-nav": {
      "command": "codegraph-nav-mcp"
    }
  }
}

4. Use It

In Claude, just ask to explore your codebase:

"Scan this project and find the payment function"
"What's the blast radius if I change auth.py?"
"Show me the architecture of this codebase"

Claude will automatically use codegraph-nav's 20 tools to explore efficiently.


Available Tools

Core Navigation

Tool Purpose When to Use
codegraph_get_minimal_context ~100 token project orientation Always use first
codegraph_scan Index codebase to .codegraph.json First time on a project
codegraph_search Find symbols by name/pattern Looking for functions/classes
codegraph_read Read specific line ranges After finding symbol locations
codegraph_stats Codebase size overview Understanding project scale
codegraph_get_hubs Central files, or scope="symbol" for PageRank symbol hubs Architecture analysis
codegraph_get_context PageRank-ranked, budget-bounded context for a query "What should I read to understand X?"
codegraph_get_structure File symbol outline Before reading a file
codegraph_get_dependencies Import/export graph Understanding coupling
codegraph_test_gaps Find untested symbols Before/after changes

Graph Intelligence

Tool Purpose When to Use
codegraph_graph_build Build graph DB (.codegraph.db) Before heavy graph analysis
codegraph_blast_radius Impact analysis (recursive CTE) "What breaks if I change this?"
codegraph_list_flows Execution flows + criticality Understanding call chains
codegraph_detect_changes Risk-scored git diff Code review / PR analysis
codegraph_search_graph FTS5 + fuzzy + RRF search Search by concept, not just name

Architecture & Domain

Tool Purpose When to Use
codegraph_list_communities Code communities + cohesion Architecture grouping
codegraph_get_community Community details + members Explore a community
codegraph_get_architecture_overview Architecture summary High-level structure
codegraph_list_routes HTTP routes (15+ frameworks) API/route exploration
codegraph_list_schemas ORM schemas (8+ ORMs) Data model exploration

How It Works

flowchart TB
    subgraph SCAN["Step 1: Scan"]
        A[(Codebase)] --> B[codegraph_scan]
        B --> C[.codegraph.json]
    end

    subgraph NAVIGATE["Step 2: Navigate"]
        D[codegraph_search] --> E[file:line locations]
        E --> F[codegraph_read]
        F --> G[Only needed code]
    end

    subgraph GRAPH["Step 3: Analyze"]
        C --> H[codegraph_graph_build]
        H --> I[.codegraph.db]
        I --> J[blast_radius / flows / risk]
    end

    C --> D
  1. Scan once - Creates .codegraph.json with all symbols indexed
  2. Search & read surgically - Find symbols and load only the lines you need
  3. Graph analysis - Build .codegraph.db for blast radius, flows, and risk scoring

Example Session

1. codegraph_get_minimal_context(path="/project", task="fix auth bug")
   → project: 142 files · 1847 symbols · py,js
   → hubs: config.py(8←), models.py(5←)
   → suggest: codegraph_search → codegraph_read → codegraph_get_dependencies

2. codegraph_search(query="authenticate")
   → src/auth.py:L10-30 [fn] authenticate

3. codegraph_read(file_path="src/auth.py", start_line=10, end_line=30)
   → Only those 20 lines (~200 tokens)

4. codegraph_blast_radius(path="/project", changed_files=["src/auth.py"])
   → blast(auth.py): 12 nodes · 5 files impacted

5. codegraph_detect_changes(path="/project")
   → risk: 0.78 HIGH | 3 files · 8 symbols changed

Detail Levels

All tools accept a detail_level parameter:

  • minimal (default) - Compact, token-efficient output
  • standard - Adds signatures, language breakdown, bidirectional counts
  • verbose - Adds docstrings, dependency chains, per-file details

Workflow Prompts

5 built-in prompts that enforce token discipline:

Prompt Use Case
investigate_bug Bug investigation: orient, search, read, dependencies
add_feature Feature implementation: orient, search similar, structure, read
review_changes Code review: orient, test gaps, search changed, read
understand_architecture Architecture analysis: orient, hubs, dependencies, structure
onboard_project Project onboarding: orient, stats, hubs, structure

Each prompt starts with codegraph_get_minimal_context and defaults to detail_level="minimal".


Supported Languages

Language Analysis Type Symbols Parents Doc comments Calls (deps) Imports Quality
Python Full AST (stdlib) ✅ (+enums, constants, nested fns) ✅ docstrings ✅ resolved ⭐⭐⭐⭐⭐
JavaScript AST (tree-sitter)* ✅ resolved ⭐⭐⭐⭐⭐
TypeScript AST (tree-sitter)* ✅ (+interfaces, enums, types) ✅ resolved ⭐⭐⭐⭐⭐
Ruby AST (tree-sitter)* # require ⭐⭐⭐⭐⭐
Go AST (tree-sitter)* ✅ (+structs, interfaces) // ✅ resolved ⭐⭐⭐⭐⭐
Rust AST (tree-sitter)* ✅ (+structs, traits, enums) /// ✅ (+macros) use ⭐⭐⭐⭐⭐
Dart / Flutter AST (tree-sitter)* ✅ (+mixins, extensions) /// ✅ resolved ⭐⭐⭐⭐⭐
Java AST (tree-sitter)*† ✅ (+records, annotations) ✅ Javadoc ⭐⭐⭐⭐⭐
Kotlin AST (tree-sitter)* ✅ (+objects, data classes) ✅ KDoc ⭐⭐⭐⭐⭐
Swift AST (tree-sitter)* ✅ (+protocols, extensions) /// ⭐⭐⭐⭐⭐
C# AST (tree-sitter)* ✅ (+records, delegates) /// using ⭐⭐⭐⭐⭐
C AST (tree-sitter)*† ✅ (+prototypes, typedefs) ✅ includes ⭐⭐⭐⭐⭐
C++ AST (tree-sitter)*† ✅ (+out-of-line members) ✅ includes ⭐⭐⭐⭐⭐
PHP AST (tree-sitter)*† ✅ (+traits, enums) ✅ docblocks use/require ⭐⭐⭐⭐⭐

*Install tree-sitter support: pip install codegraph-nav[ast] All tree-sitter analyzers fall back to regex when tree-sitter is not installed.

†Java/C/C++/PHP keep ast-grep as an intermediate fallback: with the [fast] extra installed but no tree-sitter grammar, they get a real AST parse (symbols + parents) before degrading to regex.

Every tree-sitter language extracts symbols with parent context, cross-file call dependencies (deps), and import specifiers resolved to internal repo files — which the graph builder turns into CALLS and IMPORTS_FROM edges. All except JS/TS also capture leading doc comments. Each symbol records which engine produced it ("source": "ast" | "ast-grep" | "regex"), and codegraph_stats shows the per-engine breakdown.

AST grammars ship through tree-sitter-language-pack (installed by the [ast] extra): one dependency with 160+ pre-compiled grammars for Linux/macOS/Windows — no C compiler needed. Installations that predate the pack keep working: the grammar registry also resolves the old individual tree-sitter-<lang> wheels. [dart] remains as a deprecated alias of [ast]. Without any grammar installed, every language falls back to the regex analyzer. Flutter needs no separate grammar; widgets are ordinary Dart classes.


Micro-Metadata Format

The scan output uses a compact ASCII tree with inline metadata:

my-project/
├── src/
│   ├── api/
│   │   ├── client.py [C:APIClient M:get,post] (5←)
│   │   └── routes.py [F:handle,validate] (3←)
│   └── core/
│       └── config.py [C:Config M:load] (Hub:8←)
└── tests/
    └── test_api.py [F:test_client]

═══ Summary ═══
28 files · 142 symbols · 12 hubs

Each file shows: classes (C:), functions (F:), methods (M:), and importer count (N←).


CLI Usage

# Generate code map
codegraph-nav scan /path/to/project
cgn scan .                              # Short alias

# Search for symbols
cgn search "process_payment"
cgn search -t class -o table

# Read specific lines
cgn read src/payments.py 45-89
cgn read src/payments.py 45-89 -c 3     # With context

# Get codebase stats
cgn stats

# Incremental update (only changed files)
cgn scan --incremental .

# Build the graph DB (.codegraph.db) from the code map
cgn graph build .                       # incremental (skip unchanged files)
cgn graph build . --full                # full rebuild
cgn graph stats .                       # node/edge counts (add -o json)

# Watch for changes; also rebuild the graph after each update
cgn watch . --graph

# Export as markdown
cgn export -f markdown -o docs/codebase.md

The graph build also computes a symbol-level PageRank (with the [graph] extra: pip install codegraph-nav[graph]), surfaced via the codegraph_get_hubs (scope="symbol") and codegraph_get_context MCP tools.


Python API

from codegraph_nav import CodeNavigator, CodeSearcher, LineReader

# Scan
navigator = CodeNavigator("/path/to/project")
code_map = navigator.scan()

# Search
searcher = CodeSearcher(".codegraph.json")
results = searcher.search_symbol("payment", symbol_type="function")

# Read surgically
reader = LineReader(root_path="/path/to/project")
content = reader.read_lines("src/pay.py", 45, 89)

Graph API

from codegraph_nav.graph import GraphStore, GraphBuilder, get_blast_radius, trace_flows

# Build graph from code map
store = GraphStore(".codegraph.db")
builder = GraphBuilder(store)
stats = builder.build_from_code_map(code_map)

# Blast radius
impact = get_blast_radius(store, changed_files=["src/auth.py"])
print(f"{impact['impacted_nodes']} nodes, {len(impact['impacted_files'])} files affected")

# Execution flows
flows = trace_flows(store)
for f in flows[:5]:
    print(f"{f['name']} crit:{f['criticality']:.2f} depth:{f['depth']}")

store.close()

Domain Intelligence API

from codegraph_nav.domain import detect_routes, detect_schemas, infer_project_tags

# Detect routes (FastAPI, Express, Django, Gin, etc.)
routes = detect_routes(code_map, root_path="/path/to/project")

# Detect ORM schemas (SQLAlchemy, Django, Prisma, etc.)
schemas = detect_schemas(code_map, root_path="/path/to/project")

# Infer domain tags (auth, db, cache, api, etc.)
tags = infer_project_tags(code_map)

Optional Dependencies

Extra What it adds
[mcp] MCP server (FastMCP)
[ast] Tree-sitter analyzers (JS/TS/Ruby/Go/Rust)
[graph] PageRank hub detection (networkx)
[fast] ast-grep high-perf parsing
[all] Everything above
[dev] pytest, mypy, black, ruff, build, twine

Performance

Tested on real-world open source projects:

Project Files Symbols Map Size Map Time
Flask 142 1,847 89 KB 0.8s
Django 2,156 28,493 1.2 MB 8.2s
requests 47 412 23 KB 0.3s

Token savings:

  • Small projects (50-100 files): 85-90% reduction
  • Medium projects (100-500 files): 92-96% reduction
  • Large projects (500+ files): 97-99% reduction

Development

git clone https://github.com/efrenbl/codegraph-nav.git
cd codegraph-nav
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
python3 -m pytest tests/ -v

Requirements

  • Python 3.10+
  • MCP SDK 1.0+ (for MCP server only)

License

MIT License - see LICENSE for details.


Stop burning tokens reading entire files.
Scan once, search instantly, read surgically, analyze impact.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

codegraph_nav-0.4.1.tar.gz (229.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

codegraph_nav-0.4.1-py3-none-any.whl (183.7 kB view details)

Uploaded Python 3

File details

Details for the file codegraph_nav-0.4.1.tar.gz.

File metadata

  • Download URL: codegraph_nav-0.4.1.tar.gz
  • Upload date:
  • Size: 229.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for codegraph_nav-0.4.1.tar.gz
Algorithm Hash digest
SHA256 018be6f85befb6482924ffca75e00d42761c520a8527b7c8cf88ed1aae6b46a1
MD5 d0bd5785556b7032f7933136e4399b44
BLAKE2b-256 946c1d7ad4c29577218e3b460f8ac68b7872c26a28f469d04947963e5709eee8

See more details on using hashes here.

Provenance

The following attestation bundles were made for codegraph_nav-0.4.1.tar.gz:

Publisher: release.yml on efrenbl/codegraph-nav

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file codegraph_nav-0.4.1-py3-none-any.whl.

File metadata

  • Download URL: codegraph_nav-0.4.1-py3-none-any.whl
  • Upload date:
  • Size: 183.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for codegraph_nav-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b8bab1b8aea06c3060c64d16546030d15576b235c30edf27e3d9c5f522ae948c
MD5 7a9345a215dd2090d1bb10786a503f99
BLAKE2b-256 88f8d9d23823bc53cf899492a34f25411167575ceb81e39930d2c83eb16a46dd

See more details on using hashes here.

Provenance

The following attestation bundles were made for codegraph_nav-0.4.1-py3-none-any.whl:

Publisher: release.yml on efrenbl/codegraph-nav

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page