Deep deterministic repository intelligence for AI coding agents (code, dependencies, databases, and runtime observations)
pip install codegraph-engine==2.2.0 Copy PIP instructions
PyPI (v2.2.0) • Quickstart • Built For • Database Intelligence • Runtime Evidence • Measured Performance • 56-Tool Reference • GitHub
The AI reasons. CodeGraph interrogates the repository. The evidence stays traceable. CodeGraph MCP gives AI coding agents an evidence-backed understanding of code, dependencies, databases, and optional runtime observations.
Supported Languages & Frameworks: First-class Python (FastAPI, Flask, Django, SQLAlchemy, Celery, pytest) + TypeScript / JavaScript (.ts, .tsx, .js, .jsx) & Express.js support.
Complex repository ↓ AI agent needs architectural & dataflow understanding ↓ CodeGraph interrogates the local repository index ↓ Compact, cited evidence (symbols, edges, tables, bounded slices) ↓ AI reasons and edits with traceable citations 30-Second Install pip install "codegraph-engine[mcp]" codegraph install cd your-project codegraph init codegraph doctor 1. Built for AI/ML and Backend-Heavy Repositories CodeGraph is engineered for AI/ML engineers, LLM application developers, model/inference engineers, backend Python & TypeScript/JS developers, and maintainers of large multi-package repositories where relationships cross module, framework, and database boundaries.
pip install "codegraph-engine[mcp]" Step 2: Configure Your AI Coding Agents (codegraph install) CodeGraph-MCP includes an interactive, idempotent onboarding installer (src/codegraph/installer.py) that detects installed AI coding agents (Claude Code, Cursor, Antigravity, Codex CLI, Gemini CLI, and Cline), configures mcpServers.codegraph, installs marker-bounded routing instructions ( … ), and verifies MCP server startup:
# Interactive setup (detects installed agents, previews planned changes, asks confirmation) codegraph install # Non-interactive setup for all detected agents in the current project codegraph install --yes --target auto --location local # Preview exact file modifications without writing anything codegraph install --dry-run Step 3: Initialize & Verify Your Project Index cd your-project codegraph init codegraph status codegraph doctor Dynamic Index Hot-Reloading: If your AI coding agent launches codegraph mcp serve before you run codegraph init, you do not need to restart your IDE or MCP session. As soon as codegraph init or codegraph index creates or updates .codegraph.sqlite3, the running MCP server automatically detects the updated database on the next tool call and refreshes its in-memory graph cache (get_repository_status(reload=True, reindex=True) can also be invoked directly by the agent).
CodeGraph cleanly separates agent configuration, process lifecycle, and project index files:
On Windows, running pip install --upgrade codegraph-engine while an IDE or agent still holds codegraph.exe open can trigger WinError 32. Before upgrading on Windows, run:
codegraph stop --all pip install --upgrade "codegraph-engine[mcp]" 3. Core Workflow & Architecture flowchart TD A["AI Coding Agent"] --> B["CodeGraph MCP"] B --> C["Repository Intelligence"] C --> D["Semantic Graph"] C --> E["Text Search (search_code)"] C --> F["Source Inspection (get_file)"] C --> G["Database Intelligence"] C --> H["Runtime Observation"] D --> I["Structured Evidence + Epistemic Labels"] E --> I F --> I G --> I H --> I I --> J["Context Optimization + Secret Redaction"] J --> A Routing Each Question to the Right Primitive STRUCTURAL → Graph tools (find_symbol, find_callers, find_callees, find_references, find_routes) TEXTUAL → search_code (literal/regex search across Python, HTML/Jinja, JS/TS, CSS, YAML/JSON, SQL) SOURCE → get_file (bounded start_line..end_line source inspection with truncation metadata) GRAPH → Trace tools (trace_path, trace_flow, analyze_impact, get_git_impact) DATABASE → Database tools (get_db_schema, find_db_tables, find_db_readers, find_db_writers, get_db_impact) RUNTIME → Runtime/reconciliation tools (ingest_runtime_traces, get_runtime_trace, reconcile_static_runtime) EDITING → Native agent / IDE editing tools 4. AI/ML & Backend Architecture Examples Example 1: Model Inference Service Flow POST /v1/predict (FastAPI Route) ↓ HANDLED_BY (FRAMEWORK_VERIFIED) predict_endpoint (Handler) ↓ INJECTS (DATAFLOW_VERIFIED) get_inference_service (DI Provider) ↓ CALLS (AST_VERIFIED) InferenceService.run_inference ├──►CALLS (AST_VERIFIED) ──► FeaturePreprocessor.transform ├──►CALLS (AST_VERIFIED) ──► FraudClassifier.forward ├──►CALLS (AST_VERIFIED) ──► ScorePostprocessor.calibrate └──►CALLS (AST_VERIFIED) ──► PredictionRepository.log_prediction ↓ WRITES_TABLE (AST_VERIFIED) db:table:postgresql.public.prediction_logs What CodeGraph-MCP structurally proves:
train_cli (CLI Command Handler) ↓ COMMAND_HANDLER (FRAMEWORK_VERIFIED) TrainingPipeline.run ├──►CALLS (AST_VERIFIED) ──► DatasetBuilder.load_splits ├──►CALLS (AST_VERIFIED) ──► TokenizerTransform.encode_batch ├──►CALLS (AST_VERIFIED) ──► Trainer.fit_epoch ├──►CALLS (AST_VERIFIED) ──► CheckpointManager.save_weights └──►CALLS (AST_VERIFIED) ──► Evaluator.compute_metrics What CodeGraph-MCP structurally proves:
POST /api/chat (LLM Endpoint) ↓ HANDLED_BY (FRAMEWORK_VERIFIED) chat_handler ↓ CALLS (AST_VERIFIED) AgentRunner.execute_step ├──►REGISTERS / REGISTERED_HANDLER ──► ToolRegistry ("search_orders", "refund_order") ├──►CALLS (AST_VERIFIED) ──► ContextBuilder.compile ├──►READS_TABLE (AST_VERIFIED) ──► db:table:postgresql.public.conversations └──►CALLS (AST_VERIFIED) ──► ModelProviderClient.generate What CodeGraph-MCP structurally proves:
Validated end-to-end in src/codegraph/tool_selection_eval.py (run_dundoo_bill_scanner_e2e_eval()):
Developer Prompt: "Wire up AI bill scanning next to the Manual Entry button" │ ├── 1. get_architecture() → Maps app/, templates/, static/js/, tests/ ├── 2. search_code(query="Add Manual Entry") → Matches templates/bills.html:6 ├── 3. get_file(path="templates/bills.html", 1..12) → Reads bounded 12-line HTML slice ├── 4. find_routes(path="/api/scan-bill") → Resolves POST /api/scan-bill → scan_bill_endpoint ├── 5. find_symbol(symbol="parse_bill") → Grounds app/bill_scanner.py::parse_bill ├── 6. get_file(path="app/bill_scanner.py", 1..20) → Reads parse_bill() and normalize_line_items() ├── 7. find_callers(symbol="parse_bill") → Confirms scan_bill_endpoint calls parse_bill └── 8. find_tests(symbol="parse_bill") → Finds test_parse_bill_calculates_total 5. Database Intelligence src/codegraph/database/ provides static schema, ORM model, migration, and query extraction across SQLAlchemy, Django ORM, SQLModel, Prisma (.prisma), Alembic, Django Migrations, and Raw SQL (PostgreSQL, MySQL, SQLite).
STATIC GRAPH (AST + Framework + Dataflow + DB) + OPTIONAL RUNTIME OBSERVATION (OTel JSON / JSONL Events / SQL Logs) ↓ reconcile_static_runtime() Reconciliation Outcomes (ReconciliationStatus) Reconciliation Status Static Graph Runtime Trace Meaning CONFIRMED_RUNTIME_PATH Present Observed Static relationship is structurally proven and observed executing in ingested traces. NOT_OBSERVED_AT_RUNTIME Present Not observed Statically valid edge was not exercised in the ingested trace sample. RUNTIME_ONLY_OBSERVED Dynamic / UNKNOWN Observed Executed at runtime (e.g., plugin hook, getattr, dynamic SQL) where static analysis remained UNKNOWN. STATIC_RUNTIME_CONFLICT Target A Target B Runtime execution dispatched to a different target than static resolution (e.g., dependency override or subclass). Epistemic Rules for Runtime Evidence Runtime Telemetry Is Opt-In & Observational: CodeGraph never instruments or executes your code automatically. Traces are ingested only when you call ingest_runtime_traces on OpenTelemetry JSON, structured JSONL, or SQL log files. NOT_OBSERVED_AT_RUNTIME Does Not Mean Dead Code: It only means the code path was not triggered during the recorded trace window (for example, an error handler, admin route, or periodic job). Runtime Observations Never Overwrite Static Proof: Runtime spans are stored with evidence_class="RUNTIME_OBSERVED" and kept distinct from AST_VERIFIED, FRAMEWORK_VERIFIED, and DATAFLOW_VERIFIED static edges. 7. Epistemic Trust & Evidence Contract CodeGraph enforces a fail-closed evidence contract (src/codegraph/evidence_contract.py) across all 51 canonical relationship types and 9 evidence classes. CodeGraph prefers explicit uncertainty over fabricated certainty:
Dynamically resolved target (getattr(handler, action_name)()) ↓ UNRESOLVED_REFERENCE / POSSIBLE_CALLS (status = "UNKNOWN" | "POSSIBLE") (Never fabricated into a verified CALLS edge) Current Evidence Vocabulary (src/codegraph/evidence_contract.py) Epistemic Status Allowed Evidence Classes What It Means FACT AST_VERIFIED, STATIC_VERIFIED, FRAMEWORK_VERIFIED, DATAFLOW_VERIFIED Proven directly from syntax tree, framework decorator/router semantics, or conservative local dataflow. RUNTIME_OBSERVED RUNTIME_OBSERVED Observed in user-supplied OpenTelemetry, JSONL, or SQL query logs (hit_count, p50_ms, p95_ms). POSSIBLE POSSIBLE Plausible candidate relationship (POSSIBLE_CALLS, POSSIBLE_TABLE) requiring source inspection before mutation. AMBIGUOUS AMBIGUOUS Multiple symbols or database tables match the bare identifier across modules or dialects; returns sorted candidates. UNKNOWN UNKNOWN, RUNTIME_UNOBSERVED Target cannot be statically proven (dynamic reflection, external unindexed dependency, or reason="resolution_budget_exceeded"). CONFLICT Static vs. Runtime / Multi-Source Static analysis and runtime observation (or competing definitions) disagree. 8. Measured Performance (v2.1.6 → v2.1.7) Methodology All indexing measurements below were recorded using benchmarks/run_v217_indexing_benchmark.py on the same machine (macOS arm64, Python 3.13), same repository fixtures, and same 16-phase telemetry harness, comparing v2.1.6 (benchmarks/reports/v217_before_metrics.json) against v2.1.7 (benchmarks/reports/v217_after_metrics.json).
Home Assistant Core is a large, complex public Python repository used as a real-world stress case for CodeGraph's indexing and post-processing pipeline.
During external stress testing on a Home Assistant Core checkout (~28,573 files), pre-v2.1.7 indexing exhibited:
To profile and verify fixes deterministically in CI, benchmarks/run_v217_indexing_benchmark.py provisions a 4-tier Home Assistant-architecture fixture (homeassistant/core, homeassistant/helpers, homeassistant/components/recorder SQLAlchemy models/queries, 500 component domains, and pytest fixture suites; 2,504 files, 5,015 symbols, 18,528 edges):
Rather than claiming a single universal token reduction percentage across all possible prompts, CodeGraph records candidate-vs-selected token metrics on every get_context call:
The table below reports results from the 32-task internal evaluation harness (run_tool_selection_ab_benchmark()) comparing Mode A (unassisted grep + full-file reading without CodeGraph routing rules) against Mode B (CodeGraph MCP + agent routing rules) on the same 32 tasks:
CodeGraph is designed to work alongside your editor's language server (LSP), ripgrep, and structural AST tools.
Legend: ✓ supported • ◐ partial / workflow-dependent • — not established by cited documentation
For the complete multi-tool comparison and official references ([1] LSP Specification, [2] ast-grep, [3] ripgrep, [4] Sourcegraph MCP, [5] Colby McHenry CodeGraph, [6] GitHub Code Navigation), see docs/tool-comparison.md.
CodeGraph runs 100% locally (stdio MCP + local .codegraph.sqlite3), never executes repository code during indexing, and enforces strict file-access and redaction boundaries (src/codegraph/security/paths.py, src/codegraph/security/redaction.py).
Run codegraph privacy . at any time to audit the local SQLite database and verify that no sensitive files or unredacted secrets are stored.
By default, create_server() exposes the 14-tool agent profile so AI coding agents receive a focused, non-overlapping tool surface. All 56 tools are available under --profile full.
See docs/agent-brain.md and agent-rules/tool-capabilities-summary.md for the complete 56-tool reference.
Every command below is verified against src/codegraph/cli.py:
# Agent Onboarding & Uninstall codegraph install # Interactive agent detection & setup codegraph install --yes --target auto --location local # Non-interactive local setup codegraph install --print-config claude # Print MCP JSON + rules for an agent codegraph install --dry-run # Preview planned file changes codegraph uninstall --dry-run # Preview removal of CodeGraph agent blocks codegraph uninstall --yes # Remove CodeGraph agent integrations # Repository Initialization & Indexing codegraph init . # Initialize and index repository codegraph index . --verbose # Incremental index with 16-phase telemetry codegraph index . --json # Output structured JSON phase telemetry codegraph uninit --dry-run # Preview removal of .codegraph.sqlite3 # Process Lifecycle & Upgrade Lock Safety codegraph stop # Safely stop CodeGraph MCP server for current repo codegraph stop --all # Stop all CodeGraph-owned MCP processes across repos codegraph stop --repo /path/to/repo --json # Stop MCP processes for a specific repo (JSON output) codegraph doctor --processes # Inspect active MCP processes, parent PIDs, & stale locks # Health, Integrity & Privacy Diagnostics codegraph status . # Show index freshness and graph counts codegraph doctor . --database --resources # Verify SQLite integrity, FKs, FTS, and memory codegraph privacy . # Verify zero sensitive files indexed codegraph version # Print CodeGraph version (2.1.7) # Code, Graph & Context Interrogation codegraph search "authenticate" -r . # Search indexed symbols and chunks codegraph symbols src/codegraph/cli.py -r . # List extracted symbols in a file codegraph get-symbol Indexer -r . # Get AST details for a symbol codegraph resolve-symbol resolve_Repository -r . # Ground symbol or return ambiguous candidates codegraph resolve Indexer -r . # Resolve symbol with callers and callees codegraph trace Indexer -d 2 -r . # Trace callers and callees up to depth 2 codegraph graph -r . # Summarize graph nodes and edges codegraph routes -r . # List discovered HTTP routes codegraph imports src/codegraph/cli.py -r . # List file/module imports codegraph dependents src/codegraph/cli.py -r . # List reverse dependents codegraph architecture -r . # Summarize repository architecture codegraph debug "trace authentication flow" -r . # Return facts and debugging hypotheses codegraph task "trace /api/v1/auth/login" # Normalize prompt into a TaskSpec codegraph plan "trace /api/v1/auth/login" -r . # Build deterministic RetrievalPlan codegraph context "trace /api/v1/auth/login" -r . # Compile token-budgeted ContextPacket codegraph explain-context "trace /api/v1/auth/login" -r . # ContextPacket with budget rejection reasons codegraph memory list -r . # Inspect repository-scoped notes codegraph benchmark -r . # Run deterministic benchmark suite # MCP Server Subcommands codegraph mcp serve . # Start stdio MCP server (with parent/EOF lifecycle guard) codegraph mcp serve . --profile full # Start stdio MCP server with all 56 tools codegraph mcp stop # Alias for codegraph stop codegraph mcp kill # Alias for codegraph stop (1s graceful timeout) codegraph mcp doctor . # End-to-end MCP startup & query check codegraph mcp config-check . # Read-only MCP config validation codegraph mcp capabilities # Print machine-readable capability manifest codegraph mcp rules --agent claude # Render agent rules for a specific agent 15. Honest Limitations Dynamic Metaprogramming & Reflection: Calls constructed dynamically (getattr(obj, dynamic_name)(), eval, exec, importlib.import_module(var), or runtime monkey-patching) cannot be proven statically. CodeGraph intentionally records these as UNKNOWN (UNRESOLVED_REFERENCE or POSSIBLE_CALLS) rather than inventing edges. Bounded Wildcard & Re-Export Chains: To guarantee termination on pathological repositories with circular from x import * chains, resolution halts at max_reexport_depth=16 (max_wildcard_expansions=64) and emits UNKNOWN with reason="resolution_budget_exceeded". Python-First Depth vs. JS/TS Secondary Support: Python receives deep AST, decorator, local dataflow (LocalBindingResolver), FastAPI/Flask/Django route, and SQLAlchemy/Django/SQLModel/Alembic analysis. JavaScript/TypeScript supports functions, classes, imports, calls, Express routes, and Prisma schemas, without full TypeScript compiler type evaluation. Opt-In Runtime Telemetry Scope: Runtime edges (RUNTIME_OBSERVED) reflect only the trace files you explicitly ingest. Unobserved paths (NOT_OBSERVED_AT_RUNTIME) are not dead code. Very Large Pathological Repositories: While v2.1.7 reduces indexing time by 39.1% and caps WAL size via chunked commits, initial cold indexing on repositories with tens of thousands of files still requires proportional CPU and disk I/O time (subsequent runs are incremental). 16. Documentation Map Deep Agent Brain & 56-Tool Reference: docs/agent-brain.md Compact Tool Capabilities Summary: agent-rules/tool-capabilities-summary.md Detailed Multi-Tool Capability Comparison: docs/tool-comparison.md Antigravity Skill (SKILL.md): .agents/skills/codegraph/SKILL.md Agent Rule Packs (Claude, Cursor, Antigravity, Codex, Gemini, Cline): agent-rules/README.md & agent-rules/AGENTS.md Engineering & Production Readiness: docs/engineering/production-readiness.md Reproducible v2.1.7 Benchmark Script & Artifacts: benchmarks/run_v217_indexing_benchmark.py, benchmarks/reports/v217_before_metrics.json, benchmarks/reports/v217_after_metrics.json Changelog: CHANGELOG.md 17. Contributing & License git clone https://github.com/raghurammrsd/CODE_GRAPH_MCP.git cd CODE_GRAPH_MCP python3 -m venv .venv source .venv/bin/activate pip install -e ".[dev,mcp,system]" python3 -m ruff check . python3 -m mypy src/ python3 -m pytest -q Licensed under the MIT License.
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.




