🚨 Latest Research:Tanstack npm Packages Compromised in Ongoing Mini Shai-Hulud Supply-Chain Attack.Learn More β†’
Socket
Book a DemoSign in
Socket

@sdsrs/code-graph

Package Overview
Dependencies
Maintainers
1
Versions
141
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sdsrs/code-graph

MCP server that indexes codebases into an AST knowledge graph with semantic search, call graph traversal, and HTTP route tracing

latest
Source
npmnpm
Version
0.27.0
Version published
Weekly downloads
3.3K
160.56%
Maintainers
1
Weekly downloads
Β 
Created
Source

code-graph-mcp

A high-performance code knowledge graph server implementing the Model Context Protocol (MCP). Indexes codebases into a structured AST knowledge graph with semantic search, call graph traversal, and HTTP route tracing β€” designed to give AI coding assistants deep, structured understanding of your code.

Features

  • Multi-language parsing β€” Tree-sitter AST extraction across tiers of depth:
    • Full (calls + imports + inheritance + HTTP routes + test markers): TypeScript/TSX, JavaScript, Go, Python, Rust, Java
    • Smoke-tested (calls + imports + inheritance): C#, Kotlin, Ruby, PHP, Swift, Dart
    • Limited (functions + calls + #include imports + gtest test markers; Class::method scope qualification deferred): C, C++
    • Scripting: Bash (functions + commands + source/. imports), Markdown (headings)
    • File-FTS only (no AST symbol extraction): HTML, CSS, JSON
  • Semantic code search β€” Hybrid BM25 full-text + vector semantic search with Reciprocal Rank Fusion (RRF), powered by sqlite-vec
  • Call graph traversal β€” Recursive CTE queries to trace callers/callees with cycle detection
  • HTTP route tracing β€” Map route paths to backend handler functions (Express, Flask/FastAPI, Go net/http)
  • Dead code detection β€” Find unreferenced symbols with smart Orphan/Exported-Unused classification
  • Impact analysis β€” Determine the blast radius of code changes by tracing all dependents
  • Incremental indexing β€” Merkle tree change detection with file system watcher for real-time updates. Smart event filtering skips metadata-only changes (chmod, xattr)
  • Context compression β€” Token-aware snippet extraction for LLM context windows (L0β†’full code, L1β†’summaries, L2β†’file groups, L3β†’directory overview). Compact JSON output saves 15-20% tokens
  • Embedding model β€” Optional local embedding via Candle (feature-gated embed-model). Context reordered to prioritize structural relations over code for better embedding quality
  • Self-healing β€” Automatic SQLite corruption recovery with rebuild. Startup repair for incomplete indexing (Phase 3 failures)
  • MCP protocol β€” JSON-RPC 2.0 over stdio, plug-and-play with Claude Code, Cursor, Windsurf, and other MCP clients
  • Claude Code Plugin β€” First-class plugin with slash commands (/understand, /trace, /impact), agents, skills, auto-indexing hooks, StatusLine integration, and self-updating

Why code-graph-mcp?

Unlike naive full-text search or simple AST dumps, code-graph-mcp builds a structured knowledge graph that understands the relationships between symbols across your entire codebase.

Incremental by Design

BLAKE3 Merkle tree tracks every file's content hash. On re-index, only changed files are re-parsed β€” unchanged directory subtrees are skipped entirely via mtime cache. When a function signature changes, dirty propagation automatically regenerates context for all downstream callers across files.

Hybrid Search, Not Just Grep

Combines BM25 full-text ranking (FTS5) with vector semantic similarity (sqlite-vec) via Reciprocal Rank Fusion (RRF) with raw score blending β€” so searching "handle user login" finds the right function even if it's named authenticate_session. Results are auto-compressed to fit LLM context windows.

Scope-Aware Relation Extraction

The parser doesn't just find function calls β€” it tracks them within their proper scope context. Extracts calls, imports, inheritance, interface implementations, exports, and HTTP route bindings. Same-file targets are preferred over cross-file matches to minimize false-positive edges.

HTTP Request Flow Tracing

Unique to code-graph-mcp: trace from GET /api/users β†’ route handler β†’ service layer β†’ database call in a single query. Supports Express, Flask/FastAPI, and Go HTTP frameworks.

Zero External Dependencies at Runtime

Single binary, embedded SQLite, bundled sqlite-vec extension, optional local embedding model via Candle β€” no database server, no cloud API, no Docker required. Runs entirely on your machine.

Built for AI Assistants

Every design decision β€” from token-aware compression to node_id-based snippet expansion β€” is optimized for LLM context windows. Works out of the box with Claude Code, Cursor, Windsurf, and any MCP-compatible client.

Performance

MetricValue
Indexing speed300+ files/second (single-threaded, release build)
Incremental re-index<250ms no-change detection via BLAKE3 Merkle tree
FTS search P50 / P99<300us / <1ms
Database overhead~3.5MB per 800 nodes
Token savings5-20x fewer tokens per code understanding task vs grep+read

Run code-graph-mcp benchmark on your own project to measure.

Efficiency: code-graph vs Traditional Tools

Real-world benchmarks comparing code-graph-mcp tools against traditional approaches (Grep + Read + Glob) on a 33-file Rust project (~537 AST nodes).

Tool Call Reduction

ScenarioTraditionalcode-graphSavings
Project architecture overview5-8 calls1 call (project_map)~85%
Find function by concept3-5 calls1 call (semantic_code_search)~75%
Trace 2-level call chain8-15 calls1 call (get_call_graph)~90%
Pre-change impact analysis10-20+ calls1 call (impact_analysis)~95%
Module structure & exports5+ calls1 call (module_overview)~80%
File dependency mapping3-5 calls1 call (dependency_graph)~75%
Similar code detectionN/A1 call (find_similar_code)unique

Overall Session Efficiency

MetricWithout code-graphWith code-graphImprovement
Tool calls per navigation task~6~1.2~80% fewer
Source lines read into context~8,000 lines~400 lines (structured)~95% less
Navigation token cost~36K tokens~7K tokens~80% saved
Full session token savingsβ€”β€”40-60%

What code-graph Uniquely Enables

  • Impact analysis β€” "Changing conn affects 33 functions across 4 files, 78 tests at HIGH risk" β€” impossible to derive manually with Grep
  • Transitive call tracing β€” Follow main β†’ run_serve β†’ handle_message β†’ handle_tools_call β†’ conn in one query
  • Semantic search β€” Find authenticate_session when searching "handle user login"
  • Dependency strength β€” Not just "file A imports file B", but "file A uses 38 symbols from file B"

When Traditional Tools Are Still Better

Use CaseBest Tool
Exact string / constant searchGrep
Reading a file to edit itRead
Finding files by name patternGlob

Architecture

src/
β”œβ”€β”€ domain.rs     # Shared constants, relation types, env-var config
β”œβ”€β”€ mcp/          # MCP protocol layer (JSON-RPC, tool registry, server)
β”‚   └── server/   # McpServer with IndexingState + CacheState sub-structs
β”œβ”€β”€ parser/       # Tree-sitter parsing, relation extraction, LanguageConfig dispatch
β”œβ”€β”€ indexer/      # 3-phase pipeline, Merkle tree, file watcher
β”œβ”€β”€ storage/      # SQLite schema (v6), CRUD, FTS5, migrations
β”œβ”€β”€ graph/        # Recursive CTE call graph queries
β”œβ”€β”€ search/       # RRF fusion search combining BM25 + vector
β”œβ”€β”€ embedding/    # Candle embedding model (optional, masked mean pooling)
β”œβ”€β”€ sandbox/      # Context compressor with token estimation
└── utils/        # Language detection, config

Installation

Install as a Claude Code plugin for the best experience β€” includes slash commands, agents, skills, auto-indexing hooks, StatusLine health display, and automatic updates:

# Step 1: Add the marketplace
/plugin marketplace add sdsrss/code-graph-mcp

# Step 2: Install the plugin
/plugin install code-graph-mcp

What you get:

  • MCP Server β€” All code-graph tools available to Claude
  • Slash Commands β€” /understand <module>, /trace <route>, /impact <symbol>
  • Code Explorer Agent β€” Deep code understanding expert via code-explorer
  • Auto-indexing Hook β€” Incremental index on every file edit (PostToolUse)
  • StatusLine β€” Real-time health display (nodes, files, watch status) β€” compatible with other plugins' StatusLine via composite multiplexer
  • Auto-update β€” Checks for new versions every 6h, updates silently

Manual Update

npm update -g @sdsrs/code-graph

Then reconnect the MCP server in Claude Code with /mcp.

Note: Auto-update is disabled in the source repo directory (dev mode). Use manual update when developing the plugin itself.

Invited-memory mode (quieter prompts)

By default, every user prompt the plugin deems code-related gets a small context injection from code-graph CLI output. If you'd rather rely on MEMORY.md + explicit tool calls, opt into invited-memory mode:

  • Adopt the plugin contract into your project's memory index (idempotent, self-heals):
    code-graph-mcp adopt
    
    This writes plugin_code_graph_mcp.md (decision rules) into ~/.claude/projects/<slug>/memory/ and links it from MEMORY.md inside a sentinel block. Run code-graph-mcp unadopt to remove.
  • Set the activation env var in ~/.claude/settings.json:
    {
      "env": { "CODE_GRAPH_QUIET_HOOKS": "1" }
    }
    
  • Restart Claude Code. Session startup skips the project-map injection, UserPromptSubmit stops auto-injecting context, and the MCP instructions become a short pointer to the MEMORY.md file.

Option 2: Claude Code MCP Server Only

Register as an MCP server without the plugin features:

claude mcp add code-graph-mcp -- npx -y @sdsrs/code-graph

Option 3: Cursor / Windsurf / Other MCP Clients

Add to your MCP settings file (e.g. ~/.cursor/mcp.json):

{
  "mcpServers": {
    "code-graph": {
      "command": "npx",
      "args": ["-y", "@sdsrs/code-graph"]
    }
  }
}

Option 4: npx (No Install)

Run directly without installing:

npx -y @sdsrs/code-graph

Option 5: npm (Global Install)

Install globally, then run anywhere:

npm install -g @sdsrs/code-graph
code-graph-mcp

Uninstallation

Claude Code Plugin

# Uninstall the plugin
/plugin uninstall code-graph-mcp

# (Optional) Remove the marketplace
/plugin marketplace remove code-graph-mcp

# (Optional) Clean up all config and cache data
node ~/.claude/plugins/cache/code-graph-mcp/code-graph-mcp/*/scripts/lifecycle.js uninstall

Claude Code MCP Server

claude mcp remove code-graph-mcp

Cursor / Windsurf / Other MCP Clients

Remove the code-graph entry from your MCP settings file (e.g. ~/.cursor/mcp.json).

npm (Global)

npm uninstall -g @sdsrs/code-graph

MCP Tools

ToolDescription
project_mapFull project architecture: modules, dependencies, entry points, hot functions
semantic_code_searchHybrid BM25 + vector + graph search for AST nodes
get_call_graphTrace upstream/downstream call chains for a function
trace_http_chainFull request flow: route β†’ handler β†’ downstream call chain
impact_analysisAnalyze the blast radius of changing a symbol
module_overviewHigh-level overview of a module's structure and exports
dependency_graphVisualize dependency relationships between modules. Supports compact mode
find_similar_codeFind semantically similar code via embeddings. Requires symbol_name or node_id
get_ast_nodeExtract a specific code symbol with signature, body, and relations. Supports compact mode
ast_searchSearch AST nodes by text and/or structural filters (type, return type, params)
find_referencesFind all references to a symbol (callers, importers, inheritors). Supports compact mode
find_dead_codeFind unused code β€” orphan symbols and exported-but-unused public APIs

CLI Commands

All tools are also available as CLI subcommands for shell scripts, hooks, and terminal workflows:

CommandMCP EquivalentDescription
search <query>semantic_code_searchFTS5 search by concept
ast-search [query]ast_searchStructural search with --type/--returns/--params filters
callgraph <symbol>get_call_graphShow call graph (callers/callees)
impact <symbol>impact_analysisImpact analysis (callers, routes, risk level)
show <symbol>get_ast_nodeShow symbol details (code, type, signature)
mapproject_mapProject architecture map
overview <path>module_overviewModule symbols grouped by file and type
deps <file>dependency_graphFile-level dependency graph
trace <route>trace_http_chainTrace HTTP route β†’ handler β†’ downstream calls
similar <symbol>find_similar_codeFind semantically similar code (requires embeddings)
refs <symbol>find_referencesFind all references to a symbol
dead-code [path]find_dead_codeFind unused code (orphans and exported-unused)
grep <pattern>β€”AST-context grep (ripgrep + containing function/class)
incremental-indexβ€”Run incremental index update (auto-creates DB if needed)
health-checkget_index_statusQuery index status and freshness
benchmarkβ€”Benchmark index speed, query latency, token savings

Common options: --json (JSON output), --compact (compact output), --limit N, --depth N, --file <path>.

Plugin Slash Commands

Available when installed as a Claude Code plugin:

CommandDescription
/understand <module>Deep dive into a module or file's architecture and relationships
/trace <route>Trace a full HTTP request flow from route to data layer
/impact <symbol>Analyze the impact scope of changing a symbol before modifying it
/statusShow code-graph index status and embedding progress
/rebuildForce a full code-graph index rebuild

Supported Languages (16)

LanguageExtensionsRelations Extracted
TypeScript.ts, .tsxcalls, imports, exports, inherits, implements, routes_to
JavaScript.js, .jsx, .mjs, .cjscalls, imports, exports, inherits, routes_to
Go.gocalls, imports, routes_to
Python.py, .pyicalls, imports, inherits, routes_to
Rust.rscalls, imports, inherits, implements
Java.javacalls, imports, inherits, implements
C#.cscalls, imports, inherits, implements
Kotlin.kt, .ktscalls, imports, inherits
Ruby.rbcalls, imports, inherits
PHP.phpcalls, imports, inherits, implements
Swift.swiftcalls, imports, inherits
Dart.dartcalls, imports, implements
C.c, .hcalls, imports
C++.cpp, .cc, .cxx, .hppcalls, imports, inherits
HTML.html, .htmstructural parsing
CSS.cssstructural parsing

Team-shared graph snapshot

Skip the full local index for team members and CI runners by publishing a ~3-5MB graph snapshot with each GitHub release.

Setup (one-time):

  • Copy node_modules/code-graph-mcp/templates/code-graph-snapshot.yml into your repo's .github/workflows/.
  • Push a release tag. The workflow uploads code-graph-snapshot-<sha>.db.zst as a release asset.

Verify:

npx code-graph-mcp snapshot inspect ./code-graph-snapshot-<sha>.db.zst

After setup, fresh clones automatically fetch the latest snapshot the first time the MCP server starts. No client-side configuration needed.

Storage

Uses SQLite with:

  • FTS5 for full-text search
  • sqlite-vec extension for vector similarity search
  • Merkle tree hashes for incremental change detection

Data is stored in .code-graph/index.db under the project root (auto-created, gitignored).

Build from Source

Prerequisites

  • Rust 1.75+ (2021 edition)
  • A C compiler (for bundled SQLite / sqlite-vec)

Build

# Default build β€” FTS5-only (~10 MB binary, no embedding model)
cargo build --release

# With local embedding model (~150 MB binary; downloads ~120 MB model lazily on first semantic search)
cargo build --release --features embed-model

Direct cargo install users get the FTS5-only build by default. npm/npx/plugin users get the full hybrid (FTS5 + vector) build automatically β€” release CI compiles with --features embed-model for shipped binaries.

Configure (from source)

Add the compiled binary to your MCP settings:

{
  "mcpServers": {
    "code-graph": {
      "command": "/path/to/target/release/code-graph-mcp"
    }
  }
}

Development

# Run tests
cargo test

# Run tests without embedding model
cargo test --no-default-features

# Check compilation
cargo check

# Run performance benchmarks (indexing, search, call graph)
cargo bench --no-default-features

License

See LICENSE for details.

Keywords

mcp

FAQs

Package last updated on 10 May 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts