codegraph-mcp-lite
by nanyun818
README.md
# codegraph-mcp-lite
> **Zero-dependency local codebase knowledge graph, cross-stack call-chain tracer, refactor blast-radius analyzer & ADR memory MCP Server — inspired by [DeusData/codebase-memory-mcp](https://github.com/DeusData/codebase-memory-mcp).**
>
> **零外部依赖、纯 Python 标准库实现的本地多语言代码知识图谱(Call Graph + Import Graph + 跨前后端路由桥接 + ADR 架构记忆库)CLI 与 MCP Server —— 受近期高热开源项目 [DeusData/codebase-memory-mcp](https://github.com/DeusData/codebase-memory-mcp) 启发,3 毫秒内精准回答“改这个函数会影响哪些上下游文件、接口和前端组件”。**
[](./LICENSE)
[](./pyproject.toml)
[](./pyproject.toml)
[](./src/codegraph_mcp_lite/mcp_server.py)
---
## Why `codegraph-mcp-lite`? / 痛点与核心价值
AI Coding Agents (Claude Code, Cursor, Codex, Gemini CLI) suffer from **structural context blindness**:
- **Wasteful Grep Loops**: Asking *"What breaks if I change `LedgerStore.append_entry`?"* triggers 10–20 rounds of `grep` and full-file reads, burning tens of thousands of context tokens while still missing polymorphic subclass overrides (`OVERRIDES`) or frontend `fetch("/api/...")` callers.
- **Cross-Session Architectural Amnesia**: Agents repeatedly violate past architectural invariants (e.g., removing idempotency keys or timing-safe HMAC checks) because Architecture Decision Records (ADRs) are disconnected from symbol lookup tools.
当 AI 编程助手准备重构某个底层函数时,往往需要反复执行 `grep` 并通读十几个源文件,不仅消耗海量上下文 Token,还极易漏掉**子类多态重写(Override)**或**跨语言 HTTP 路由调用方(如 TypeScript `fetch("/api/v1/checkout")` 调用 Python FastAPI 路由)**。
**`codegraph-mcp-lite` turns your repository into a persistent SQLite WAL knowledge graph in milliseconds**:
1. **Incremental SHA-256 Graph Indexing**: Deep Python `ast` analysis (class inheritance, `self.service.method()` type inference, relative imports, `@app.get/post` route decorators) + polyglot brace-scope parsing for **TypeScript, JavaScript, and Go**. Warm re-indexing skips unchanged files in **~2 ms**.
2. **Cross-Stack Blast-Radius & Risk Scoring (`impact`)**: Reverse BFS across `CALLS`, `CALLS_ROUTE`, `OVERRIDES`, and `INHERITS` computes a deterministic `0–100` refactor risk score, listing direct/transitive callers, exposed HTTP endpoints, covering tests, and active **ADR guardrails**.
3. **Shortest Execution Path Tracer (`trace --to`)**: Instantly finds the exact multi-hop call chain from a TypeScript UI widget (`CheckoutWidget.submitOrder`) through FastAPI endpoints down to cryptographic or ledger primitives.
4. **Architectural Hygiene (`cycles` & `hotspots`)**: Built-in **Tarjan Strongly Connected Components (SCC)** circular import/recursion detector + **PageRank** coupling hotspot analyzer + **Mermaid** diagram exporter.
5. **100% Stdlib, Zero Binary/Build Friction**: Runs out of the box on Windows, macOS, and Linux with Python 3.10+—no C compilers, no Tree-sitter shared-library builds, and zero API keys required.
---
## Architecture / 核心架构图
```mermaid
flowchart LR
Repo["Polyglot Source Repo<br/>(Python / TS / JS / Go)"] --> Hash["Incremental SHA-256<br/>Change Detector"]
Hash --> PyAST["Python Deep AST Extractor<br/>(Classes, Self Attr Types, Routes)"]
Hash --> Poly["Polyglot Lexical/Brace Parser<br/>(TS / JS / Go + fetch('/api/...')"]
PyAST & Poly --> Linker["Cross-File Graph Linker<br/>(CALLS / IMPORTS / INHERITS / OVERRIDES / CALLS_ROUTE)"]
Linker --> Store[("SQLite WAL + FTS5<br/>.codegraph/graph.sqlite3")]
ADR["ADR Memory Ledger<br/>(Scope Glob Guardrails)"] --> Store
Store --> Impact["BFS Blast-Radius &<br/>Risk Analyzer"]
Store --> Trace["Shortest Call-Path<br/>& Neighborhood Tracer"]
Store --> Hygiene["Tarjan Cycle Detector &<br/>PageRank Hotspots"]
Impact & Trace & Hygiene <--> Agent["AI Coding Agent<br/>stdio MCP Server / CLI / SKILL.md"]
```
---
## Inspired By & Architecture Comparison / 致敬与架构对比
> **Inspired by**: [**DeusData/codebase-memory-mcp**](https://github.com/DeusData/codebase-memory-mcp). Full credit to the DeusData team for pioneering persistent SQLite code knowledge graphs, call-path tracing, and integrated ADR memory for MCP coding agents.
`codegraph-mcp-lite` is a clean-room, educational, **zero-dependency Python stdlib implementation** crafted for instant hackability, cross-stack HTTP route bridging, and zero-build portability:
| Dimension / 维度 | `DeusData/codebase-memory-mcp` (Upstream) | `codegraph-mcp-lite` (This Repo) |
| :--- | :--- | :--- |
| **Implementation / 语言实现** | High-performance native C static binary + Tree-sitter + Hybrid LSP | **~1,100 LOC pure Python 3.10+ stdlib** (`ast`, `sqlite3`, `re`, `hashlib` only) |
| **Runtime Dependencies / 依赖** | Prebuilt platform binary / Tree-sitter grammars | **0 external packages** (`pip install -e .` or run directly from source anywhere) |
| **Supported Languages / 语言支持** | 150+ languages via Tree-sitter | **Python (deep AST)** + **TypeScript / JavaScript / Go** (comment/string-masked brace parser) |
| **Cross-Stack Route Bridge** | Service & HTTP route graph indexing | **Automatic TS/JS/Py HTTP client (`fetch("/api/...")`) -> `@app.post("/api/...")` edge linking** |
| **Graph Algorithms / 图算法** | Cypher-like queries, call tracing, semantic search | **Reverse-BFS Risk Scoring**, **Shortest Call Path (`--to`)**, **Tarjan Cycle SCC**, **PageRank Hotspots**, **Mermaid Export** |
| **Architectural Memory / 决策记忆** | `manage_adr` persistent ADR tools | **Glob-scoped ADR Ledger** automatically surfaced as guardrails inside `impact` reports |
---
## 30-Second Quickstart / 30 秒零配置上手
No API keys, Docker containers, or third-party pip dependencies needed:
```bash
git clone https://github.com/nanyun818/codegraph-mcp-lite.git
cd codegraph-mcp-lite
pip install -e .
# 1. Run the built-in full-stack polyglot demo (Python FastAPI + Ledger + TypeScript UI + ADRs)
codegraph-mcp-lite demo
# 2. Run the token-efficiency & sub-5ms latency benchmark
codegraph-mcp-lite benchmark
# 3. Index and analyze any local repository (e.g. dogfooding on this repo itself!)
codegraph-mcp-lite index .
codegraph-mcp-lite hotspots --top 5 --root .
codegraph-mcp-lite impact "CodeGraphEngine.analyze_impact" --root .
codegraph-mcp-lite mermaid --root .
```
---
## Real Terminal Output / 真实终端运行实录
### 1. Interactive Polyglot Blast-Radius & Cross-Stack Call Trace (`codegraph-mcp-lite demo`)
Notice how modifying `LedgerStore.append_entry` in Python automatically traces upstream through `BillingOrchestrator` -> FastAPI `@app.post("/api/v1/checkout")` -> **TypeScript `CheckoutWidget.submitOrder`** in `1.32 ms`, while surfacing `ADR-001` and covering unit tests:
```text
$ codegraph-mcp-lite demo
=== codegraph-mcp-lite v0.1.0 Interactive Code Intelligence Demo ===
[1] Indexed Polyglot Workspace ({'python': 9, 'typescript': 1}): 10 files, 42 symbols, 49 typed edges in 20.03 ms
Incremental warm re-index: 10/10 SHA-256 cached, 0 reparsed in 1.84 ms
[2] Refactor Blast Radius for `LedgerStore.append_entry` (core/ledger.py:18) [1.32 ms]:
Risk Rating : CRITICAL (91/100)
- 2 direct + 5 transitive dependents across 5 file(s)
- Touches 2 public HTTP route(s): POST /api/v1/checkout, POST /api/v1/refund
- Cross-language blast radius detected (backend <-> frontend caller bridge)
- Governed by active ADR constraint(s): ADR-001
- Covered by 1 automated test symbol(s)
Direct & Transitive Dependents:
depth=1 [python] BillingOrchestrator.process_checkout (services/billing.py:26, via CALLS)
depth=1 [python] BillingOrchestrator.issue_refund (services/billing.py:33, via CALLS)
depth=2 [python] post_checkout_endpoint (api/routes.py:25, via CALLS) [Route: POST /api/v1/checkout]
depth=2 [python] post_refund_endpoint (api/routes.py:31, via CALLS) [Route: POST /api/v1/refund]
depth=3 [python] test_end_to_end_checkout_creates_ledger_entry (tests/test_checkout_flow.py:10, via CALLS)
depth=3 [typescript] CheckoutWidget.submitOrder (web/checkout_widget.ts:15, via CALLS_ROUTE)
depth=3 [typescript] CheckoutWidget.requestOrderRefund (web/checkout_widget.ts:24, via CALLS_ROUTE)
ADR Guardrail: [ADR-001] Double-Entry Idempotent Ledger Mutations -> All balance changes MUST pass an explicit idempotency_key to LedgerStore.append_entry; never mutate balances via raw SQL.
[3] Cross-Stack Shortest Call Path (`CheckoutWidget.submitOrder` [TS] -> `LedgerStore.append_entry` [Py]):
Step 0: CheckoutWidget.submitOrder [web/checkout_widget.ts:14]
Step 1: --(CALLS_ROUTE @ web/checkout_widget.ts:15)--> post_checkout_endpoint [api/routes.py:23]
Step 2: --(CALLS @ api/routes.py:25)--> BillingOrchestrator.process_checkout [services/billing.py:22]
Step 3: --(CALLS @ services/billing.py:26)--> LedgerStore.append_entry [core/ledger.py:18]
[4] Architectural Hygiene (Tarjan Cycle Detector + PageRank Hotspots):
! Circular Module Import: plugins/event_bus.py <-> plugins/audit_hook.py
* Hotspot: publish_domain_event (plugins/event_bus.py:6) | fan_in=3, fan_out=1, score=179.01
* Hotspot: record_compliance_trail (plugins/audit_hook.py:6) | fan_in=1, fan_out=1, score=161.95
* Hotspot: compute_digest (core/crypto.py:7) | fan_in=1, fan_out=0, score=56.03
* Hotspot: verify_hmac_signature (core/crypto.py:13) | fan_in=1, fan_out=1, score=48.52
```
### 2. Context Token Savings & Latency Benchmark (`codegraph-mcp-lite benchmark`)
Tested across a 42-file / 170-symbol multi-service workspace comparing naive iterative `grep` + file reads against structured graph queries:
```text
$ codegraph-mcp-lite benchmark
=== codegraph-mcp-lite Context Token & Latency Benchmark ===
Indexed Monorepo: 42 files | 170 symbols | 177 edges | Cold index: 49.1 ms
| Agent Engineering Query | Naive Tok | Graph Tok | Savings | Latency |
| ------------------------------------------------------ | --------: | --------: | ------: | ------: |
| Cross-stack blast radius (`LedgerStore.append_entry`) | 2,669 | 1,064 | -60.1% | 2.48ms |
| 6-hop trace (`submitOrder` -> `verify_hmac_signature`) | 2,420 | 568 | -76.5% | 2.72ms |
| Repo-wide circular import audit (42 files) | 6,121 | 50 | -99.2% | 2.11ms |
| Top-5 coupling hotspots (170 symbols) | 6,121 | 328 | -94.6% | 5.26ms |
| ------------------------------------------------------ | --------: | --------: | ------: | ------: |
| TOTAL / AVERAGE | 17,331 | 2,010 | -88.4% | 3.14ms |
Summary: Eliminated 15,321 exploration tokens (88.4% reduction) with 3.14 ms average query latency.
```
---
## MCP Server & Agent Skill Integration / MCP 与 Skill 接入指南
### 1. Connect via MCP (`stdio` JSON-RPC 2.0)
Add `codegraph-mcp-lite` to your Claude Code (`~/.claude.json`), Cursor (`.cursor/mcp.json`), Codex, or Zed configuration:
```json
{
"mcpServers": {
"codegraph-lite": {
"command": "codegraph-mcp-lite-server",
"args": ["--root", "."]
}
}
}
```
Or run directly without global installation using `PYTHONPATH`:
```json
{
"mcpServers": {
"codegraph-lite": {
"command": "python",
"args": ["-m", "codegraph_mcp_lite.mcp_server", "--root", "."],
"env": {
"PYTHONPATH": "/path/to/codegraph-mcp-lite/src"
}
}
}
}
```
#### Exposed MCP Tools (6 Tools)
| MCP Tool | Description / 功能说明 |
| :--- | :--- |
| `index_repository` | Incrementally index or force-refresh a workspace into `.codegraph/graph.sqlite3` |
| `search_symbols` | FTS5 BM25 + exact symbol & HTTP route lookup (`function`, `method`, `class`, `interface`) |
| `analyze_impact` | Reverse-BFS blast radius, risk score (`0-100`), exposed HTTP routes, covering tests & ADRs |
| `trace_call_path` | Upstream callers, downstream callees, or shortest execution path (`to_symbol`) |
| `get_architecture_overview` | Summary stats, PageRank coupling hotspots, Tarjan cycle audit & Mermaid diagram |
| `manage_adr` | Upsert or list persistent Architecture Decision Records bound to file/symbol globs |
### 2. Claude Code / Agent Skill (`SKILL.md`)
Copy [`SKILL.md`](./SKILL.md) into `.claude/skills/codegraph-mcp-lite/SKILL.md` so coding agents automatically run `codegraph-mcp-lite impact` before editing shared functions.
---
## CLI Reference / 命令行速查
```bash
codegraph-mcp-lite index [ROOT] [--force] [--json]
codegraph-mcp-lite search "<QUERY>" [--kind method|function|class] [--root .] [--json]
codegraph-mcp-lite impact "<SYMBOL>" [--depth 5] [--root .] [--json]
codegraph-mcp-lite trace "<SYMBOL>" [--to "<TARGET_SYMBOL>"] [--direction both|upstream|downstream] [--json]
codegraph-mcp-lite hotspots [--top 10] [--root .] [--json]
codegraph-mcp-lite cycles [--root .] [--json]
codegraph-mcp-lite mermaid [--focus "<SYMBOL>"] [--root .]
codegraph-mcp-lite adr add --id ADR-001 --title "..." --scope "core/*" --decision "..."
codegraph-mcp-lite adr list [--root .] [--json]
codegraph-mcp-lite mcp --root .
```
---
## Running Tests / 运行测试
```bash
python -m unittest discover -s tests -v
```
## License
Released under the [MIT License](./LICENSE). Copyright (c) 2026 `nanyun818`.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues