MCP Context Graph
Click on "Install 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 Graphfind 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: MemoryGraph
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.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/padobrik/mcp-context-graph'
If you have feedback or need assistance with the MCP directory API, please join our Discord server