Command Palette

Search for a command to run...

UnylyUnyly
Весь каталог

Context Graph

БесплатноНе проверен

A self-contained, in-memory graph database for AI Agents. Provides semantic code understanding through the Model Context Protocol (MCP).

GitHubEmbed

Описание

A self-contained, in-memory graph database for AI Agents. Provides semantic code understanding through the Model Context Protocol (MCP).

README

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.

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:

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:

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

Or install it:

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

Requires Python 3.12+.

Connecting an MCP Client

Claude Code

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

Claude Desktop (claude_desktop_config.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

{
  "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

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:

# 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

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

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 for details.

from github.com/padobrik/mcp-context-graph

Установка Context Graph

У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.

▸ github.com/padobrik/mcp-context-graph

FAQ

Context Graph MCP бесплатный?

Да, Context Graph MCP бесплатный — установка в пару кликов через Unyly без оплаты.

Нужен ли API-ключ для Context Graph?

Нет, Context Graph работает без API-ключей и переменных окружения.

Context Graph — hosted или self-hosted?

Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.

Как установить Context Graph в Claude Desktop, Claude Code или Cursor?

Открой Context Graph на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.

Похожие MCP

Compare Context Graph with

Не уверен что выбрать?

Найди свой стек за 60 секунд

Автор?

Embed-бейдж для README

Похожее

Все в категории data