MCP Context Graph
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MCP Context Graph find who calls the function 'calculate_tax'"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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.
uvx mcp-context-graph /path/to/your/projectThat'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.
Related MCP server: kg-memory-mcp
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-readableHonest 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 │ └──────────┘
└──────────────────────────────────────────────┘Parse — tree-sitter grammars for Python, TypeScript, and JavaScript extract definitions, call expressions, and import statements.
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.Link — a two-pass resolver turns call sites and imports into
CALLSandIMPORTSedges across files, so "who calls this?" is a graph lookup, not a text search.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. |
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/projectOr install it:
uv pip install mcp-context-graph # or: pip install mcp-context-graphRequires Python 3.12+.
Connecting an MCP Client
Claude Code
claude mcp add context-graph -- uvx mcp-context-graph /absolute/path/to/projectClaude 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 |
| "(Re)build the graph" — returns stats and the context-footprint reduction | one-off |
| "Where is | ~100 tokens |
| "Who calls | ~100–500 tokens |
| "What surrounds | ~200–1,000 tokens |
| "Show me the full implementation" — source-map-accurate original code | proportional to the body |
| "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 bodyFour 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 bodyexpand_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 |
| functions, classes, methods, calls, imports (incl. relative) |
TypeScript |
| functions, arrow/function expressions, classes, methods, interfaces, type aliases, calls, imports |
JavaScript |
| 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 --versionDevelopment
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 + blackProject 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-workArchitecture 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 aMultiDiGraph).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_LEVELcontrols 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.
Available Tools
6 toolsdebug_dump_graphA
DEBUG: Dump the entire graph structure for visualization. Returns the graph in Mermaid diagram, JSON, or Graphviz DOT format. Useful for debugging and understanding the graph structure.
Inputs: format, show_edges, limit_nodes.
expand_sourceA
Expand a symbol's compact signature to its full original source code using token-level source maps. Use this when the signature is not enough and you need the implementation.
Inputs: name, symbol_id, end_offset, start_offset.
find_callersA
Find all functions/methods that call a given function, resolved through the call graph (not text search). Useful for impact analysis before changing a function.
Inputs: name (required).
find_symbolA
Find function, class, or method definitions by name. Returns all matching definitions with their locations and compact signatures - far cheaper than reading files. Optionally filter by language or include call sites.
Inputs: name (required), language, include_calls.
get_contextA
Get the contextual neighborhood around a symbol: the symbol plus connected nodes (callers, callees, imports, containers) within a given depth, and the relationships between them. The compact alternative to reading whole files for context.
Inputs: name, depth, format, symbol_id.
index_projectA
(Re)index the project to build the code graph. Scans Python, TypeScript, and JavaScript files, extracts definitions, and resolves call/import relationships. Indexing also happens automatically on the first query; use this tool with force=true for a full rebuild, or to see indexing stats and the context-footprint reduction.
Inputs: path, force.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
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.
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.
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.
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
Related MCP Connectors
Persistent memory, knowledge graph, task management and more for AI agents via MCP.
Persistent, inspectable memory for AI agents with lineage, correction, and a hosted MCP endpoint.
Persistent, portable memory for AI assistants — your private memory graph, from any MCP client.
Persistent knowledge graph for AI agents. Remember, recall, and forget facts.
Related MCP Servers
- AlicenseAqualityCmaintenanceA local knowledge graph MCP server that provides AI agents with permanent, structured memory about codebases, enabling semantic search, blast radius analysis, and convention enforcement.83MIT
- FlicenseNot gradedqualityDmaintenanceAn in-memory knowledge graph MCP server that gives coding agents structural and semantic recall over codebases by indexing Python source, ADR documents, and project configuration, exposing 7 tools for search, traversal, context retrieval, and natural-language Q&A.-
- AlicenseNot gradedqualityDmaintenanceA local-first compiled knowledge graph MCP server that provides structured memory for AI agents with full-text search, vector embeddings, and timeline tracking.215 npm8MIT
- AlicenseNot gradedqualityBmaintenanceProvides local-first persistent memory with a typed knowledge graph and bounded multi-hop retrieval via MCP, letting coding agents and local LLM systems store, search, and recall facts across sessions without hosted services or model dependencies.MIT