Stores and queries code graph representations with vector indexing, enabling graph traversal, relationship analysis, and semantic search across parsed TypeScript/NestJS codebases.
Provides deep understanding of NestJS architectural patterns including controllers, services, modules, dependency injection, HTTP endpoints, guards, pipes, and interceptors.
Generates embeddings for semantic code search, powers natural language to Cypher query conversion, and enables vector-based similarity matching for code discovery.
Parses TypeScript projects using AST analysis to extract code entities, relationships, and framework patterns for graph-based code understanding.
Code Graph Context MCP Server
A Model Context Protocol (MCP) server that builds rich code graphs to provide deep contextual understanding of TypeScript codebases to Large Language Models. This server parses your codebase using AST analysis, constructs a comprehensive graph representation in Neo4j, and provides intelligent querying capabilities through semantic search and graph traversal.
Config-Driven & Extensible: Define custom framework schemas to capture domain-specific patterns beyond the included NestJS support. The parser is fully configurable to recognize your architectural patterns, decorators, and relationships.
Features
Rich Code Graph Generation: Parses TypeScript projects and creates detailed graph representations with AST-level precision
Semantic Search: Vector-based semantic search using OpenAI embeddings to find relevant code patterns and implementations
Natural Language Querying: Convert natural language questions into Cypher queries using OpenAI assistants API
Framework-Aware & Customizable: Built-in NestJS schema with ability to define custom framework patterns via configuration
Weighted Graph Traversal: Intelligent traversal that scores paths based on relationship importance, query relevance, and depth
High Performance: Optimized Neo4j storage with vector indexing for fast retrieval
MCP Integration: Seamless integration with Claude Code and other MCP-compatible tools
Architecture
The MCP server consists of several key components:
Core Components
TypeScript Parser (
src/core/parsers/typescript-parser-v2.ts): Usests-morphto parse TypeScript AST and extract code entitiesGraph Storage (
src/storage/neo4j/neo4j.service.ts): Neo4j integration for storing and querying the code graphEmbeddings Service (
src/core/embeddings/embeddings.service.ts): OpenAI integration for semantic search capabilitiesMCP Server (
src/mcp/mcp.server.ts): Main MCP server providing tools for code analysis
Graph Schema
The system uses a dual-schema approach:
Core Schema: AST-level nodes (Classes, Methods, Properties, Imports, etc.)
Framework Schema: Semantic interpretations (NestJS Controllers, Services, HTTP Endpoints, etc.)
Getting Started
Prerequisites
Node.js >= 18
Neo4j >= 5.0 with APOC plugin
OpenAI API Key (for embeddings and natural language processing)
Docker (recommended for Neo4j setup)
Installation
Choose the installation method that works best for you:
Option 1: Development Install (From Source)
Best for: Contributing to the project or customizing the code
Clone the repository:
Install dependencies:
Set up Neo4j using Docker:
This will start Neo4j with:
Web interface: http://localhost:7474
Bolt connection: bolt://localhost:7687
Username:
neo4j, Password:PASSWORD
Configure environment variables:
Build the project:
Add to Claude Code:
Option 2: NPM Install (Global Package)
Best for: Easy setup and automatic updates
Install the package globally:
Set up Neo4j (choose one):
Option A: Docker (Recommended)
Option B: Neo4j Desktop
Download from neo4j.com/download
Install APOC plugin
Start database
Option C: Neo4j Aura (Cloud)
Create free account at neo4j.com/cloud/aura
Note your connection URI and credentials
Add to Claude Code:
Then configure in your MCP config file (~/.config/claude/config.json):
Note: The env vars can be configured for any Neo4j instance - local, Docker, cloud (Aura), or enterprise.
Verify Installation
After installation, verify everything is working:
Check Neo4j is running:
Test APOC plugin:
Should return a list of APOC functions.
Test MCP server connection:
Should show: code-graph-context: ✓ Connected
Troubleshooting
"APOC plugin not found"
"OPENAI_API_KEY environment variable is required"
Get your API key from: https://platform.openai.com/api-keys
Add to Claude Code MCP config
envsectionVerify with:
echo $OPENAI_API_KEY(if using shell env)
"Connection refused bolt://localhost:7687"
"Neo4j memory errors"
"MCP server not responding"
Tool Usage Guide & Sequential Workflows
Sequential Tool Usage Patterns
The MCP tools are designed to work together in powerful workflows. Here are the most effective patterns:
Pattern 1: Discovery → Focus → Deep Dive
Pattern 2: Broad Search → Targeted Analysis
Start Broad: Use
search_codebaseto find relevant starting pointsFocus: Use
traverse_from_nodeto explore specific relationshipsPaginate: Use
skipparameter to explore different sections of the graph
Tool Deep Dive
1. search_codebase - Your Starting Point
Purpose: Semantic search using vector embeddings to find the most relevant code nodes.
Response Structure: Returns normalized JSON using JSON:API pattern to eliminate duplication:
nodes: Map of unique nodes (stored once, referenced by ID)
depths: Array of depth levels with relationship chains
Source Code: Included by default (truncated to 1000 chars: first 500 + last 500)
Statistics: Total connections, unique files, max depth
Real Response Example:
Key Features:
JSON:API Normalization: Nodes stored once in
nodesmap, referenced by ID to eliminate duplicationSource Code Truncation: Max 1000 chars per snippet (first 500 + last 500 chars)
Relationship Chains: Shows full path like "HAS_MEMBER → INJECTS → USES_REPOSITORY"
Direction Indicators: OUTGOING (what this calls), INCOMING (who calls this)
Pro Tips:
Use specific domain terms: "JWT token validation" vs "authentication"
Start with limit=1-3 for initial exploration to avoid token limits
Look for node IDs in
nodesmap to use withtraverse_from_nodeCheck
truncatedfield to see how many bytes were hidden from source code
2. traverse_from_node - Deep Relationship Exploration
Purpose: Explore all connections from a specific node with precise control over depth and pagination.
Response Structure: Identical JSON:API format to search_codebase:
Focused Traversal: Starts from your specified node
Depth Control: Configurable max depth (1-10, default 3)
Pagination: Skip parameter for exploring large graphs in chunks
Source Code Included by Default: Set
includeCode: falsefor structure-only view
Real Response Example:
Parameters:
nodeId(required): Node ID from search_codebase resultsmaxDepth(default: 3): Traversal depth (1-10)skip(default: 0): Pagination offsetincludeCode(default: true): Include source code snippetssummaryOnly(default: false): Just file paths and statisticsdirection(default: BOTH): Filter by OUTGOING/INCOMING/BOTHrelationshipTypes(optional): Filter by specific relationships like ["INJECTS", "USES_REPOSITORY"]
Pagination Strategy:
3. parse_typescript_project - Graph Generation
Purpose: Parse a TypeScript/NestJS project and build the initial graph database.
Performance Notes:
Large projects (>1000 files) may take several minutes
Embedding generation adds significant time but enables semantic search
Use
clearExisting: trueto avoid duplicate data
4. test_neo4j_connection - Health Check
Purpose: Verify database connectivity and APOC plugin availability.
Workflow Examples
Example 1: Understanding Authentication Flow
Example 2: API Endpoint Analysis
Example 3: Service Dependency Mapping
Advanced Usage Tips
Understanding Response Format (JSON:API Normalization)
Key Insight: All responses use JSON:API pattern to eliminate duplication by storing each node once and referencing by ID.
How to Read Responses:
Start with : All unique nodes are stored here once
Look at : Shows how nodes are connected at each depth level
Follow : Use IDs to look up full node data in
nodesmapCheck : Indicates how many bytes of source code were hidden
Example Reading Pattern:
Managing Large Responses
Start Small: Use
limit: 1-3for initial searchesRelationship Filtering: Use
relationshipTypesto focus on specific connectionsStructure-Only View: Set
includeCode: falseto exclude source code snippetsSummary Mode: Use
summaryOnly: truefor just file paths and statistics
Efficient Graph Exploration
Breadth First: Start with low
maxDepth(1-2) to get overviewDepth Second: Increase
maxDepth(3-5) for detailed analysisDirection Filtering: Use
direction: "OUTGOING"or"INCOMING"to focus explorationSource Code on Demand: Source code included by default but truncated to 1000 chars
Weighted Traversal
The search_codebase tool uses weighted traversal by default (useWeightedTraversal: true) to intelligently prioritize which relationships to explore. This produces more relevant results by scoring each node at every depth level.
How Scoring Works:
Each potential path is scored using three factors multiplied together:
Edge Weight (0.0-1.0): How important is this relationship type?
Critical (0.9-0.95):
INJECTS,EXPOSES,ROUTES_TO- core architectural relationshipsHigh (0.8-0.88):
EXTENDS,IMPLEMENTS,USES_REPOSITORY- important semantic linksMedium (0.5-0.6):
IMPORTS,EXPORTS,HAS_MEMBER- structural relationshipsLow (0.3-0.4):
DECORATED_WITH,HAS_PARAMETER- metadata relationships
Node Similarity: Cosine similarity between the node's embedding and your query embedding. Nodes semantically related to your search rank higher.
Depth Penalty: Exponential decay (default 0.85 per level). Closer nodes are preferred:
Depth 1: 1.0 (no penalty)
Depth 2: 0.85
Depth 3: 0.72
When to Disable:
Performance Optimization
Token Efficiency: JSON:API normalization eliminates duplicate nodes in responses
Code Truncation: Source code limited to 1000 chars (first 500 + last 500) to prevent token overflow
Memory: Large traversals may hit Neo4j memory limits (increase heap size if needed)
Caching: Node IDs are persistent; save interesting ones for later exploration
Available MCP Tools
Core Tools
Tool | Description | Parameters | Use Case |
| Test tool that says hello | None | Verify MCP connection |
| Test Neo4j connection and APOC plugin | None | Health check before operations |
Parsing Tools
Tool | Description | Parameters | Use Case |
| Parse TypeScript/NestJS project into graph |
,
,
| Initial setup: build the graph database |
Search & Exploration Tools
Tool | Description | Parameters | Best For |
| Vector-based semantic search - Find most relevant code using OpenAI embeddings |
,
,
(default: true) | Starting point for code exploration. Uses weighted scoring for intelligent traversal |
| Focused graph traversal - Explore specific relationships from a known node |
(string),
(1-10, default: 3),
(default: 0) | Deep diving into specific code relationships. Pagination for large graphs |
| AI-powered query generation - Convert natural language to Cypher queries using GPT-4 |
(string) | Advanced queries - currently requires OpenAI assistant setup |
Tool Selection Guide
Start Here: search_codebase
Use when you don't know specific node IDs
Best for exploring new codebases
Returns rich context with code snippets
Go Deeper: traverse_from_node
Use when you have specific node IDs from search results
Perfect for understanding relationships and dependencies
Use
skipparameter for pagination through large result sets
Advanced: natural_language_to_cypher
Requires additional OpenAI assistant configuration
Best for complex queries beyond simple search/traversal
Currently in development - may require setup
Claude Code Integration Tips
Guiding Tool Usage with claude.md
You can add a claude.md file to your repository root to help Claude Code understand when to use these MCP tools effectively. Here are some useful patterns:
Trigger Word Hints
Weighted Traversal Hints
Framework-Specific Patterns
Document your custom node types and relationships so Claude knows what to search for:
Common Query Examples
Framework Support
NestJS Framework Schema
The server provides deep understanding of NestJS patterns:
Node Types
Controllers: HTTP endpoint handlers with route analysis
Services: Business logic providers with dependency injection mapping
Modules: Application structure with import/export relationships
Guards: Authentication and authorization components
Pipes: Request validation and transformation
Interceptors: Request/response processing middleware
DTOs: Data transfer objects with validation decorators
Entities: Database models with relationship mapping
Relationship Types
Module System:
MODULE_IMPORTS,MODULE_PROVIDES,MODULE_EXPORTSDependency Injection:
INJECTS,PROVIDED_BYHTTP API:
EXPOSES,ACCEPTS,RESPONDS_WITHSecurity:
GUARDED_BY,TRANSFORMED_BY,INTERCEPTED_BY
Example Graph Structure
Configuration
Environment Variables
Variable | Description | Default |
| OpenAI API key for embeddings and LLM | Required |
| Reuse existing OpenAI assistant | Optional |
| Neo4j database URI |
|
| Neo4j username |
|
| Neo4j password |
|
Parse Options
Customize parsing behavior:
Limitations
Current Limitations
Language Support: Currently supports TypeScript/NestJS only
Framework Support: Primary focus on NestJS patterns
File Size: Large files (>10MB) may cause parsing performance issues
Memory Usage: Graph generation is memory-intensive for very large projects
Vector Search: Requires OpenAI API for semantic search functionality
Real-time Updates: No file watching - requires manual re-parsing for code changes
Response Size: Large graph traversals can exceed token limits (25,000 tokens max)
Neo4j Memory: Database memory limits can cause query failures on large graphs
Performance Considerations
Large Projects: Projects with >10,000 files may require increased memory allocation
Graph Traversal: Deep traversals (>5 levels) may be slow for highly connected graphs
Embedding Generation: Initial parsing with embeddings can take several minutes for large codebases
Neo4j Memory: Recommend at least 4GB RAM allocation for Neo4j with large graphs
Known Issues
Complex Type Inference: Advanced TypeScript type gymnastics may not be fully captured
Dynamic Imports: Runtime module loading not tracked in static analysis
Decorator Arguments: Complex decorator argument patterns may not be fully parsed
Monorepo Support: Limited support for complex monorepo structures
Troubleshooting
Common Issues
Neo4j Connection Failed
Neo4j Memory Issues
If you encounter errors like "allocation of an extra X MiB would use more than the limit":
Token Limit Exceeded
If responses exceed 25,000 tokens:
OpenAI API Issues
Parsing Failures
Debug Mode
Enable detailed logging:
Contributing
Fork the repository
Create a feature branch:
git checkout -b feature/amazing-featureCommit your changes:
git commit -m 'Add amazing feature'Push to the branch:
git push origin feature/amazing-featureOpen a Pull Request
Development Setup
License
This project is proprietary software. All rights reserved - see the LICENSE file for details.
Acknowledgments
Model Context Protocol by Anthropic
Neo4j for graph database technology
ts-morph for TypeScript AST manipulation
OpenAI for embeddings and natural language processing
NestJS for the framework patterns and conventions
Support
Create an Issue for bug reports or feature requests
Join the MCP Discord for community support
Check the MCP Documentation for MCP-specific questions
This server cannot be installed