grafema-mcp
The Grafema MCP server turns your codebase into a queryable graph, enabling deep code analysis, navigation, and knowledge management.
Code Graph Analysis
Build and analyze the code graph (
analyze_project,get_analysis_status,get_stats,get_schema)Query using Datalog, Cypher, or GraphQL (
query_graph,query_graphql)Find nodes by type, name, or file (
find_nodes,get_node)Explore file/project structure (
read_project_structure,get_file_overview)
Code Navigation & Understanding
Find callers of functions (
find_calls), get full node context (get_context), neighbors (get_neighbors)Traverse the graph via BFS along specific edge types (
traverse_graph)Get function details, call graph, callers/callees (
get_function_details)Find conditional guards (
find_guards), describe nodes in DSL notation (describe), get class/interface shapes (get_shape)
Dataflow & Call Tracing
Trace data flow forward/backward (
trace_dataflow), call chains (trace_calls), alias chains (trace_alias), side effects (trace_effects)
Invariants & Guarantees
Create, list, check, and delete persistent architectural guarantees (
create_guarantee,list_guarantees,check_guarantees,delete_guarantee)Check one-off invariants without saving (
check_invariant)
Datalog Reasoning
Explain why a fact holds (
explain_fact) or doesn't (explain_gap)Simulate hypothetical changes without committing (
sim_datalog)
Knowledge Graph (Enox)
Store facts/observations (
remember,add_assertion), recall with natural language (recall), semantic search (semantic_search)Explore, traverse, and query the knowledge graph (
enox_explore,enox_traverse,enox_query)Manage assertions, save documents (ADRs, specs), crawl entities ontologically (
save_document,crawl_entity)Get stats and recent activity (
enox_stats,recent_activity)
Project & Configuration
Discover services (
discover_services), write config (write_config), check coverage (get_coverage)Query npm package registry (
query_registry), find shared behaviors across features (find_shared_behaviors)Get documentation (
get_documentation), report issues to GitHub (report_issue)
Grafema
Grafema turns your codebase, infrastructure, knowledge, and workflows around it — into one queryable graph. For humans and AI.
We treat code as text. But text is just a form.
What actually matters when you write code is the system you have in your head — its structure. Entities, invariants, limitations. Goals and purpose. And how all these things relate to each other.
Software is naturally an executable graph — and so is everything around it: your services, your decisions, your team's knowledge. Grafema uses compiler-grade AST parsers — containing years of community-shared knowledge for each language — to excavate the deepest possible model of your system, and turn it into a transparent, queryable, enrichable map that grounds your understanding of it.
We refuse to accept "that's impossible to analyze statically." You can read code and understand it — you have a mental model in your head. So it's a matter of good enough heuristics. Human brains are literally built on this.
It's not magic and won't cover 100% of your system on day one. There will be gaps and "Here be dragons" signs. You will slay these dragons one by one — extend analysis with your own rules, fill up the knowledge base. And if you contribute, you slay one for everyone.
Thinking in graphs is not easy. But once it clicks - you stop reading code and just navigate the system. And your AI minions too.
Welcome to the party!
Licensed under FSL-1.1-Apache-2.0 — free to use, source available, converts to Apache 2.0 after 2 years. Details
v0.4.1 — Early access. Changelog | Known limitations
Quick Start
npm install -g grafema
grafema analyze --quickstartThat's it. --quickstart auto-detects your project languages, generates config, and builds the graph in one command.
For more control, use the two-step flow: grafema init (review config) → grafema analyze.
Explore your code
# What does this file do? (compact DSL overview, 10-20x smaller than source)
grafema tldr src/server.ts
# Who calls this function?
grafema who handleRequest
# Where does this data come from? (backward dataflow trace)
grafema wtf req.user
# Why is it structured this way? (knowledge base decisions)
grafema why auth-middlewareUse with AI (MCP)
Add to .mcp.json in your project root:
{
"mcpServers": {
"grafema": {
"command": "npx",
"args": ["grafema-mcp", "--project", "."]
}
}
}There is also a Docker image for running the MCP server (stdio) in a container — see the root Dockerfile: docker run -i --rm -v "$PWD":/workspace grafema-mcp.
30+ MCP tools available: find_nodes, find_calls, trace_dataflow, get_file_overview, describe, query_graph, and more. The AI agent queries the graph instead of reading files — faster, cheaper, more complete.
find_nodes returns rich context in a single call: callers, members, parent, import/call counts. Fuzzy name matching via local embeddings means approximate queries like find_nodes(name="PtyHostHeartbeatService") find HeartbeatService even without exact match.
Related MCP server: Axon Pro
Capabilities
Analyze
✅ Call graph — who calls what, across all files
✅ Data flow — trace values source to sink, forward and backward
✅ Control flow — CFG, reachability, branching paths
✅ Data shapes — object structure through assignment chains
✅ Effect propagation — transitive side-effect analysis through call graph
✅ Symbolic execution
✅ Cross-language & inter-process — service boundaries, message passing, remote calls
⏳ Side effect chain analysis
⏳ Inter-service contracts — message queue schemas, API schemas (OpenAPI, JSON Schema, gRPC)
⏳ Infrastructure as Code — Terraform, Kubernetes, Docker
Query
✅ CLI:
tldr,who,wtf,why,check,overview✅ 40+ MCP tools for AI agents (graph queries, navigation, dataflow, knowledge, git history)
✅ Datalog for custom structural queries
✅ Cypher query language
✅ Programmatic API (
@grafema/util)✅ HexAtlas — visual code map (2D/3D)
✅ VS Code extension
Document
✅
grafema export --as docs-md— generate human-readable docs from the live graph✅
grafema export --as openapi-3.1— auto-generate OpenAPI for HTTP routes✅
grafema export --as mcp-schema— JSON-RPC tool registry, directly servable by any MCP runtime✅
grafema export --as json-schema— Draft 2020-12 schemas per FEATURE✅ Intent sidecars (
_ai/intents/...) — handwritten "when to use" + captured examples that augment autogen output✅
grafema features --duplicates— cross-modality dedup ("which CLI commands are wrappers around the same library function as which MCP tools")
Connect knowledge to code entities and flows
✅ Knowledge base — decisions, ADRs linked to code nodes
✅ Effects-DB & Registry — curated database of side effects and contract mappings for popular third-party packages across ecosystems (npm, PyPI, and more)
⏳ Git integration — blame, churn, authorship
Enforce your rules
✅ Architectural invariants as Datalog rules
✅
grafema check— CI gate⏳ Code Quality Metrics — complexity, coupling, hotspots
Enrich with your own meaning
✅ Custom node types and edges via plugins
✅ Library callback enricher — auto-detect MCP tools, CLI commands
✅ Manifest generation — API surface with effect annotations
Language Support
Language | Parser | Analyze | Resolve | Dataflow | Status |
JavaScript/TypeScript | full | full | full | Production | |
Rust | full | full | partial | Beta | |
Haskell | full | full | partial | Beta | |
Java | full | full | partial | Beta | |
Kotlin | kotlin-compiler-embeddable | full | full | partial | Beta |
Python | full | full | partial | Beta | |
Go | go/ast (stdlib) | full | full | partial | Beta |
C/C++ | tree-sitter-c | full | full | partial | Beta |
Swift | full | full | - | Alpha | |
Objective-C | libclang | full | full | - | Alpha |
Elixir/Erlang | native BEAM AST | full | full | - | Alpha |
JS/TS is the primary language with full dataflow support. Each language uses its community's canonical parser — not a generic tokenizer. grafema init includes all languages by default — analyzers for absent languages are simply skipped.
CLI Commands
Command | Question it answers | What it does |
| "What's in this file?" | Compact DSL overview (10-20x token savings) |
| "Where does this come from?" | Backward dataflow trace |
| "Who uses this?" | Find all callers/references |
| "Why is it this way?" | Knowledge base decisions |
| Initialize Grafema in a project | |
| Build/rebuild the code graph ( | |
| "Are my rules still satisfied?" | Run architectural guarantees, exit 1 on violations |
| Check system health | |
| Clean stale artifacts and upgrade binaries | |
| High-level project stats |
VS Code Extension
Interactive graph navigation directly in your editor. Install from the VS Code Marketplace or search "Grafema Explore" in Extensions.
Cmd+Shift+G — Find graph node at cursor
Value Trace — See where data comes from and flows to
Callers — All call sites for the function under cursor
Blast Radius — Impact analysis: what breaks if you change this?
Nodes in File — All graph nodes in current file with positions
Explorer — Navigate edges (incoming/outgoing) interactively
Benchmarks
Analysis Performance
Codebase | Files | Nodes | Edges | Time |
Grafema (self) | 509 | 203K | 385K | 25s |
BullMQ | 90 | 24K | 50K | 8s |
microsoft/vscode | ~5,600 | 3.56M | 7.55M | 14 min |
AI Agent Accuracy (Autoresearch)
Methodology: 30 questions sourced from real VS Code GitHub issues, scored by LLM judge. Questions span Sillito taxonomy levels L1 (finding focus) through L4 (full architecture understanding). Each question run as independent claude -p session with no prior context.
Condition | Accuracy | MCP Adoption | Tokens | Detail |
Baseline (grep + read only) | 20/30 (67%) | 0% | 88K | Agent uses Grep, Read, Glob |
Grafema (graph tools) | 23/30 (77%) | 96% | 139K | +10% accuracy, graph-guided navigation |
Grafema provides the biggest advantage on L4 architecture questions and debugging/tracing (up to +4 points per question) where structural graph queries outperform text search. On simple L1 lookups ("where is X?"), grep is often sufficient.
The evaluation harness captures full tool interaction traces including MCP tool results, reasoning chains, and fallback patterns. See autoresearch/ for methodology and raw data.
Architecture
Grafema uses a Rust orchestrator, Haskell per-language analyzers, and a custom columnar graph database (RFDB):
grafema analyze → Rust orchestrator → per-language analyzers → RFDB (graph DB)
│ ↓
│ batched ingestion (500 files) unix socket
│ streaming (ASTs freed after ingest) ↓
└──────── resolution plugins ←── query layer
↓
grafema tldr / MCP / CLI ← @grafema/utilRFDB — columnar graph database optimized for code analysis workloads. Deferred indexing, L1 compaction, edge-type and by-name indexes. Includes local embedding index for fuzzy name search — approximate queries find structurally similar names without exact match (e.g.,
PtyHostHeartbeatServicematchesHeartbeatService). Automatic segment GC after compaction.Orchestrator — Rust binary that coordinates discovery, parsing, RFDB ingestion, and resolution across languages. Streaming pipeline frees AST memory after ingestion.
Analyzers — per-language binaries (Haskell + native parsers where needed: libclang for ObjC, tree-sitter for C/C++, SwiftSyntax for Swift). Run as daemon pools with JSON-over-stdio protocol.
MCP Server — 30+ tools for AI agent integration (find_nodes, find_calls, trace_dataflow, describe, query_graph, etc.)
Environment Variables
Variable | Purpose |
| Path to orchestrator binary (auto-detected) |
| Path to RFDB server binary (auto-detected) |
Normally not needed — binaries are included in the npm package. Use these when developing Grafema or using custom builds.
Platform Support
Platform | Status |
macOS ARM (Apple Silicon) | Full support |
macOS Intel (x64) | Full support |
Linux x64 | Full support |
Linux ARM64 | Full support |
Windows | Not planned |
Packages
Package | Description |
Unified package (CLI + MCP + binaries) | |
Command-line interface | |
MCP server for AI assistants | |
Query layer, config, RFDB lifecycle | |
Type definitions | |
GraphQL API server |
Documentation
Requirements
Node.js >= 18
macOS (ARM or Intel) or Linux (x64 or ARM64)
License
FSL-1.1-Apache-2.0 — see LICENSING.md for details.
Author
Vadim Reshetnikov — Senior R&D Engineer with 6+ years working in massive legacy untyped codebases with high-load, high-performance backends. Building Grafema to fight the cognitive complexity of software development and maintenance.
Grafema was born from a real pain: spending 58% of engineering time on code comprehension (per research), with no tools that actually understand code structure at scale. Type systems help — but only for typed languages. Grafema fills the gap for everything else.
LinkedIn: linkedin.com/in/disentinel
Telegram: @vadresh — dev log, research notes, behind-the-scenes
Available Tools
52 toolsadd_assertionA
Create a precise edge between two nodes in the knowledge graph.
Use this when you need exact control over the graph structure:
Specific relation type between two entities
Confidence level on an assertion
Domain scoping
Both "from" and "to" become nodes if they don't exist yet.
Example: add_assertion(from="Grafema", relation="uses", to="RFDB", context="RFDB is the storage engine for code graphs", confidence=1.0)
Inputs: from (required), relation (required), to (required), context, +2 more.
analyze_projectA
Build the code graph by analyzing project source code.
REQUIRED before using query tools. Without analysis, the graph is empty.
Options:
service: Analyze only one service (faster for multi-service projects)
force: Re-analyze even if graph exists (use after code changes)
index_only: Fast mode — create MODULE nodes only, skip detailed analysis
Phases: Discovery → Indexing → Analysis → Enrichment → Validation Returns: Analysis summary with node/edge counts and timing.
Tip: Use get_stats after analysis to verify graph was built successfully.
Inputs: service, force, index_only.
check_guaranteesA
Validate code against defined guarantees and return violations.
Use this to:
Find violations: Run all rules, get list of breaking code
Verify specific rule: check_guarantees(names=["no-eval"]) — test one guarantee
Pre-commit validation: Catch issues before code review
After code changes: Verify you didn't break existing rules
Returns: Violations array with node IDs, file, line, rule name. Empty array = all guarantees pass.
Inputs: names.
check_invariantA
Check a one-off code invariant using a Datalog rule. Returns violations if broken.
Use this for ad-hoc checks without saving a permanent guarantee. For persistent rules, use create_guarantee + check_guarantees instead.
Use cases:
Quick check: "Are there any eval() calls?" — rule: violation(X) :- node(X, "CALL"), attr(X, "name", "eval").
Audit: "Functions over 100 lines?" — check for excessive complexity
Pre-commit: "Any new SQL injection risks?" — one-time check before pushing
Returns: List of nodes violating the rule, with file and line info.
Inputs: rule (required), description, limit, offset.
crawl_entityA
Run ontological crawl on a code entity — generate hypotheses and verify against code graph. Uses the Grafema code graph for verification. Records findings in knowledge database. Example: crawl_entity(entity="compactionEnricher", context="TypeScript enricher creating FEATURE nodes")
Inputs: entity (required), context, depth.
create_guaranteeB
Create a new code guarantee.
Two types supported:
Datalog-based: Uses rule field with Datalog query (violation/1)
Contract-based: Uses type + schema for JSON validation
Examples:
Datalog: name="no-eval" rule="violation(X) :- node(X, "CALL"), attr(X, "name", "eval")."
Contract: name="orders" type="guarantee:queue" priority="critical" schema={...}
Inputs: name (required), rule, severity, type, +7 more.
delete_assertionA
Remove an edge from the knowledge graph.
Use this when an assertion is wrong, outdated, or no longer relevant. Consider using update_assertion to lower confidence instead of deleting, or add_assertion with "supersedes" relation to record the replacement.
Example: delete_assertion(fact_id="edge-abc123")
Inputs: fact_id (required).
delete_guaranteeA
Delete a guarantee by name.
Use this when:
A guarantee is no longer relevant to the codebase
Replacing a guarantee with a new version (delete old, create new)
Cleaning up experimental guarantees after testing
This permanently removes the guarantee. Use list_guarantees first to verify the name.
Inputs: name (required).
describeA
Render a node's neighborhood as compact Grafema DSL notation.
Reduces verbose edge listings to archetype-grouped visual operators: o- dependency/import
outward flow (calls, delegates, passes) < inward flow (reads, extends, receives) => persistent write (db, file, redis) x exception (throws, rejects) ~>> event/message (emits, publishes) ?| conditional guard (if, case) |= governance (governs, monitors)
Containment edges ({ }) define nesting structure.
Example output: login { o- imports bcrypt > calls UserDB.findByEmail, createToken < reads config.auth => writes session >x throws AuthError ~>> emits 'auth:login' }
Use depth to control detail: 0 = names only (children listed, no edges) 1 = edges (default — shows all relationship lines) 2 = nested + folded (compressed view — repetitive siblings collapsed) 3 = nested (exact — every node expanded, no folding)
10-30 lines vs 500+ lines of raw edge data. Ideal for LLM context windows.
Inputs: target (required), depth, perspective.
discover_servicesA
Discover services in the project without running full analysis.
Use this during onboarding to understand project structure BEFORE running analyze_project.
Returns:
Service names and paths (e.g., "backend" at "apps/backend")
Entry points (e.g., "src/index.ts")
No graph data yet — this is fast discovery only
Workflow:
discover_services — see what's in the project
analyze_project — build graph for specific service or all
Query tools — explore the graph
Tip: If project has no .grafema/config.yaml, this scans for common patterns (package.json, index.ts, etc.). Use write_config to save the configuration.
Inputs: no named parameters.
enox_exploreA
Get all edges around an entity in the knowledge graph — see everything connected to it.
Use this to understand the full context of an entity: what it relates to, what depends on it, what contradicts it, etc.
Returns all incoming and outgoing edges with connected node summaries.
Example: explore(entity="RFDB V2 engine")
Inputs: entity (required).
enox_queryA
Filter nodes in the knowledge graph by type, domain, or name.
Use this for exact filtering when you know what you're looking for. Unlike semantic_search, this does exact/substring matching on fields.
Example: query_graph(type="decision", domain="engineering", limit=20)
Inputs: type, domain, name, limit.
enox_statsA
Get statistics about the Enox knowledge graph.
Use this to:
Check if the knowledge graph has content
See node and edge counts by type
Assess graph density and coverage
Returns: total nodes, total edges, counts by type, domain distribution.
Inputs: no named parameters.
enox_traverseA
Graph traversal from a knowledge entity following specific edge types and direction.
Use this for structured exploration:
"What does X depend on?" → traverse(start="X", direction="outgoing", edge_types=["depends_on"])
"What supersedes X?" → traverse(start="X", direction="incoming", edge_types=["supersedes"])
Full neighborhood: traverse(start="X", direction="both", max_depth=2)
Returns nodes with depth info (0 = start, 1 = direct, 2+ = transitive).
Example: traverse(start="RFDB", direction="outgoing", edge_types=["depends_on", "uses"], max_depth=3)
Inputs: start (required), direction, edge_types, max_depth.
explainA
Explain a code element using graph data — returns structured context + prompt for the LLM to summarize.
Unlike other tools that return raw data, this tool returns graph query results PLUS a natural-language prompt asking the calling LLM to explain the results to the user. The LLM uses its own reasoning to produce a human-readable summary.
No extra API calls needed — the calling model (Claude, GPT, etc.) does the summarization.
Use cases:
"Explain where this value comes from" → dataflow trace + summarization prompt
"What does this function do?" → structure + calls + prompt to describe
"How is this variable used?" → forward trace + prompt to explain usage patterns
The question parameter guides what graph data to fetch and how to frame the summary.
Inputs: target (required), file, question.
explain_factA
Explain WHY a derived (Datalog) fact holds — returns the rule that derived it plus the supporting body facts (why()/provenance).
This is the inverse of "what holds": instead of listing results, it justifies ONE result. Provenance is computed on demand against the current graph snapshot.
Default program is the bundled depends.dl, so the common use is explaining a MODULE→MODULE dependency edge:
"Why does module A depend on B?" → explain_fact(predicate="depends", key=["<A_id>", "<B_id>"])
For a custom rule, pass its source. key is the fact's ground tuple as wire-string
terms (node ids as their decimal id). A null/"no derivation" result means the fact
is not derivable by the program (it does not hold as a derived fact).
Inputs: predicate (required), key (required), source.
explain_gapA
Explain why a derived (Datalog) fact does NOT hold — the why-not dual of explain_fact.
Returns the rule whose gap it characterizes, the body premises that WERE satisfiable (with the head bound), and the first premise no binding satisfies:
a MISSING positive premise → the gap closes by ADDING such a fact (verify with sim_datalog)
a PRESENT negated premise → the gap closes by REMOVING the blocking fact
Default program is the bundled depends.dl, so the common use is explaining a missing MODULE→MODULE dependency:
"Why does module A NOT depend on B?" → explain_gap(predicate="depends", key=["<A_id>", "<B_id>"])
A "no gap" result means the fact actually IS derivable (use explain_fact), or no rule head matches the key.
Inputs: predicate (required), key (required), source.
find_callsA
Find every place in the codebase that calls a specific function or method.
Use this when you need to answer:
"Who calls getUserById?" → name="getUserById"
"Where is redis.get used?" → name="get", className="redis"
"Is this function dead code?" → if 0 calls found, likely unused
Returns file, line, and whether the call target is resolved (linked to its definition in the graph).
Inputs: name (required), className, limit, offset.
find_guardsA
Find conditional guards protecting a node.
Returns all SCOPE nodes that guard the given node, walking from inner to outer scope. Useful for answering "what conditions must be true for this code to execute?"
Each guard includes:
scopeId: The SCOPE node ID
scopeType: Type of conditional (if_statement, else_statement, etc.)
condition: Raw condition text (e.g., "user !== null")
constraints: Parsed constraints (if available)
file/line: Location in source
Example use cases:
"What conditions guard this API call?"
"Is this code protected by a null check?"
"What's the full guard chain for this function call?"
Inputs: nodeId (required).
find_nodesA
Find nodes in the graph by type, name, or file pattern.
Use this when you need to:
Find all functions in a specific file: type="FUNCTION", file="src/api.js"
Find a class by name: type="CLASS", name="UserService"
List all HTTP routes: type="http:route"
Get all modules in a directory: type="MODULE", file="services/"
Returns semantic IDs that you can pass to get_context, get_node, get_neighbors, or find_guards.
Supports partial matches on name and file. When a name filter returns no exact matches, automatically falls back to fuzzy name matching using token similarity (CamelCase/snake_case aware). Use limit/offset for pagination.
Inputs: type, name, file, limit, +1 more.
get_analysis_statusA
Get the current analysis status and progress.
Use this to:
Poll progress during long-running analysis (started by analyze_project)
Check if analysis is still running before making queries
See which phase is active (discovery, indexing, analysis, enrichment, validation)
Returns: { running: boolean, phase: string, progress: number, error: string | null }
Call this periodically after analyze_project to monitor progress.
Inputs: no named parameters.
get_contextA
Get deep context for a graph node: source code + full graph neighborhood.
Shows ALL incoming and outgoing edges grouped by type, with source code at each connected node's location. Works for ANY node type.
Use this after find_nodes or query_graph to deep-dive into a specific node.
Output includes:
Node info (type, name, semantic ID, location)
Source code at the node's location
All outgoing edges (what this node connects to)
All incoming edges (what connects to this node)
Code context at each connected node's location
Primary edges (CALLS, ASSIGNED_FROM, DEPENDS_ON, etc.) include code context. Structural edges (CONTAINS, HAS_SCOPE, etc.) are shown in compact form.
Inputs: semanticId (required), contextLines, edgeType.
get_coverageA
Check which files were analyzed and which were skipped.
Use this to:
Find gaps: "Why doesn't query find this file?" — check if it was analyzed
Verify include/exclude patterns work correctly
Debug empty query results: file not in graph → not analyzed
Identify unsupported file types or parse errors
Returns: analyzed/skipped file counts, coverage percentage, skip reasons.
Use AFTER analyze_project when queries return unexpected empty results.
Inputs: path, depth.
get_documentationA
Get documentation about Grafema usage and query syntax.
Topics available:
queries: Datalog query syntax, predicates (including numeric comparisons), and examples
types: Available node and edge types (including METRIC and ISSUE diagnostic nodes)
guarantees: How to create and manage code guarantees
notation: DSL notation reference (archetypes, operators, LOD, perspectives)
metrics: Performance metrics (METRIC nodes) and analysis issues (ISSUE nodes)
effects: Side-effect taxonomy and manifest system
onboarding: Step-by-step guide for new projects
overview: High-level Grafema architecture
Use this when you need to learn Datalog syntax, DSL notation, or understand available features.
Inputs: topic.
get_file_overviewA
Understand what a file does without reading it — shows structure and relationships from the graph.
USE THIS FIRST when you need to understand a file. It replaces reading the file with a structured summary: imports, exports, classes, functions, variables, and how they connect to the rest of the codebase.
Returns:
Imports: what modules are pulled in and which names
Exports: what the file exposes to others
Classes: with methods and their call targets
Functions: with what they call
Variables: with their assignment sources
After this, use get_context with specific node IDs to deep-dive into relationships.
Inputs: file (required), include_edges.
get_function_detailsA
Get comprehensive details about a function, including what it calls and who calls it.
Graph structure: FUNCTION -[HAS_SCOPE]-> SCOPE -[CONTAINS]-> CALL/METHOD_CALL CALL -[CALLS]-> FUNCTION (target)
Returns:
Function metadata (name, file, line, async)
calls: What functions/methods this function calls
calledBy: What functions call this one
For calls array:
resolved=true means target function was found
resolved=false means unknown target (external/dynamic)
type='CALL' for function calls like foo()
type='METHOD_CALL' for method calls like obj.method()
depth field shows transitive level (0=direct, 1+=indirect)
Use transitive=true to follow call chains (A calls B calls C). Max transitive depth is 5 to prevent explosion.
Inputs: name (required), file, transitive.
get_neighborsA
Get direct neighbors of a node — all incoming and/or outgoing edges.
Returns edges grouped by type with connected node summaries.
Use this when you need:
"What does this node connect to?" (outgoing)
"What connects to this node?" (incoming)
Simple graph exploration without Datalog
Direction options:
outgoing: Edges FROM this node (calls, contains, depends on)
incoming: Edges TO this node (callers, containers, dependents)
both: All edges (default)
Edge type filter: Pass edgeTypes to see only specific relationships. Omit to get all edge types.
Cheaper than get_context (no code snippets). Use when you only need the graph structure, not source code.
Inputs: semanticId (required), direction, edgeTypes.
get_nodeA
Get a single node by its semantic ID with full metadata.
Use this when you have a node ID from find_nodes, query_graph, or another tool and need the complete record.
Returns: All node properties (type, name, file, line, exported) plus type-specific metadata (async, params, className, etc.).
Use cases:
After find_nodes: get full details for a specific result
After query_graph: inspect a violation node
Quick lookup without full context (faster than get_context)
Tip: For relationships and code context, use get_context instead. For just the direct edges, use get_neighbors.
Inputs: semanticId (required).
get_schemaA
Get the graph schema: available node and edge types with counts.
Use this to:
Discover what types exist: "What node types does this graph have?"
Validate edge types before traverse_graph or get_neighbors
Understand graph structure before writing Datalog queries
Find correct type names (e.g., "http:route" not "HTTP_ROUTE")
Options:
type: "nodes" (node types only), "edges" (edge types only), "all" (default)
Tip: Run this first when exploring a new graph to learn the available vocabulary.
Inputs: type.
get_shapeA
Get the shape (methods + properties) of a CLASS, INTERFACE, or typed variable.
Shows all members including inherited ones via EXTENDS chain. For variables, follows INSTANCE_OF to find the type, then returns its shape.
Use this to understand:
"What methods does GraphBackend have?" → get_shape(target="GraphBackend")
"What can I call on this variable?" → get_shape(target="db", file="handlers.ts")
"What does this interface require?" → get_shape(target="NodeRecord")
Returns: members (methods + properties), extends chain, implements list.
Inputs: target (required), file.
get_statsA
Get graph statistics: node and edge counts by type.
Use this to:
Verify analysis completed: nodeCount > 0 means the graph is loaded
Understand graph size before running expensive queries
See what node/edge types exist in this particular codebase
Debug empty results: check if expected node types are present
Returns:
nodeCount, edgeCount: Total counts
nodesByType: {FUNCTION: 1234, CLASS: 56, ...}
edgesByType: {CALLS: 5678, CONTAINS: 3456, ...}
Use BEFORE querying an unfamiliar graph to understand what data is available.
Inputs: no named parameters.
list_guaranteesA
List all defined code guarantees (rules and contracts).
Use this to:
See existing invariants: "What rules does this codebase enforce?"
Understand code contracts before modifying code
Find Datalog-based rules (e.g., "no-eval", "no-sql-injection")
List contract-based guarantees (queue schemas, API contracts)
Returns for each guarantee: name, type, description, rule/schema, priority, status. Use BEFORE check_guarantees to see what will be validated.
Inputs: no named parameters.
query_graphA
Execute a Datalog or Cypher query on the code graph.
Set language to "cypher" for Cypher queries (e.g., MATCH (n:FUNCTION) RETURN n.name). Default is Datalog.
Available Datalog predicates:
type(Id, Type) / node(Id, Type) - match nodes by type
edge(Src, Dst, Type) - match edges
attr(Id, Name, Value) - match node attributes (name, file, line, etc.)
gt(Val, N), lt(Val, N), gte(Val, N), lte(Val, N) - numeric comparisons
+ - negation (not)
NODE TYPES:
MODULE, FUNCTION, METHOD, CLASS, VARIABLE, PARAMETER
CALL, PROPERTY_ACCESS, METHOD_CALL, CALL_SITE
METRIC (performance metrics: value/unit/source in metadata, OBSERVES → MODULE)
ISSUE (analysis problems: category/severity/message in metadata, CONTAINS ← MODULE)
http:route, http:request, db:query, socketio:emit, socketio:on
EDGE TYPES:
CONTAINS, CALLS, DEPENDS_ON, ASSIGNED_FROM, INSTANCE_OF, PASSES_ARGUMENT
OBSERVES (METRIC → MODULE, links performance metric to observed file)
EXAMPLES: violation(X) :- node(X, "MODULE"). violation(X) :- node(X, "FUNCTION"), attr(X, "file", "src/api.js"). violation(X) :- node(X, "CALL"), + edge(X, _, "CALLS"). violation(F, Ms) :- node(M, "METRIC"), attr(M, "name", "parse_ms"), attr(M, "value", Ms), gte(Ms, 500), edge(M, Mod, "OBSERVES"), attr(Mod, "file", F).
Inputs: query (required), language, limit, offset, +2 more.
query_graphqlA
Execute a GraphQL query on the code graph.
GraphQL provides typed, nested queries with pagination — complementary to Datalog. Use GraphQL when you need nested data in one query (node + edges + neighbors). Use Datalog (query_graph) for pattern matching and logical rules.
SCHEMA HIGHLIGHTS:
node(id: ID!): Node — get a single node
nodes(filter: {type, name, file, exported}, first, after): NodeConnection — paginated search
bfs/dfs(startIds, maxDepth, edgeTypes): [ID!]! — graph traversal
reachability(from, to, edgeTypes, maxDepth): Boolean — path existence
datalog(query, limit, offset): DatalogResult — Datalog passthrough
findCalls(target, className): [CallInfo!]! — call graph
traceDataFlow(source, file, direction, maxDepth): [[String!]!]! — data flow
stats: GraphStats — node/edge counts
Node fields: id, name, type, file, line, column, exported, metadata, outgoingEdges(types), incomingEdges(types), children, parent
EXAMPLE: query { nodes(filter: {type: "FUNCTION", file: "src/api"}, first: 5) { edges { node { name, file, line outgoingEdges(types: ["CALLS"]) { edges { node { dst { name, file } } } } } } totalCount } }
Use get_documentation(topic="graphql-schema") for the full schema.
Inputs: query (required), variables, operationName.
query_registryA
Query the local manifest registry for package export information and side effects.
The registry contains pre-analyzed manifests for npm dependencies. Each manifest describes a package's API surface: exported symbols, their kinds, and side effects.
Use this when you need to:
Know what a package exports: query_registry(package="graphql") → 216 exports
Check effects of a specific function: query_registry(package="yaml", symbol="parse") → PURE
Understand a dependency's API without reading its source code
Verify if a package is in the registry: query_registry(package="express") → not found
Returns: package metadata (purl, source_type, confidence), and either:
A specific export (when symbol is given)
All exports summary (when only package is given)
Full registry index (when neither is given)
source_type values:
"compiled_js" — standard npm package, fully analyzed
"source" — TypeScript source, fully analyzed
"minified" — bundled output (esbuild/webpack), exports not statically resolvable
"dts_only" — type declarations only, not in registry
Inputs: package, symbol.
read_project_structureA
Get the directory structure of the project. Returns a tree of files and directories, useful for understanding project layout during onboarding.
Excludes: node_modules, .git, dist, build, .grafema, coverage, .next, .nuxt
Use this tool when studying a new project to identify services, packages, and entry points.
Inputs: path, depth, include_files.
recallA
Broad "what do we know about X" — combines embedding search with graph traversal.
Use this at session start or before making decisions to check for prior art, known failures, and existing context.
Depth controls how far to traverse from matched nodes:
1: direct matches only (fast)
2: matches + their neighbors (default, good balance)
3: two hops out (broader context, slower)
Example: recall(query="federation architecture", depth=2)
Inputs: query (required), depth.
recent_activityA
Get recently created or updated nodes and edges.
Use this at session start to see what other sessions have recorded recently. Helps avoid duplicating work and provides continuity across sessions.
Example: recent_activity(since="2026-05-20T00:00:00Z", limit=10)
Inputs: since, limit.
rememberA
Quick knowledge write — store a fact about a subject.
Use this when you:
Discover something worth remembering across sessions
Want to record an experiment result, decision, or observation
Need a quick "jot it down" without specifying exact graph structure
The subject becomes a node (or reuses an existing one), and the fact is stored as an assertion from that node.
Example: remember(subject="RFDB compaction", fact="flush_data_only was a no-op in V2 engine", domain="engineering")
Inputs: subject (required), fact (required), domain, confidence, +1 more.
report_issueA
Report a bug or issue with Grafema to GitHub.
Use this tool when you encounter:
Unexpected errors or crashes
Incorrect analysis results
Missing features that should exist
Documentation issues
The tool will create a GitHub issue automatically if GITHUB_TOKEN is configured. If not configured, it will return a pre-formatted issue template that the user can manually submit at https://github.com/Disentinel/grafema/issues/new
IMPORTANT: Always ask the user for permission before reporting an issue. Include relevant context: error messages, file paths, query used, etc.
Inputs: title (required), description (required), context, labels.
save_documentA
Store a document or artifact as a node in the knowledge graph.
Use this for longer-form content that should be persisted:
ADRs (Architecture Decision Records)
Postmortems and incident reports
Specifications and design documents
Session notes and artifacts
The document becomes a node with its content stored. Use relates_to to link it to relevant entities in the graph.
Example: save_document(title="ADR: Federation via thick client", content="## Context\n...", doc_type="adr", relates_to=["Grafema", "RFDB"])
Inputs: title (required), content (required), doc_type, relates_to.
semantic_searchA
Substring search across knowledge-graph node names (case-insensitive).
NOTE: despite the name, embedding-based semantic ranking is not wired yet (RFD-63). This currently matches substrings of node names — results are plain matches, not similarity-ranked. Use recall for broader retrieval.
Example: semantic_search(query="auth token", top_k=5, domain="devops")
Inputs: query (required), top_k, domain.
sim_datalogA
Predict which NEW derived facts a hypothetical change would create — WITHOUT committing anything (what-if simulation).
Give it hypothetical nodes and/or edges; it evaluates the program over base ∪ overlay and returns only the facts that are NEW vs the current graph (sim ∖ base).
Default program is the bundled depends.dl, so the common use is previewing module dependencies:
"If module A imported B, which NEW dependencies appear?" → sim_datalog(predicate="depends", edges=[{src:"<A_id>", dst:"<B_id>", edgeType:"IMPORTS_FROM"}])
Hypothetical node ids may be NEW (invent a decimal id) — an edge may reference them, so you can simulate a wholly new module/import, not only bridge existing nodes. The committed graph is never touched. Companion to explain_gap: gap names the missing premise, sim verifies that adding it produces the fact.
Inputs: predicate (required), nodes, edges, source.
trace_aliasA
Trace an alias chain to find the original source. For code like: const alias = obj.method; alias(); This traces "alias" back to "obj.method".
Inputs: variableName (required), file (required).
trace_callsA
Trace call chains from or to a function/method, following CALLS and CALLS_REMOTE edges transitively.
Use this when you need to:
"What does this function eventually call?" (forward) — full call tree including cross-language hops
"Who calls this function?" (backward) — all callers up the stack
"Show the full call chain from handler to database" (forward with depth)
Unlike trace_dataflow (which follows data assignments), this follows function CALLS edges:
CALLS: same-language function/method invocation
CALLS_REMOTE: cross-process/language boundary (IPC, HTTP, socket)
Returns: Indented call tree showing each hop with file:line location.
Inputs: source (required), file, direction, max_depth.
trace_dataflowA
Trace data flow paths from or to a variable/expression.
Use this when you need to:
Forward trace: "Where does this value flow to?" (assignments, function calls, returns)
Backward trace: "Where does this value come from?" (sources, assignments)
Both: Full data lineage from sources to sinks
Direction options:
forward: Follow ASSIGNED_FROM, PASSES_ARGUMENT, FLOWS_INTO edges downstream
backward: Follow edges upstream to find data sources
both: Trace in both directions for complete context
Use cases:
Track tainted data: "Does user input reach database query?" (forward from input)
Find data sources: "What feeds this API response?" (backward from response)
Impact analysis: "If I change this variable, what breaks?" (forward trace)
Returns: List of nodes in the data flow chain with edge types and depth. Tip: Start with max_depth=5, increase if needed.
Inputs: source (required), file, direction, max_depth, +2 more.
trace_effectsA
Trace transitive side effects of a function through its call graph.
For any function, traverses CALLS edges (DFS) and collects effects from leaf nodes using the effects-db (Node.js builtins, npm packages).
Use this when you need to:
"What side effects does this function have?" → direct + transitive effects
"Does this handler do IO?" → trace shows IO:FILE:READ from fs.readFileSync at depth 3
"Where does the fetch() call come from?" → leaf_sources shows the origin at depth N
"What crosses module boundaries?" → boundary_crossings shows file-to-file effect flow
Effect types: PURE, MUTATION, IO (with subtypes like IO:FILE:READ, IO:HTTP:REQUEST), THROW, ASYNC, NONDETERMINISTIC, UNKNOWN.
UNKNOWN means: unresolved call, external package not in effects-db, or depth limit reached.
Returns: direct effects, transitive effects, boundary crossings, leaf sources.
Inputs: node (required), file, max_depth.
traverse_graphA
Traverse the graph using BFS from start nodes, following specific edge types.
Use this for:
Impact analysis: "What's affected if I change this?" (outgoing CALLS, DEPENDS_ON)
Dependency trees: "What does this module import?" (outgoing IMPORTS_FROM)
Reverse dependencies: "Who depends on this?" (incoming DEPENDS_ON)
Reachability: "Can data flow from X to Y?" (outgoing FLOWS_INTO, ASSIGNED_FROM)
Returns nodes with depth info (0 = start, 1 = direct neighbor, 2+ = transitive).
Direction:
outgoing: Follow edges FROM start nodes (default)
incoming: Follow edges TO start nodes
Examples:
All transitive callers: traverse_graph(startNodeIds=[fnId], edgeTypes=["CALLS"], direction="incoming")
Module dependency tree: traverse_graph(startNodeIds=[modId], edgeTypes=["IMPORTS_FROM"], maxDepth=10)
Tip: Start with maxDepth=5. Use get_schema(type="edges") to find valid edge type names.
Inputs: startNodeIds (required), edgeTypes (required), maxDepth, direction.
update_assertionA
Update an existing edge in the knowledge graph.
Use this to change the context or confidence of a previously recorded assertion without deleting and re-creating it.
Example: update_assertion(fact_id="edge-abc123", confidence=0.5, context="Partially confirmed after testing")
Inputs: fact_id (required), context, confidence.
update_nodeA
Update metadata on an existing node in the knowledge graph.
Use this to rename, re-domain, or add descriptions to existing nodes without affecting their edges.
Example: update_node(node_id="node-abc123", description="V2 storage engine with segment-based persistence")
Inputs: node_id (required), name, domain, description.
write_configA
Write or update the Grafema configuration file (.grafema/config.yaml). Validates all inputs before writing. Creates .grafema/ directory if needed.
Use this tool after studying the project to save the discovered configuration. Only include fields you want to override — defaults are used for omitted fields.
Inputs: services, plugins, include, exclude, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 52 tools
Many tools have overlapping purposes, such as multiple query/trace/explore tools (query_graph, query_graphql, trace_calls, trace_dataflow, get_neighbors, enox_explore, etc.). The descriptions try to differentiate, but the sheer number and functional overlap will confuse an agent about which tool to use.
Naming conventions are mixed: some tools use verb_noun (add_assertion, create_guarantee), some use noun-like prefixes (enox_query, enox_stats), and others are compound phrases (find_shared_behaviors, trace_dataflow). No consistent pattern, making it hard for an agent to predict tool names.
At 52 tools, the set is excessively large for a single server. Many tools could be merged (e.g., trace_* tools, find_* tools). This over-fragmentation increases cognitive load and reduces coherence.
The tool surface covers a broad domain (project analysis, code query, knowledge graph, guarantees), but there are gaps: no tools for updating the code graph (only knowledge graph), and the 'enox' knowledge graph integration feels separate. Some common operations like 'delete' are missing for code graph nodes.
Maintenance
Related MCP Connectors
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
Deterministic context layer for your codebase: change impact, blast radius, answers with receipts.
AI Agent with Architectural Memory. Impact analysis (free), tests and code from the graph (pro).
A private graph database you query in plain English or Cypher. Hosted, nothing to install.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceGenerates and queries a graph representation of a codebase to identify entities and their relationships, such as function calls and inheritance. It supports multiple languages including Python, JavaScript, and Rust to help users navigate and understand complex code structures.24 npm22MIT
- AlicenseBqualityDmaintenanceTransforms codebases into structural knowledge graphs for AI agents and developers, providing precise architectural awareness and dependency mapping.1530MIT
- AlicenseNot gradedqualityDmaintenanceA high-performance, polyglot code-analysis graph for coding agents that enables cross-language and cross-process code relationship queries in sub-millisecond time.MIT
- AlicenseAqualityDmaintenanceEnables creating and querying semantic knowledge graphs to model business logic, code relationships, and project structure across multiple projects.111MIT