Skip to main content
Glama
padobrik

MCP Context Graph

by padobrik
README.md
# MCP Context Graph

**A lightweight, in-memory code graph for AI agents — no Neo4j, no vector database, no infrastructure.**

MCP Context Graph is a minimal, self-contained alternative to heavyweight code-graph stacks. Where larger open-source solutions bring a graph database, an embedding pipeline, and a fleet of services, this project brings three things: tree-sitter parsing, a NetworkX graph, and token-level source maps — all in a single Python process that starts in under a second and speaks the [Model Context Protocol](https://modelcontextprotocol.io).

```bash
uvx mcp-context-graph /path/to/your/project
```

That's the entire deployment.

## The Problem

AI coding agents burn most of their context window on *finding* code, not *reasoning* about it. The standard failure modes:

- **Read whole files** — expensive, and most of each file is irrelevant to the question
- **Grep for text** — finds strings, not semantics; every match means reading another file
- **Lose the call graph** — "who calls this?" degenerates into reading the entire repository

MCP Context Graph parses your codebase once, builds a semantic graph (definitions, calls, imports, containment), and lets the agent query it through six MCP tools. The agent gets compact signatures and relationships by default, and can expand any symbol to its exact original source when it actually needs the implementation.

## Proof of Work: Measured Token Reduction

This is not a hand-wavy claim — the repository ships a reproducible, offline benchmark (`mcp-context-graph benchmark <path>`) that replays three real agent workflows against any codebase and counts tokens with `tiktoken` (o200k_base). No API keys required.

Results of the benchmark run against **this repository itself** (50 files → 963 nodes, 2,138 edges, indexed in ~200 ms):

| Agent workflow | Reading files | Using the graph | Reduction |
|---|---|---|---|
| **repo_map** — build a mental map of the repo | 85,129 tok | 22,496 tok | **3.8x** (73.6%) |
| **find_callers** — "who calls X?" (top-5 hottest symbols) | 174,685 tok | 26,253 tok | **6.7x** (85.0%) |
| **understand** — "show me X and its context" | 155,720 tok | 27,525 tok | **5.7x** (82.3%) |

Baselines are what a file-mediated agent actually does: `repo_map` reads every source file; `find_callers` greps for the name and reads every matching file; `understand` reads the symbol's file plus the files of its direct callers/callees. The graph side is the literal JSON tool responses — overhead included.

Estimated input-token cost per 1,000 agent queries on this repo (prices per 1M input tokens, adjust to current provider pricing):

| Model | Reading files | Using graph | Savings |
|---|---|---|---|
| claude-sonnet-4.5 | $99.12 | $16.13 | **$82.99** |
| gpt-5.2 | $82.60 | $13.44 | **$69.16** |
| gpt-4o-mini | $4.96 | $0.81 | **$4.15** |
| gemini-2.5-pro | $115.64 | $18.82 | **$96.82** |

Query latency is effectively free: `find_definition` ~0.4 µs, `find_callers` ~28 µs, `get_context(depth=2)` ~360 µs.

Run it on your own project:

```bash
uvx mcp-context-graph benchmark /path/to/project            # human-readable
uvx mcp-context-graph benchmark /path/to/project --markdown # README-ready
uvx mcp-context-graph benchmark /path/to/project --json     # machine-readable
```

**Honest caveat:** savings scale with repository size. On a two-file toy project the JSON envelope of a tool response can cost more than just reading both files. The graph pays off from roughly "a few dozen files" upward — exactly where agents start struggling.

## How It Works

```
                ┌──────────────────────────────────────────────┐
                │              mcp-context-graph               │
   your repo    │                                              │     AI agent
  ┌─────────┐   │  tree-sitter ──► normalizer ──► minifier     │   ┌──────────┐
  │ *.py    │──►│   (parse)       (defs/calls/    (signatures  │◄──│ find_    │
  │ *.ts    │   │                  imports)        + source    │──►│ callers  │
  │ *.js    │   │                                  maps)       │   │ get_     │
  └─────────┘   │                      │                       │◄──│ context  │
                │                      ▼                       │──►│ expand_  │
                │            NetworkX MultiDiGraph             │   │ source   │
                │     CONTAINS / CALLS / IMPORTS edges         │   └──────────┘
                └──────────────────────────────────────────────┘
```

1. **Parse** — tree-sitter grammars for Python, TypeScript, and JavaScript extract definitions, call expressions, and import statements.
2. **Minify** — each definition is reduced to its signature (`def calculate_tax(amount: float) -> float: ...`) with a character-accurate **source map** back to the original file.
3. **Link** — a two-pass resolver turns call sites and imports into `CALLS` and `IMPORTS` edges across files, so "who calls this?" is a graph lookup, not a text search.
4. **Serve** — six MCP tools over stdio. The graph auto-indexes on the first query and transparently re-ingests modified, deleted, and newly created files before every query (check-on-read; no file watcher, no daemon).

### Design Constraints (Why It Stays Small)

| Constraint | Consequence |
|---|---|
| In-memory only | No database to install, corrupt, or migrate. Restart = reindex (~200 ms for 50 files). |
| Name-based call resolution | No full type inference. Same-file definitions win ties; ambiguities resolve deterministically. |
| Signatures by default, source on demand | The context window holds structure, not bodies. `expand_source` recovers exact bodies via source maps. |
| stdio transport, one project per server | No ports, no auth, no multi-tenancy complexity. |

## Installation

No installation needed with [uv](https://github.com/astral-sh/uv):

```bash
uvx mcp-context-graph /path/to/project
```

Or install it:

```bash
uv pip install mcp-context-graph   # or: pip install mcp-context-graph
```

Requires Python 3.12+.

## Connecting an MCP Client

### Claude Code

```bash
claude mcp add context-graph -- uvx mcp-context-graph /absolute/path/to/project
```

### Claude Desktop (`claude_desktop_config.json`)

```json
{
  "mcpServers": {
    "context-graph": {
      "command": "uvx",
      "args": ["mcp-context-graph", "/absolute/path/to/your/project"]
    }
  }
}
```

> Claude Desktop requires an absolute path; relative paths like `.` resolve against the desktop app's working directory, not your project.

### Cline / Cursor / other MCP clients

```json
{
  "mcpServers": {
    "context-graph": {
      "command": "uvx",
      "args": ["mcp-context-graph", "."]
    }
  }
}
```

Clients that launch servers from the workspace directory (like Cline) can use `.`.

Set `MCP_CONTEXT_GRAPH_LOG_LEVEL=DEBUG` in the server environment for verbose stderr logging.

## MCP Tools

| Tool | Question it answers | Typical cost |
|---|---|---|
| `index_project` | "(Re)build the graph" — returns stats and the context-footprint reduction | one-off |
| `find_symbol` | "Where is `calculate_tax` defined?" | ~100 tokens |
| `find_callers` | "Who calls `calculate_tax`?" — resolved through the call graph | ~100–500 tokens |
| `get_context` | "What surrounds `calculate_tax`?" — center signature + neighbor references + relationships | ~200–1,000 tokens |
| `expand_source` | "Show me the full implementation" — source-map-accurate original code | proportional to the body |
| `debug_dump_graph` | "Visualize the graph" — Mermaid / JSON / DOT | debug only |

Indexing is automatic: the first query triggers a full ingest, and every subsequent query performs a fast staleness check (modified/deleted/new files are re-ingested and re-linked). `index_project` is only needed for a forced rebuild (`force: true`) or to inspect stats.

### A Typical Agent Session

```text
agent> find_symbol {"name": "calculate_tax"}
       → 1 definition: billing/tax.py:12, "def calculate_tax(amount: float, rate: float) -> float: ..."

agent> find_callers {"name": "calculate_tax"}
       → 3 callers: checkout.process_order, invoices.finalize, tests.test_tax_rounding

agent> get_context {"name": "calculate_tax", "depth": 1}
       → center signature + 5 connected symbols + relationships
         ("process_order --calls--> calculate_tax", ...)

agent> expand_source {"name": "calculate_tax"}
       → exact original source of the function body
```

Four queries, a few hundred tokens — instead of reading three files.

## Token-Level Source Maps

Most code indexers store either full source (expensive) or bare symbol names (lossy). This project stores **minified signatures plus character-accurate source maps**:

```python
# Original file (billing/tax.py)
def calculate_tax(amount: float, rate: float) -> float:
    """Calculate tax for the given amount."""
    return amount * rate

# Stored in the graph (what queries return)
def calculate_tax(amount: float, rate: float) -> float: ...

# Source map (per definition)
Segment(minified=[0,56)  → original=[0,56))    # signature, preserved exactly
Segment(minified=[57,60) → original=[57,131))  # "..." ↔ the real body
```

`expand_source` walks the map back to the original file and returns the exact bytes of the implementation — the graph never becomes a stale copy of your code.

## Supported Languages

| Language | Extensions | Extraction |
|---|---|---|
| Python | `.py`, `.pyw` | functions, classes, methods, calls, imports (incl. relative) |
| TypeScript | `.ts`, `.tsx` | functions, arrow/function expressions, classes, methods, interfaces, type aliases, calls, imports |
| JavaScript | `.js`, `.jsx`, `.mjs`, `.cjs` | functions, generators, arrow/function expressions, classes, methods, calls, imports |

Each language is a self-contained config (grammar + `.scm` query files); adding a language means adding one config class and three query files.

`.gitignore` is respected, and `node_modules`, `.venv`, `__pycache__`, build artifacts, and friends are always excluded.

## CLI Reference

```bash
mcp-context-graph [PATH]                 # serve MCP over stdio (default)
mcp-context-graph serve [PATH]           # same, explicit
mcp-context-graph index PATH             # one-shot index, print stats JSON
mcp-context-graph benchmark PATH         # token-reduction report
mcp-context-graph benchmark PATH --json --top 10
mcp-context-graph --version
```

## Development

```bash
git clone https://github.com/padobrik/mcp-context-graph.git
cd mcp-context-graph
uv sync --dev

make check        # lint (ruff) + typecheck (mypy --strict) + tests (pytest)
make test         # 265 tests: unit, property-based (hypothesis), integration
make format       # ruff --fix + black
```

### Project Structure

```
src/mcp_context_graph/
  core/           # Graph data structures (GraphNode, GraphEdge, ContextGraph)
  ingest/         # Pipeline: tree-sitter parser → normalizer → minifier → ingestor
  languages/      # Per-language grammar configs and .scm query files
  provenance/     # Source maps: segments + O(log n) bidirectional offset lookup
  mcp/            # MCP server (stdio) and tool implementations
  benchmark.py    # Token-reduction proof-of-work
```

### Architecture Notes

- **Two-pass reference resolution.** Files are parsed independently; call sites and imports queue as pending references, then resolve against the complete graph. Cross-file edges work regardless of file order, and incremental refreshes re-resolve idempotently (edges are keyed by `(source, target, type)` in a `MultiDiGraph`).
- **Check-on-read freshness.** Every tool call compares mtimes for tracked files and rescans for new files. No watcher process, no events to miss.
- **Protocol hygiene.** stdout is reserved for JSON-RPC; all logging goes to stderr (`MCP_CONTEXT_GRAPH_LOG_LEVEL` controls verbosity).
- **Graceful degradation.** If tree-sitter fails on a file, a regex fallback still extracts top-level definitions rather than dropping the file.

## License

MIT License. See [LICENSE](LICENSE) for details.

TDQS

A4.2/5.0

Scored across 6 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: indexing, symbol lookup, caller analysis, context retrieval, source expansion, and graph dumping. There is no overlap that would cause an agent to select the wrong tool.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern in lowercase snake_case (e.g., find_symbol, get_context). The verbs are descriptive and uniform, making the toolset predictable.

Tool Count5/5

Six tools is a well-scoped size for a code graph server, covering core operations without excessive fragmentation or missing essential functionality. Each tool earns its place.

Completeness5/5

The toolset covers the full workflow: indexing, symbol discovery, relationship analysis, source retrieval, and graph visualization. There are no significant gaps for the stated purpose of providing code context.

Maintenance

ActivityStale
ResponsivenessNo issues