Deep deterministic repository intelligence for AI coding agents (code, dependencies, databases, and runtime observations)
pip install codegraph-engine==2.3.0 Copy PIP instructions
Deterministic Codebase Intelligence for AI Coding Agents. High-performance Model Context Protocol (MCP) server for Claude Code, Cursor, Antigravity, Cline, and Codex.
Documentation Site • PyPI Package • Overview • What's New in v2.3.0 • Quickstart • CLI Outputs • Database Intelligence • Runtime Evidence • Git Intelligence • Benchmarks • 62-Tool Reference • GitHub
When AI coding agents (such as Claude Code, Cursor, or Antigravity) explore complex enterprise repositories, text-based search (grep/ripgrep) forces them to parse large, multi-thousand-line files to reconstruct call chains, router mounts, dependency injection graphs, and ORM schemas. This consumes 60% to 80% of the LLM context window with irrelevant code and frequently leads to hallucinations regarding entity relationships and database structures.
CodeGraph MCP provides deterministic, compiler-grade repository intelligence through the Model Context Protocol. Instead of guessing based on lexical approximations, the AI agent queries a local, persistent SQLite index for verified AST relationships, framework router trees, database lineages, and live runtime observations—resolved in sub-5ms latency.
┌─────────────────────────────────────────────────────────────┐ │ AI CODING AGENT │ │ (Claude Code • Cursor • Antigravity) │ └──────────────────────────────┬──────────────────────────────┘ │ Model Context Protocol (stdio / SSE) ▼ ┌─────────────────────────────────────────────────────────────┐ │ CODEGRAPH MCP ENGINE │ ├──────────────────────────────┬──────────────────────────────┤ │ AST Code Relationships │ Framework Route Hierarchy │ │ (Callers, Callees, DI) │ (FastAPI, Django, Express) │ ├──────────────────────────────┼──────────────────────────────┤ │ Database Lineage & Schemas │ Non-Invasive Dev Tracing │ │ (SQLAlchemy, Prisma, ORM) │ (HTTP metrics, exceptions) │ └──────────────────────────────┴──────────────────────────────┘ │ ▼ Deterministic • Local-First • Verified Evidence Core Architecture Capabilities Zero Hallucination Guarantee: Every returned entity and relationship is statically verified via Abstract Syntax Trees or explicitly flagged as UNKNOWN / POSSIBLE. Sub-5ms Freshness Verification: Monotonic commit tracking validates git rev-parse HEAD and porcelain status instantly, avoiding full-tree re-indexing on unchanged codebases. Context Window Optimization: Yields 65% to 85% token reduction by returning structured, bounded source slices rather than entire file dumps. Zero-Friction Dev Interception (codegraph run): Wraps local development servers (e.g., codegraph run npm run dev, codegraph run uvicorn main:app) to capture real HTTP routes, latencies, and stack traces without application code changes. Multi-Agent Setup (codegraph install): Automatically detects, configures, and verifies integrations for Claude Code, Cursor, Antigravity, and Cline. Supported Languages & Frameworks: Python (FastAPI, Flask, Django, SQLAlchemy, Celery, pytest) and TypeScript / JavaScript (.ts, .tsx, .js, .jsx, Express.js).
Version 2.3.0 introduces compiler-grade Git-Aware Repository Intelligence, allowing AI agents and CI/CD pipelines to understand how code evolves across branches, commits, and working tree edits:
Version 2.2.1 introduced runtime telemetry reconciliation, SQLite WAL concurrency, and multi-transport SSE resilience:
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 server health:
# 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 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).
Wrap your development server transparently to stream real HTTP routes, durations, and uncaught exceptions directly into CodeGraph MCP:
# Node / Express / Next.js codegraph run npm run dev # Python / FastAPI / Uvicorn codegraph run uvicorn main:app --reload # Django codegraph run python manage.py runserver 3. Core Architecture & Mental Model flowchart TD A["AI Coding Agent (Claude, Cursor, Antigravity, Cline)"] --> B["CodeGraph MCP Server (stdio or SSE)"] B --> C["Deterministic Repository Intelligence"] C --> D["AST Semantic Graph (Callers, Callees, References, DI)"] C --> E["Literal & Regex Text Search (search_code)"] C --> F["Bounded Source Inspection (get_file)"] C --> G["Database Intelligence (Tables, ORM, Migrations, R/W)"] C --> H["Zero-Friction Runtime Telemetry (codegraph run)"] 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 tools (codegraph run, ingest_runtime_traces, get_runtime_trace, reconcile_static_runtime) EDITING → Native agent / IDE editing tools 4. Real-World CLI Outputs Below are exact, verifiable outputs produced by CodeGraph MCP v2.2.1:
$ codegraph run python3 -c "print('>> Dev server active on port 8000')" >> Dev server active on port 8000 HTTP requests, status codes, and exceptions are automatically streamed to .codegraph/runtime.sqlite3 with child exit codes preserved.
$ codegraph status . { "repository": "/Users/raghuram/Documents/ChatGPT/MCP", "freshness": "FRESH", "freshness_detail": "Index matches current repository state.", "files": 190, "chunks": 1965, "symbols": 1947, "framework_routes": 0, "graph_edges": 12712, "resource_profile": "BALANCED", "pressure_level": "NORMAL", "activity_mode": "IDLE", "estimated_memory_mb": 43.23, "modified_files": [], "deleted_files": [], "parse_failed_files": [] } Validated in < 5ms via the Git commit diff fast path.
$ codegraph index --verbose Phase: Repository Scan 190 / 190 files | 100% | elapsed: 0.09s | rate: 128,203 files/min | memory: 42 MB Phase: Post-Processing 190 / 190 files | 100% | elapsed: 0.62s | rate: 18,273 files/min | memory: 67 MB Phase: Symbol Resolution 190 / 190 files | 100% | elapsed: 0.80s | rate: 14,311 files/min | memory: 91 MB Phase: Relationship Resolution 190 / 190 files | 100% | elapsed: 1.49s | rate: 7,648 files/min | memory: 116 MB Phase: Database Analysis 190 / 190 files | 100% | elapsed: 1.77s | rate: 6,424 files/min | memory: 120 MB Phase: Final Commit & Checkpoint 190 / 190 files | 100% | elapsed: 2.59s | rate: 4,396 files/min | memory: 141 MB Summary: elapsed=2.595s peak_rss=141.0MB max_wal=9.44MB final_wal=0.00MB commits=15 checkpoints=15 [repository_scan] 88.1ms files=190 items=190 writes=0 [ast_parsing] 154.7ms files=13 items=3322 writes=0 [database_analysis] 283.9ms files=13 items=1631 writes=0 [symbol_resolution] 52.5ms files=190 items=5854 writes=0 [relationship_resolution] 694.0ms files=190 items=32806 writes=0 [sqlite_writes] 1146.4ms files=13 items=50206 writes=50208 scanned=190 indexed=13 unchanged=177 removed=0 4. Bounded Monorepo Route Discovery (codegraph routes --limit 3) $ codegraph routes --limit 3 Found 3 route(s): [GET] /api/v1/health -> health_check (src/app/api.py:14) [fastapi] [POST] /api/v1/orders -> create_order (src/app/orders.py:42) [fastapi] [GET] /api/v1/users/{id} -> get_user (src/app/users.py:88) [fastapi] 5. Safe Background Process Termination (codegraph stop --json) $ codegraph stop --json { "status": "ok", "stopped_count": 0, "stale_cleaned_count": 0, "processes": [] } 5. 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:
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).
POST /orders ↓ HANDLED_BY (FRAMEWORK_VERIFIED) OrderService.create_order ↓ CALLS (AST_VERIFIED) OrderRepository.insert_order ↓ WRITES_TABLE (AST_VERIFIED) db:table:postgresql.public.orders ↓ FOREIGN_KEY_TO (AST_VERIFIED) orders.user_id ──► users.id Capabilities Exposed by the 11 Database MCP Tools Table & Column Discovery (get_db_schema, get_db_table, find_db_tables, find_db_columns): Extract tables, column types, nullability, defaults, primary keys (HAS_PRIMARY_KEY), indexes (HAS_INDEX), unique/check constraints, and foreign keys (FOREIGN_KEY_TO). ORM Mapping (find_db_models): Map SQLAlchemy __tablename__, Django models.Model (Meta.db_table), SQLModel table=True, and Prisma model blocks via MAPS_TO_TABLE and MAPS_TO_COLUMN. Readers, Writers & Callers (find_db_readers, find_db_writers, find_db_callers, find_db_queries): Identify every function or method that executes SELECT (READS_TABLE) or INSERT / UPDATE / DELETE / .add() / .save() (WRITES_TABLE) against a table. Migration Lineage & Schema Blast Radius (find_db_relationships, get_db_impact): Track Alembic (op.create_table, op.add_column) and Django (migrations.CreateModel, migrations.AddField) operations (MIGRATES_TABLE) and compute bidirectional code $\leftrightarrow$ database impact. 7. Zero-Friction Runtime Intelligence & Static Reconciliation Static analysis proves what can happen structurally; runtime telemetry records what was observed during execution. CodeGraph MCP v2.2.1 brings them together transparently:
STATIC GRAPH (AST + Framework + Dataflow + DB) + RUNTIME OBSERVATION (codegraph run / OTel JSON / JSONL / 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 recorded trace sample. RUNTIME_ONLY_OBSERVED Dynamic / UNKNOWN Observed Executed at runtime (e.g., plugin hook, getattr, dynamic SQL) where static analysis was UNKNOWN. STATIC_RUNTIME_CONFLICT Target A Target B Runtime execution dispatched to a different target than static resolution (e.g., dependency override). Epistemic Rules for Runtime Evidence Runtime Telemetry Is Non-Invasive: codegraph run uses standard environment variable hooks (NODE_OPTIONS, PYTHONSTARTUP). You never modify application source code. NOT_OBSERVED_AT_RUNTIME Does Not Mean Dead Code: It only indicates that the code path was not triggered during the recorded trace window (such as an error branch or periodic batch job). Runtime Observations Never Overwrite Static Proof: Runtime spans are recorded with evidence_class="RUNTIME_OBSERVED" and strictly distinguished from AST_VERIFIED and FRAMEWORK_VERIFIED static edges. 8. Epistemic Trust & Evidence Contract CodeGraph MCP enforces a fail-closed evidence contract (src/codegraph/evidence_contract.py) across all 51 canonical relationship types and 9 evidence classes. CodeGraph MCP 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) 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 traces captured by codegraph run or ingested OTel/JSONL/SQL logs (hit_count, duration_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 dependency, or reason="resolution_budget_exceeded"). CONFLICT Static vs. Runtime / Multi-Source Static analysis and runtime observation (or competing definitions) disagree. 8. Git-Aware Repository Intelligence & Merge Conflict Safety CodeGraph MCP v2.3.0 tracks the exact evolution of repository code across commits, branches, and working tree changes:
Repository state ↓ Git change detection (CLEAN / DIRTY / STALE) ↓ Structural AST diff (functions, parameters, routes) ↓ Downstream impact analysis (callers, callees, tests, DB) ↓ Context freshness validation (VALID / PARTIALLY_STALE / STALE) ↓ Evidence-backed answer 1. Working Tree & Index Freshness (codegraph git-state) Tracks current branch, current HEAD commit, indexed commit, and modified/staged files with sub-millisecond status caching:
codegraph git-state Never silently serves stale repository facts. Explicitly reports CLEAN, DIRTY, STALE, REINDEXING, or ERROR.
Traverses affected callers, routes, tests, and DB writers with token-bounded results and visual ASCII hierarchy:
codegraph git-impact --tree 3. Semantic & Contract Merge Conflicts (codegraph git-conflicts) Detects silent merge conflicts before git merge or pull request landing—such as branch A invoking a function or route handler that branch B deleted or altered:
codegraph git-conflicts main HEAD 4. Structural AST Diff (codegraph git-diff) Computes semantic AST differences between Git revisions (added/removed/modified symbols, changed parameter signatures):
codegraph git-diff HEAD~1 HEAD 5. Deterministic Symbol History (codegraph symbol-history) Traces symbol lifecycle across commits (introduced, modified, moved, renamed, or deleted):
codegraph symbol-history resolve_target 6. GitHub Action for Pull Request Impact Automate change impact directly in your CI pipeline with .github/workflows/codegraph-pr-impact.yml and .github/actions/codegraph-impact/action.yml.
Recorded using benchmarks/run_v217_indexing_benchmark.py on macOS arm64, Python 3.13 with permanent SQLite WAL concurrency:
Evaluated across 50 production tasks and 10 categories via benchmarks/run_v21_eval.py:
CodeGraph MCP works alongside your editor's language server (LSP), ripgrep, and structural AST tools:
Legend: ✓ supported • ◐ partial / workflow-dependent • — not supported
CodeGraph MCP runs 100% locally (stdio / sse 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 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.
# 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 --yes # Remove CodeGraph MCP agent integrations # Zero-Friction Runtime Interceptor (v2.2.1) codegraph run npm run dev # Wrap Node/Express/Next.js dev server codegraph run uvicorn main:app --reload # Wrap FastAPI/ASGI dev server codegraph run python manage.py runserver # Wrap Django dev server codegraph run --sample-rate 0.5 npm test # Sample 50% of captured traces # 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 doctor --processes # Inspect active MCP processes & parent PIDs # Health, Integrity & Freshness Diagnostics codegraph status . # Show index freshness (sub-50ms Git fast path) codegraph doctor . --database --processes # Verify SQLite integrity, FKs, FTS, and memory codegraph privacy . # Verify zero sensitive files indexed codegraph version # Print CodeGraph MCP version (2.2.1) # Code, Graph, Routes & Context Interrogation codegraph search "authenticate" -r . # Search indexed symbols and text 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 candidates codegraph trace Indexer -d 2 -r . # Trace callers and callees up to depth 2 codegraph routes -r . --limit 25 --offset 0 # List routes with bounded pagination codegraph architecture -r . # Summarize repository architecture codegraph context "trace /api/v1/auth/login" -r . # Compile token-budgeted ContextPacket # MCP Server Subcommands codegraph serve . # Start stdio MCP server (14 default tools) codegraph serve . --profile full # Start stdio MCP server with all 56 tools codegraph serve . --transport sse --port 8765 # Start SSE HTTP server on port 8765 codegraph mcp serve . --transport sse # Alias for SSE MCP server codegraph mcp stop # Stop active MCP processes 14. 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 Scaling Benchmark Script: benchmarks/run_v217_indexing_benchmark.py Changelog: CHANGELOG.md 15. 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.




