Structural code analysis tool powered by Tree-sitter AST parsing.
para-graph is a deterministic code analysis tool that extracts structural information from multi-language codebases and produces a knowledge graph in JSONL format.
It uses Tree-sitter for fast, accurate AST parsing β no compiler pipeline required. The output graph captures:
- Entities β classes, functions, interfaces, arrow functions, methods
- Relationships β imports, function calls, inheritance (future)
Part of the PARA Workspace ecosystem.
- Node.js >= 18.0.0
- TypeScript 5.x
- Tree-sitter (native bindings compiled automatically via
node-gyp-build)
- Multi-Language Support β TypeScript, TSX, Python π, Bash π, Go πΉ, PHP π
- Deep CALLS Capture β Extracts member call chains, object+method pairs, and constructors
- Topological Edge Confidence β Edge classification (
EXTRACTED,INFERRED,AMBIGUOUS) - God Nodes Detection β Runtime degree analytics (
fanIn/fanOut) with SQLite caching to identify architectural choke points - Deterministic parsing β Tree-sitter AST & Pure SSEC Queries, no LLM heuristics
- JSONL & SQLite Dual-Backend β Robust storage with FTS5 semantic search and fast cold starts
- Global Workspace Server β Serve multiple project graphs simultaneously via MCP
- Semantic Enrichment β Agent-driven context tagging (summary, complexity, domain concepts)
- Compact Memory β Architectural logs consolidated in
.beads/graph/for context retention - Fast In-Memory Query Engine β Indexed lookups with LRU cache (Max=3 projects)
- Impact Analysis β BFS traversal to find all affected nodes when changing a code entity
- Context Bundle β Get source code, callers, callees, imports, and tests in one MCP call
- Agentic Edge Resolution β Inject missing relationships (e.g., dynamic Bash imports) directly via MCP
- MCP Auto-Setup β Manifest-declared
mcp:block enables automatic IDE configuration via./para mcp-setup - Agent Auto-trigger Hooks β BeforeTool hooks that nudge the AI Agent to use Knowledge Graph before file scanning
- Atomic File Structure Snapshots (v0.17.0+) β Captures project directory tree snapshots, hashing files (sha256) into SQLite for version tracking.
- Protected Files Guard (v0.17.0+) β Manages protected files list and alerts if any critical files are missing during snapshot verification.
- Session Context Compaction (v0.17.1+) β Scans and compacts active session rules, skills, and project contract, writing a summary to
vibecode_session/artifacts/session.mdfor context recovery. - RRF Hybrid Search Scorer (v0.17.1+) β Integrates Reciprocal Rank Fusion (RRF) to merge FTS5 keyword results and LIKE similarity matches.
- Multi-seed Context Retrieval (v0.17.1+) β Gathers comprehensive context from multiple seed node IDs with topological distance capping (20 per seed, 50 globally).
- Profile-Driven Junk Governance (v0.17.6.1+) β Auto-detects and classifies untracked or ignored junk files based on profile markers (Astro, TypeScript, CF Workers, Python, PHP) or explicit configuration, categorizing them into 3 safety tiers.
Prerequisite: Make sure you have Node.js (>= 18.0.0) and
npminstalled on your system. Notice:better-sqlite3is dynamically installed during setup only for Node < 22 environments to skip native compilation on modern Node versions.
# Clone
git clone https://github.com/pageel/para-graph.git
cd para-graph
# Install
npm install
# Build
npm run build
# Scan a project by name (auto-detects paths)
npx para-graph build my-projectOr run directly without cloning:
npx para-graph build ./src ./output# Scan by project name (auto-detect workspace)
para-graph build <project-name>
# Scan source code and export graph (manual paths)
para-graph build <target-dir> [output-dir] [--clean]
# Inject Graph Data & Validate Drift in Markdown Docs/Plans
para-graph inject <target-dir>
# Take a snapshot of the project directory structure
para-graph project-snapshot <project-name>
# Compare two project snapshots
para-graph project-diff <project-name> <src-snap-id> <tgt-snap-id>
# Start MCP server for AI Agent integration
para-graph serve [workspace-root]
# Manage BeforeTool hooks
para-graph hooks install
para-graph hooks uninstall
para-graph hooks status
# Show help
para-graph --helpThe hooks command manages BeforeTool hooks that automatically nudge your AI Agent to use the Knowledge Graph instead of scanning files blindly.
# Install hook into ~/.gemini/settings.json
para-graph hooks install
# Check current hook status
para-graph hooks status
# Remove hook and restore original settings
para-graph hooks uninstallHow it works:
para-graph buildgenerates the Knowledge Graphpara-graph hooks installinjects a BeforeTool hook into Gemini CLI settings- On the next file access, the Agent receives a context nudge: "Knowledge Graph is available β use MCP tools first"
- A lock file prevents repeated nudging in the same session
para-graph buildautomatically resets the lock after graph updates
# Basic usage
para-graph build my-project # Shorthand (recommended)
para-graph build ./src # Output to ./output/
para-graph build ./src ./my-graph # Custom output directory
para-graph build ./src ./out --clean # Wipe existing graph, scan from scratch| Argument | Required | Default | Description |
|---|---|---|---|
project-name |
β (or target-dir) | β | Name of project in workspace (auto-resolves repo/ and .beads/graph/) |
target-dir |
β (or project-name) | β | Directory containing supported source files |
output-dir |
β | ./output |
Where to write the graph output |
--clean |
β | β | Do not load existing graph, overwrite and scan from scratch |
# Start MCP server (stdio transport)
para-graph serve /path/to/workspace
# Or let it auto-detect the workspace root (if inside one)
para-graph servepara-graph supports AI-driven semantic enrichment, but you should NOT enrich 100% of the graph nodes. We strictly recommend the 20% Rule (Compact Memory Rule):
- Focus on God Nodes: Only enrich the top 10-20% of structural nodes that orchestrate logic (high degree/fan-in/fan-out) and core domain entities.
- Signal-to-Noise Ratio: Simple getters, setters, utilities, and test fixtures should rely entirely on Tree-sitter AST and their names. Enriching them bloats the context window and wastes tokens.
- Semantic Drift Protection: By only enriching core architectural hubs (which change less frequently), you reduce the maintenance burden of keeping semantic summaries synced with the source code.
- Graph-based Inference: The AI can naturally infer the purpose of small utility functions by observing the
CALLSedges connected to a well-enriched God Node.
π‘ Best Practice: When using the
/para-graphworkflow'scompactaction, the system is hardcoded to find and enrich the top 3 God Nodes incrementally per run. Do not attempt to batch-enrich the entire project.
To connect para-graph to an AI Agent editor (like Claude Desktop, Cursor, or Google Antigravity), you need to configure their respective MCP settings.
If you are using PARA Workspace v1.8.2+, you can automatically configure the MCP server in your IDE by running:
./para mcp-setupThis will safely detect your active IDE and inject the para-graph MCP server configuration.
If you prefer to configure the server manually:
Edit your claude_desktop_config.json (or mcp_config.json for Antigravity) and add the following:
{
"mcpServers": {
"para-graph": {
"command": "<ABSOLUTE_WORKSPACE_PATH>/cli/para",
"args": [
"graph",
"serve",
"<ABSOLUTE_WORKSPACE_PATH>"
]
}
}
}Note: Replace <ABSOLUTE_WORKSPACE_PATH> with the absolute path to your PARA Workspace root directory.
Go to Cursor Settings > Features > MCP Servers > Add New MCP Server:
- Name:
para-graph - Type:
command - Command:
<ABSOLUTE_WORKSPACE_PATH>/cli/para graph serve <ABSOLUTE_WORKSPACE_PATH>
Once connected, your AI Agent gains access to the following tools:
graph_query: Search entities by name or semantic type.graph_edges: Find function callers and imports connected to a node.graph_enrich: Save semantic documentation, complexity, and domain concepts to a node.graph_impact_analysis: Discover upstream/downstream affected files and nodes (blast radius) when changing code.graph_context_bundle: Get the entire context of a code snippet (source code, callers, callees, imports, tests) in one call. Supports multi-seed node IDs.graph_add_edges: Batch inject edges (CALLS, IMPORTS_FROM) to resolve relationships for weak AST-linking languages (e.g. Bash).graph_god_nodes: Retrieve the most connected nodes in the graph to prioritize AI enrichment.graph_expand_node: Retrieve only the source code for a specific node with AST bounds checking.graph_link_docs: Link documentation markdown files to graph nodes based on anchor tags.insight_push: Push a project insight (lesson, risk, decision, pattern, gotcha) to the database.insight_search: Search project insights using full-text search with metadata filters.insight_validate: Update the confidence lifecycle of a project insight (hypothesis -> validated -> deprecated).memory_push: Push a session event (conversation, decision, error) to the project MemoryStore.memory_search: Full-text search (FTS5) over stored memory events by keyword.memory_curate: Cluster raw events into semantic slices using session-based curation.graph_audit_csa: Run Convergent Specification Architecture (CSA) compliance audit for a project.graph_fix_csa: Run CSA self-healing fix for dangling spec references (auto-replaces drifted spec anchors in code files).project_snapshot: Take a snapshot of the project directory structure, record metadata to SQLite, and verify protected files. Also detects and classifies physical junk files based on active profiles (auditJunk: true), returning both a backward-compatible flat list and a 3-tier safety report.project_diff: Compare two project snapshots to identify added, removed, and modified files (physical drift detection).project_protected_files: List, add, or remove protected files for a project.project_session_compact: Scan rules, skills, and project contract, and write a compacted context summary for agent recovery.project_state_get: Get cached project metadata and task counts from SQLite. Checks freshness against configuration files via MD5 hashes.project_state_sync: Sync and cache project metadata and task counts from config files (project.md,backlog.md,sprint-current.md) into SQLite database.
// Import as a library
import { CodeGraph } from 'para-graph';
// Import MCP server factory
import { createServer } from 'para-graph/mcp';Three files are generated in the output directory:
One code entity per line, sorted by file path:
{"id":"src/graph/code-graph.ts::CodeGraph","type":"class","name":"CodeGraph","filePath":"src/graph/code-graph.ts","startLine":10,"endLine":81,"exportType":"named","signature":"export class CodeGraph {"}One relationship per line, sorted by source file:
{"sourceId":"src/index.ts","targetId":"./parser/file-walker.js","relation":"IMPORTS_FROM","sourceFile":"src/index.ts","sourceLine":3}Summary statistics:
{
"version": "0.1.0",
"nodeCount": 31,
"edgeCount": 47,
"fileCount": 6,
"createdAt": "2026-04-21T03:35:33.508Z"
}| Type | Description |
|---|---|
file |
Source file |
class |
Class declaration |
function |
Function, method, or arrow function |
interface |
Interface declaration |
variable |
Variable declaration (future) |
| Relation | Description |
|---|---|
IMPORTS_FROM |
File imports from another module |
CALLS |
Function/method calls another function |
INHERITS |
Class extends another (future) |
IMPLEMENTS |
Class implements interface (future) |
src/
βββ cli.ts # Subcommand router (shebang entrypoint)
βββ commands/
β βββ build.ts # Build command β scan, parse, export graph
β βββ serve.ts # Serve command β MCP server lifecycle
β βββ inject.ts # Inject command β Living Docs context
β βββ hooks.ts # Hooks command β BeforeTool hook management
βββ graph/
β βββ models.ts # GraphNode, GraphEdge type definitions
β βββ code-graph.ts # In-memory graph with dual indexing
β βββ jsonl-exporter.ts # Serialize graph β JSONL files
β βββ jsonl-importer.ts # Load graph from JSONL files
β βββ graph-store.ts # LRU cache manager for multi-project graphs
βββ mcp/
β βββ server.ts # MCP server factory (pure library export)
β βββ tools.ts # MCP tools: query, edges, enrich, impact_analysis, context_bundle, add_edges
β βββ resources.ts # MCP resources: JSONL file access
βββ parser/
β βββ registry.ts # Language Registry (lazy-loads parsers by extension)
β βββ tree-sitter-parser.ts # AST parsing and SSEC mapping engine
β βββ file-walker.ts # Recursive multi-language file scanner
βββ queries/
βββ typescript.scm # SSEC query patterns for TS/TSX
βββ python.scm # SSEC query patterns for Python
βββ go.scm # SSEC query patterns for Go
βββ php.scm # SSEC query patterns for PHP
βββ bash.scm # SSEC query patterns for Bash
Source files β File Walker β Registry Lookup β Tree-sitter Parser + SSEC Query β CodeGraph (in-memory) β JSONL Export
β
GraphStore (LRU)
β
MCP Server β AI Agent
When you run ./para install-tool para-graph, the tool is installed and distributes its components across 4 different areas in the PARA Workspace:
workspace-root/
βββ .para/tools/graph/ # [Area A] Tool Engine Core
β βββ dist/ # Compiled JavaScript files
β β βββ cli.js # Main CLI Router
β β βββ mcp/server.js # MCP Server Core
β βββ package.json # Runtime dependencies and version
β βββ tool.manifest.yml # Manifest declaring agent assets
β βββ install-hooks.sh # Post-install hook script
β
βββ Resources/references/para-workspace/cli/commands/graph.sh # [Area B] CLI Shell Wrapper (or Projects/para-workspace/repo/... in dev profile)
β
βββ .agents/ # [Area C] Agent Intelligence
β βββ workflows/para-graph.md # Graph operation workflow
β βββ skills/para-graph/ # Skill for AI Agent interactions
β βββ skills/csa/ # Skill for CSA compliance auditing
β βββ rules/graph-first-policy.md # Rule enforcing graph queries
β βββ rules/csa-compliance.md # Rule enforcing CSA double-binding
β
βββ ~/.gemini/antigravity-ide/knowledge/ # [Area D] Knowledge Items (IDE Context Store)
βββ para_graph_architecture/ # Architecture documentation for AI
βββ para_graph_mcp_tools/ # MCP tools usage instructions
βββ para_graph_workflows/ # CLI commands catalog
- A. Engine Core (
.para/tools/graph/): The actual executable code of the tool, extracted from the release tarball.- No Source Code (
src/): TypeScript source files are omitted. Only compiled JavaScript files exist indist/for zero-overhead runtime. install-hooks.sh: Auto-runs after extraction to trigger dependency installation, synchronize Knowledge Items, and register the MCP server in the IDE configuration.
- No Source Code (
- B. CLI Wrapper (
cli/commands/graph.sh): Sourced by the mainparascript. In production, this wrapper is generated atResources/references/para-workspace/cli/commands/graph.sh. On developer environments with the dev profile active, it installs intoProjects/para-workspace/repo/cli/commands/graph.shinstead. When you run./para graph build ..., this wrapper maps tonode .para/tools/graph/dist/cli.js build ...to execute the engine. - C. Agent Intelligence (
.agents/): Copied from the tool templates to empower the IDE's AI Agent with commands (/para-graph), skills, and rules. - D. Knowledge Items (
~/.gemini/.../knowledge/): Markdown-based context files synchronized to the IDE storage. They provide the AI Agent with immediate awareness of the code graph's architecture, tools, and commands.
# Install dependencies
npm install
# Run in development
npm run dev
# Build TypeScript
npm run build
# Run tests
npm run test| Component | Technology |
|---|---|
| Runtime | Node.js β₯ 18 |
| Language | TypeScript 5.x (strict mode) |
| AST Parser | tree-sitter + tree-sitter-typescript |
| Test Runner | Vitest |
| Dev Runner | tsx |
This tool ships AI intelligence artifacts that enhance the PARA Workspace agent experience. When installed via ./para install-tool para-graph, these artifacts are automatically fetched from GitHub and installed into your workspace's .agents/ directory:
| Type | Name | Version | Description & Usage |
|---|---|---|---|
| Workflow | /para-graph |
2.0.1 | Type @[/para-graph] to instruct the AI to re-scan and update the graph memory. |
| Skill | para-graph | 2.5.0 | Centralized Graph Intelligence Router. Loaded on-demand for workflows like /plan, /docs, /brainstorm to provide graph enrichment and architecture validation. |
| Skill | csa | 1.1.0 | Global Convergent Specification Architecture (CSA) skill for workspace-wide verification and documentation quality gates. |
| Rule | graph-first-policy |
1.1.0 | Enforces graph-first development practices. The agent will proactively query the MCP server before making architecture decisions. |
| Knowledge Item | para_graph_architecture |
β | Describes the core architecture of the hybrid code-knowledge graph, nodes and edges schemas, and directory layout inside the .beads/graph/ folder. |
| Knowledge Item | para_graph_mcp_tools |
β | Instruction guide on using MCP tools (graph_query, graph_context_bundle, etc.) to query and interact with the code graph. |
| Knowledge Item | para_graph_workflows |
β | Guides on integrating para-graph CLI commands (build, serve, link) with the PARA workspace workflows. |
v0.12.0+: AI Intelligence is no longer bundled in the tarball. It is fetched on-demand from GitHub via the
post_install()hook. Update independently:./para install-tool para-graph --sync.Requires PARA Workspace v1.8.5+ for automatic template sync.
| Phase | Description | Status |
|---|---|---|
| P1 | Structural Base (Tree-sitter AST) | β Done |
| P2 | Semantic Enrichment (Agent-Driven) | β Done |
| P3 | Storage & Query Engine | β Done |
| P4 | CLI Integration & NPM Package | β Done |
| P5 | Multi-language Support & Query Refactor | β Done |
| P6 | Impact & Context Queries | β Done |
| P7 | Agentic Bash Edge Resolution | β Done |
| P8 | Deep CALLS + Pattern Detection | β Done |
| P9 | Edge Resolution & Topology Analytics | β Done |
| P10 | Agent Auto-trigger (Hook Injection) | β Done |
| P11 | Compact Memory | β Done |
| P12 | SQLite Storage Engine (Dual Backend) | β Done |
| P13 | Freshness-Aware Memory | β Done |
| P14 | Schema Evolution + Code Search | π Planned |
| P-Vis | Graph Visualization MVP | π Planned |
| PX | Documentation & Stable Release (v1.0.0) | π Planned |