Skip to content

Latest commit

Β 

History

41 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

⚑ cgraph

Your codebase, as a queryable graph.

Give AI agents instant structural awareness β€” callers, callees, impact analysis, trace paths β€” without scanning thousands of files.

Node.js TypeScript MCP Tests License

  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”     MCP      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    SQLite    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚ Copilot │◄────────────►│  cgraph  │◄────────────►│ .cgraph/ β”‚
  β”‚  Agent  β”‚  JSON-RPC    β”‚  Server  β”‚   sql.js     β”‚ graph.db β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚                        β–²                         β–²
       β”‚ "who calls             β”‚ 22 tools                β”‚ files, nodes,
       β”‚  handleRequest?"       β”‚ instant response        β”‚ edges, roles
       β–Ό                        β”‚                         β”‚
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  1 call β”‚  instead of  β”‚  Parser  │───index────►│ Your Codeβ”‚
  β”‚  2.2s   β”‚              β”‚ + Walker β”‚              β”‚  .ts .py β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β”‚  .c  .sh β”‚
                                                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Getting Started Β· MCP Tools Β· CLI Reference Β· Benchmarks Β· Architecture


🎯 The Problem

AI agents waste 70% of tool calls on grep β†’ read_file β†’ grep β†’ read_file chains just to understand code structure. Every question triggers a cascade:

❌ Without cgraph                          βœ… With cgraph
─────────────────────────────              ──────────────────────
1. grep "handleRequest"                    1. cgraph_node handleRequest
2. read_file server.ts                        β†’ definition, callers,
3. grep "import.*handleRequest"               callees, file:line
4. read_file routes.ts                        all in ONE response
5. grep "routes" to find callers
6. read_file app.ts
7. finally has the answer                  Done. 2.2 seconds.
   14 seconds later...

cgraph pre-computes the graph once, then answers structural queries instantly.


✨ Feature Highlights

πŸ”Œ Install & Forget

One-command installer. Auto-indexes on first Copilot query. No config per project.

πŸ› οΈ 22 MCP Tools

search Β· context Β· trace Β· explore Β· node Β· callers Β· callees Β· impact Β· files Β· status Β· affected Β· export Β· changed Β· deadcode Β· cycles Β· stats Β· suggest Β· auto-context Β· intent-search Β· validate-plan Β· lint Β· dna

⚑ Dramatically Faster Workflows

Collapses multi-step grep→read chains into single precomputed graph queries. Avg MCP tool latency: 17ms.

🌍 Multi-Language

TypeScript Β· JavaScript Β· Python Β· C Β· C++ Β· Shell Β· PowerShell β€” all from one index.

🧠 Smart Analysis

Dead code detection Β· cycle finding Β· refactoring suggestions Β· role classification Β· project statistics.

πŸ”„ Incremental & Live

3-tier change detection. File watcher with auto re-index. Parallel parsing with worker threads.


πŸš€ Getting Started

Option A: One-Command Install

No Node.js or git required β€” the installer handles everything.

Windows

powershell -ExecutionPolicy Bypass -File install.ps1

macOS / Linux

bash install.sh

The installer will:

  1. πŸ“¦ Download portable Node.js (if needed)
  2. πŸ“₯ Fetch cgraph source
  3. πŸ”¨ Build it
  4. πŸ”— Add cgraph to your PATH
  5. βš™οΈ Configure VS Code MCP globally (works in all workspaces)

That's it. Open any project β†’ ask Copilot β†’ cgraph auto-indexes and responds.

Option B: From Source

git clone https://github.com/samarth-w/agent_graph.git
cd agent_graph
npm install && npm run build
npm link                       # optional: makes `cgraph` available globally
πŸ“‹ VS Code MCP Configuration (if you installed from source)

Add to your VS Code settings.json (Ctrl+Shift+P β†’ "Open User Settings (JSON)"):

{
  "mcp": {
    "servers": {
      "cgraph": {
        "command": "node",
        "args": ["<path-to-cgraph>/bin/cgraph.js", "serve", "--mcp"],
        "cwd": "${workspaceFolder}"
      }
    }
  }
}

Windows tip: If VS Code can't find node, use "C:\\Program Files\\nodejs\\node.exe".

πŸ‘₯ Teammate Setup

With Node.js: git clone β†’ npm install β†’ npm run build β†’ npm link β†’ add MCP config.

Without Node.js: Share the repo folder β†’ run install.ps1 (Win) or install.sh (Mac/Linux) β†’ done.


πŸ”§ MCP Tools

When running as an MCP server, 22 tools are available to AI agents:

graph LR
    subgraph "πŸ” Discovery"
        A[cgraph_search] --> B[cgraph_explore]
        A --> C[cgraph_node]
    end
    subgraph "🧭 Navigation"
        C --> D[cgraph_callers]
        C --> E[cgraph_callees]
        D --> F[cgraph_trace]
    end
    subgraph "πŸ’‘ Intelligence"
        F --> G[cgraph_context]
        G --> H[cgraph_impact]
        H --> I[cgraph_affected]
    end
    subgraph "πŸ“Š Analysis"
        J[cgraph_deadcode]
        K[cgraph_cycles]
        L[cgraph_stats]
        M[cgraph_suggest]
    end
    subgraph "🧠 Agentic Intelligence"
        R[cgraph_auto_context]
        S[cgraph_intent_search]
        T[cgraph_validate_plan]
        U[cgraph_lint]
        V[cgraph_dna]
    end
    subgraph "πŸ“¦ Utilities"
        N[cgraph_status]
        O[cgraph_files]
        P[cgraph_export]
        Q[cgraph_changed]
    end

    style A fill:#3B82F6,color:#fff
    style G fill:#8B5CF6,color:#fff
    style H fill:#EF4444,color:#fff
    style M fill:#F59E0B,color:#fff
    style R fill:#10B981,color:#fff
    style T fill:#EC4899,color:#fff
Loading
Tool What it does When to use
cgraph_context Builds ranked code context for a task Start here β€” best for architecture & feature questions
cgraph_search Find symbols by name with fuzzy matching Looking for a specific function or class
cgraph_node Symbol detail + full call trail Deep-dive on one symbol
cgraph_explore Source code for multiple related symbols Need actual code, not just structure
cgraph_callers Who calls this? (reverse graph) Understanding usage patterns
cgraph_callees What does this call? (forward graph) Understanding dependencies
cgraph_trace Call path between two symbols "How does X reach Y?"
cgraph_impact Blast radius of a change Pre-change risk assessment
cgraph_affected Test files impacted by changes CI optimization, test selection
cgraph_changed Symbols changed in git diff Code review, change mapping
cgraph_deadcode Unreachable symbols Cleanup candidates
cgraph_cycles Circular dependency detection Architecture health
cgraph_stats Project metrics & hotspots Codebase overview
cgraph_suggest Refactoring suggestions Extract, inline, move, split recommendations
cgraph_export Mermaid / DOT / HTML diagrams Visualization & docs
cgraph_files List all indexed files Inventory check
cgraph_auto_context File-level warm start: symbols, callers, callees, tests Open a file β€” instant awareness before coding
cgraph_intent_search Natural language symbol search (BM25) "find auth middleware" β€” searches by meaning, not just name
cgraph_validate_plan Pre-flight change risk assessment Before refactoring β€” blast radius, affected tests, risk score
cgraph_lint Architecture rule enforcement CI gate β€” deny imports, max fan-out, cycle checks
cgraph_dna Codebase fingerprint & health scores Onboarding β€” languages, architecture style, health overview
cgraph_status Index health & stats Debugging, verification

πŸ’» CLI Reference

cgraph <command> [options]

Core Commands

Command Description
index [dir] Build / update the code graph (incremental)
sync [dir] Re-index changed files only
search <query> Search symbols β€” supports kind:, lang:, path:, role:, exported: filters
callers <symbol> Reverse call graph β€” who calls this?
callees <symbol> Forward call graph β€” what does this call?
impact <symbol> What breaks if this changes?
trace <from> <to> Find the call path between two symbols
context <task> Build ranked code context for a task description
explore <query> Get source code for related symbols
node <symbol> Symbol detail with call trail
query <symbol> Look up a symbol with callers/callees
where <symbol> Find where a symbol is defined

Analysis Commands

Command Description
deadcode Find unreachable symbols (dead code)
cycles Detect circular dependencies
stats Project metrics β€” hotspots, coupling, complexity
suggest AI-powered refactoring suggestions

Agentic Intelligence Commands

Command Description
auto-context <file> File-level warm start β€” symbols, callers, callees, related tests
intent <query> Natural language symbol search (BM25 scoring)
validate Pre-flight change risk assessment from stdin
lint Architecture rule enforcement via .cgraph.json rules
dna Codebase fingerprint β€” languages, health scores, architecture style

Infrastructure Commands

Command Description
status Index health (files, nodes, edges, languages, roles)
files List all indexed files
affected <files> Find test files impacted by changes
export Generate Mermaid, DOT, or interactive HTML diagrams
changed Map git diff to changed symbols
watch [dir] Watch for file changes and auto re-index
serve --mcp Start MCP server (JSON-RPC 2.0 over stdio)

Global Options

--depth <n>       Max traversal depth (default: 3)
--max-nodes <n>   Max nodes to return (default: 50)
--kind <kind>     Filter by symbol kind (function, class, method, etc.)
--file <path>     Filter by file path
--json            Raw JSON output
--pretty          Formatted output

Project Configuration

Drop a .cgraph.json in your project root to customize behavior:

{
  "maxDepth": 5,
  "maxNodes": 100,
  "ignorePaths": ["vendor", "generated"],
  "extensions": [".ts", ".tsx", ".py"]
}

πŸ“Š Benchmarks

Benchmarked on a real-world TypeScript finance app β€” 16 files, 168 symbols, 1,006 edges. MCP tool latency benchmarked on cgraph's own codebase β€” 81 files, 687 nodes, 1,282 edges.

Agent Question Without cgraph With cgraph Speedup
Where is formatMoney defined and who calls it? 7 calls · 14.0s 1 call · 2.2s 🟒 6.5x
Impact of changing ApiController? 6 calls · 12.0s 1 call · 2.2s 🟒 5.6x
How does createApp reach formatMoney? 4 calls · 8.0s 1 call · 2.2s 🟒 3.6x
Changed store.ts β€” what tests to run? 5 calls Β· 10.0s 1 call Β· 2.2s 🟒 4.6x
Explain the architecture 11 calls · 22.0s 2 calls · 4.4s 🟒 5.0x
Total 33 calls · 66s 6 calls · 13s ⚑ 5.1x faster

MCP Tool Latency (self-hosted benchmark)

Metric Value
Avg latency (22 tools) 17ms
Min latency 2ms (search, callees)
Max latency 103ms (explore β€” includes source read)
Cold index + query 566ms (auto-index on first call)
Warm re-sync 288ms (no-change check)
Burst (10Γ— search) 6ms/call

Performance powered by bulk adjacency maps β€” getFileMap, getNodeMap, getAdjacencyMaps load the graph in 3 queries, then all lookups are O(1) map gets. Zero N+1 query patterns.

πŸƒ Run benchmarks yourself
# Agent workflow comparison (with vs without cgraph)
node scripts/benchmark-agent.mjs <your-project-dir>

# MCP server latency (22 tools, burst, cold start)
node scripts/benchmark.mjs

# Raw efficiency comparison (grep+read vs cgraph)
node scripts/benchmark-compare.mjs

πŸ—οΈ Architecture

How It Works

flowchart TB
    subgraph Index["πŸ“₯ Indexing Pipeline"]
        direction TB
        W[File Walker] -->|"*.ts *.py *.c *.sh"| P[Parser]
        P -->|"symbols + calls"| S[Synthesizer]
        S -->|"dynamic dispatch edges"| R[Edge Resolver]
        R -->|"import-aware resolution"| C[Role Classifier]
    end

    subgraph Store["πŸ’Ύ Storage"]
        DB[(SQLite via sql.js)]
        DB --- F[files]
        DB --- N[nodes]
        DB --- E[edges]
    end

    subgraph Serve["πŸ”Œ MCP Server"]
        MCP[JSON-RPC 2.0] --> Cache[LRU Cache]
        Cache --> Q[Query Engine]
        Q --> BFS[BFS Traversal]
        Q --> CTX[Context Builder]
        Q --> ANA[Analysis Engine]
    end

    Index --> DB
    DB --> Serve
    Agent[πŸ€– AI Agent] <-->|stdio| MCP

    style Agent fill:#8B5CF6,color:#fff
    style DB fill:#3B82F6,color:#fff
    style MCP fill:#22C55E,color:#fff
Loading

Design Principles

Principle Implementation
Zero cloud dependencies Pure JS/WASM β€” sql.js instead of better-sqlite3, no native bindings
Incremental by default 3-tier: mtime+size β†’ content hash β†’ parse. Rebuilds only what changed
Import-aware resolution Resolves calls through imports: import match > same-file > global name
Smart role classification Symbols tagged as entry Β· core Β· hub Β· bridge Β· utility Β· leaf Β· test Β· dead
Bounded traversal BFS with maxDepth + maxNodes caps + cycle detection
Token-conscious Context payloads include estimated token counts so agents can budget
Bulk query optimization Adjacency maps loaded in 3 SQL queries β€” all per-node lookups are O(1) map gets

Supported Languages

JavaScript
.js .jsx .mjs .cjs
via @babel/parser
TypeScript
.ts .tsx
via @babel/parser
Python
.py .pyi
regex-based
C / C++
.c .h .cpp .cc .hpp
regex-based Β· #include resolution
Shell
.sh .bash .zsh
regex-based Β· source/. imports
PowerShell
.ps1 .psm1 .psd1
regex-based Β· dot-sourcing

Framework Detection

Route and endpoint extraction for: Express Β· React Router Β· Next.js Β· Flask Β· FastAPI Β· Django

Database Schema

Per-project SQLite at .cgraph/graph.db:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  files   β”‚     β”‚                   nodes                     β”‚     β”‚   edges   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€     β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€     β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ id       │◄───┐│ id Β· file_id Β· name Β· qualified_name        β”‚β”Œβ”€β”€β”€β–Ίβ”‚ source_id β”‚
β”‚ path     β”‚    β”‚β”‚ kind Β· start_line Β· end_line Β· signature    β”‚β”‚    β”‚ target_id β”‚
β”‚ hash     β”‚    └─ doc Β· exported Β· role                       β”œβ”˜    β”‚ kind      β”‚
β”‚ language β”‚     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ mtime    β”‚                        β–²
β”‚ size     β”‚     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”‚         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β”‚ raw_refs β”‚β”€β”€β”€β”€β”€β”€β”€β”˜         β”‚ metadata β”‚
                 β”‚ caller   β”‚                 β”‚ key      β”‚
                 β”‚ callee   β”‚                 β”‚ value    β”‚
                 β”‚ kind     β”‚                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“ Project Structure

cgraph/
β”œβ”€β”€ bin/cgraph.js                  # CLI entry point
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ cli.ts                     # 22 CLI commands (commander)
β”‚   β”œβ”€β”€ config.ts                  # Configuration + .cgraph.json loader
β”‚   β”œβ”€β”€ context.ts                 # Context builder (search β†’ expand β†’ snippets)
β”‚   β”œβ”€β”€ graph.ts                   # BFS traversal, impact, trace, dead code, cycles, suggest
β”‚   β”œβ”€β”€ indexer.ts                 # File walker + parallel parser + incremental edge resolver
β”‚   β”œβ”€β”€ mcp.ts                     # MCP server (22 tools, JSON-RPC 2.0, progress notifications)
β”‚   β”œβ”€β”€ storage.ts                 # GraphDB (sql.js WASM SQLite)
β”‚   β”œβ”€β”€ parser.ts                  # Multi-language parser (babel + regex)
β”‚   β”œβ”€β”€ synthesizer.ts             # Dynamic dispatch edge synthesis
β”‚   β”œβ”€β”€ frameworks.ts              # Framework route extraction
β”‚   β”œβ”€β”€ lint.ts                    # Architecture rule enforcement engine
β”‚   β”œβ”€β”€ search.ts                  # Fuzzy symbol search + BM25 intent search
β”‚   β”œβ”€β”€ export.ts                  # Mermaid / DOT / HTML diagram generation
β”‚   β”œβ”€β”€ cache.ts                   # LRU cache with disk persistence
β”‚   β”œβ”€β”€ watcher.ts                 # File watcher with debounced re-index
β”‚   β”œβ”€β”€ git.ts                     # Git diff β†’ changed symbol mapping
β”‚   β”œβ”€β”€ adaptive.ts                # Dynamic traversal limits
β”‚   β”œβ”€β”€ query-parser.ts            # Search query field extraction
β”‚   β”œβ”€β”€ gitignore.ts               # .gitignore parsing
β”‚   └── types.ts                   # All type definitions
β”œβ”€β”€ __tests__/                     # 216 tests (vitest)
β”œβ”€β”€ scripts/                       # Benchmarks, installers, smoke tests
β”œβ”€β”€ demo/                          # Finance tracker + C++/Shell demos
β”œβ”€β”€ install.ps1 / install.sh       # Standalone installers
└── .cgraph.json                   # Project-level configuration

πŸ§ͺ Development

npm run build              # compile TypeScript
npm run dev                # watch mode (rebuild on save)
npm test                   # run 216 unit tests
npm run test:watch         # watch tests
πŸ“œ All scripts
Script Purpose
install.ps1 / install.sh Standalone installer (downloads Node if needed)
scripts/local-install.ps1 / .sh Build + npm link for dev testing
scripts/smoke-test.ps1 / .sh 22 end-to-end CLI tests
scripts/setup-mcp.ps1 Auto-configure MCP for a project
scripts/benchmark.mjs MCP server latency (22 tools, burst, cold start)
scripts/benchmark-agent.mjs Agent workflow benchmark β€” with vs without cgraph
scripts/benchmark-compare.mjs Raw efficiency comparison (grep+read vs cgraph)

πŸ“š Usage as Library

import { GraphDB } from 'cgraph/storage';
import { indexProject } from 'cgraph/indexer';
import { findCallers, suggestRefactorings } from 'cgraph/graph';
import { buildContext } from 'cgraph/context';

// Index & query
const db = await GraphDB.open('.cgraph/graph.db');
await indexProject('.');

const callers = findCallers(db, 'handleRequest', { maxDepth: 3 });
const suggestions = suggestRefactorings(db, { file: 'src/app.ts' });

db.close();

πŸ“„ License

AGPL-3.0 β€” see LICENSE for details.

For proprietary/closed-source usage, contact the author for a commercial license.


Built with ❀️ for developers who want their AI agents to actually understand their code.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages