code-graph-context 2.4.5 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Code Graph Context MCP Server
1
+ # Code Graph Context
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/code-graph-context.svg)](https://www.npmjs.com/package/code-graph-context)
4
4
  [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
@@ -8,77 +8,139 @@
8
8
  [![OpenAI](https://img.shields.io/badge/OpenAI-Powered-412991?logo=openai&logoColor=white)](https://openai.com/)
9
9
  [![MCP](https://img.shields.io/badge/MCP-Server-blue)](https://modelcontextprotocol.io/)
10
10
 
11
- 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.
12
-
13
- **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.
11
+ **Give your AI coding assistant a photographic memory of your codebase.**
12
+
13
+ Code Graph Context is an MCP server that builds a semantic graph of your TypeScript codebase, enabling Claude to understand not just individual files, but how your entire system fits together.
14
+
15
+ > **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.
16
+
17
+ ```
18
+ ┌─────────────────────────────────────────────────────────────┐
19
+ │ YOUR CODEBASE │
20
+ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
21
+ │ │ Service │ │Controller│ │ Module │ │ Entity │ │
22
+ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
23
+ └───────┼─────────────┼─────────────┼─────────────┼──────────┘
24
+ │ │ │ │
25
+ ▼ ▼ ▼ ▼
26
+ ┌─────────────────────────────────────────────────────────────┐
27
+ │ CODE GRAPH CONTEXT │
28
+ │ │
29
+ │ AST Parser ──► Neo4j Graph ──► Vector Embeddings │
30
+ │ (ts-morph) (Relationships) (OpenAI) │
31
+ │ │
32
+ └─────────────────────────────────────────────────────────────┘
33
+
34
+
35
+ ┌─────────────────────────────────────────────────────────────┐
36
+ │ CLAUDE CODE │
37
+ │ │
38
+ │ "What services depend on UserService?" │
39
+ │ "What's the blast radius if I change this function?" │
40
+ │ "Find all HTTP endpoints that accept a UserDTO" │
41
+ │ "Refactor this across all 47 files that use it" │
42
+ │ │
43
+ └─────────────────────────────────────────────────────────────┘
44
+ ```
45
+
46
+ ## Why Code Graph Context?
47
+
48
+ | Without Code Graph | With Code Graph |
49
+ |---|---|
50
+ | Claude reads files one at a time | Claude understands the entire dependency tree |
51
+ | "What uses this?" requires manual searching | Instant impact analysis with risk scoring |
52
+ | Refactoring misses edge cases | Graph traversal finds every reference |
53
+ | Large codebases overwhelm context | Semantic search finds exactly what's relevant |
54
+ | Multi-file changes are error-prone | Swarm agents coordinate parallel changes |
14
55
 
15
56
  ## Features
16
57
 
17
- - **Multi-Project Support**: Parse and query multiple projects in a single database with complete isolation via `projectId`
18
- - **Rich Code Graph Generation**: Parses TypeScript projects and creates detailed graph representations with AST-level precision
19
- - **Semantic Search**: Vector-based semantic search using OpenAI embeddings to find relevant code patterns and implementations
20
- - **Natural Language Querying**: Convert natural language questions into Cypher queries using OpenAI assistants API
21
- - **Framework-Aware & Customizable**: Built-in NestJS schema with ability to define custom framework patterns via configuration
22
- - **Weighted Graph Traversal**: Intelligent traversal that scores paths based on relationship importance, query relevance, and depth
23
- - **Workspace & Monorepo Support**: Auto-detects Nx, Turborepo, pnpm, Yarn, and npm workspaces
24
- - **Parallel Parsing**: Multi-threaded parsing with configurable worker pool for maximum CPU utilization
25
- - **Async Parsing**: Background parsing with Worker threads for large codebases without blocking the MCP server
26
- - **Streaming Import**: Chunked processing for projects with 100+ files to prevent memory issues
27
- - **TypeAlias Support**: Full parsing of TypeScript type aliases into graph nodes
28
- - **Incremental Parsing**: Only reparse changed files for faster updates
29
- - **File Watching**: Real-time monitoring with automatic incremental graph updates on file changes
30
- - **Impact Analysis**: Assess refactoring risk with dependency analysis (LOW/MEDIUM/HIGH/CRITICAL scoring)
31
- - **Dead Code Detection**: Find unreferenced exports, uncalled private methods, unused interfaces with confidence scoring
32
- - **Duplicate Code Detection**: Identify structural duplicates (identical AST) and semantic duplicates (similar logic via embeddings)
33
- - **Swarm Coordination**: Multi-agent stigmergic coordination through pheromone markers with exponential decay
34
- - **High Performance**: Optimized Neo4j storage with vector indexing for fast retrieval
35
- - **MCP Integration**: Seamless integration with Claude Code and other MCP-compatible tools
58
+ - **Multi-Project Support**: Parse and query multiple projects in a single database with complete isolation
59
+ - **Semantic Search**: Vector-based search using OpenAI embeddings to find relevant code
60
+ - **Natural Language Querying**: Convert questions into Cypher queries
61
+ - **Framework-Aware**: Built-in NestJS schema with ability to define custom framework patterns
62
+ - **Weighted Graph Traversal**: Intelligent traversal scoring paths by importance and relevance
63
+ - **Workspace Support**: Auto-detects Nx, Turborepo, pnpm, Yarn, and npm workspaces
64
+ - **Parallel & Async Parsing**: Multi-threaded parsing with Worker threads for large codebases
65
+ - **Streaming Import**: Chunked processing for projects with 100+ files
66
+ - **Incremental Parsing**: Only reparse changed files
67
+ - **File Watching**: Real-time graph updates on file changes
68
+ - **Impact Analysis**: Assess refactoring risk (LOW/MEDIUM/HIGH/CRITICAL)
69
+ - **Dead Code Detection**: Find unreferenced exports with confidence scoring
70
+ - **Duplicate Detection**: Structural (AST hash) and semantic (embedding similarity) duplicates
71
+ - **Swarm Coordination**: Multi-agent stigmergic coordination with pheromone decay
36
72
 
37
73
  ## Architecture
38
74
 
39
- The MCP server consists of several key components:
40
-
41
- ### Core Components
42
-
43
- 1. **TypeScript Parser** (`src/core/parsers/typescript-parser.ts`): Uses `ts-morph` to parse TypeScript AST and extract code entities
44
- 2. **Graph Storage** (`src/storage/neo4j/neo4j.service.ts`): Neo4j integration for storing and querying the code graph
45
- 3. **Embeddings Service** (`src/core/embeddings/embeddings.service.ts`): OpenAI integration for semantic search capabilities
46
- 4. **MCP Server** (`src/mcp/mcp.server.ts`): Main MCP server providing tools for code analysis
75
+ ```
76
+ TypeScript Source → AST Parser (ts-morph) → Neo4j Graph + Vector Embeddings → MCP Tools
77
+ ```
47
78
 
48
- ### Graph Schema
79
+ **Core Components:**
80
+ - `src/core/parsers/typescript-parser.ts` - AST parsing with ts-morph
81
+ - `src/storage/neo4j/neo4j.service.ts` - Graph storage and queries
82
+ - `src/core/embeddings/embeddings.service.ts` - OpenAI embeddings
83
+ - `src/mcp/mcp.server.ts` - MCP server and tool registration
49
84
 
50
- The system uses a dual-schema approach:
85
+ **Dual-Schema System:**
86
+ - **Core Schema**: AST-level nodes (ClassDeclaration, MethodDeclaration, ImportDeclaration, etc.)
87
+ - **Framework Schema**: Semantic interpretation (NestController, NestService, HttpEndpoint, etc.)
51
88
 
52
- - **Core Schema**: AST-level nodes (Classes, Methods, Properties, Imports, etc.)
53
- - **Framework Schema**: Semantic interpretations (NestJS Controllers, Services, HTTP Endpoints, etc.)
89
+ Nodes have both `coreType` (AST) and `semanticType` (framework meaning), enabling queries like "find all controllers" while maintaining AST precision.
54
90
 
55
- ## Getting Started
91
+ ## Quick Start
56
92
 
57
93
  ### Prerequisites
58
94
 
59
95
  - **Node.js** >= 18
60
- - **Neo4j** >= 5.23 with APOC plugin
61
- - **OpenAI API Key** (for embeddings and natural language processing)
62
- - **Docker** (recommended for Neo4j setup)
96
+ - **Docker** (for Neo4j)
97
+ - **OpenAI API Key**
63
98
 
64
- ### Installation
65
99
 
66
- Choose the installation method that works best for you:
67
100
 
68
- #### Option 1: NPM Install (Recommended)
101
+ ### 1. Install
69
102
 
70
103
  ```bash
71
- # Install globally
72
104
  npm install -g code-graph-context
105
+ code-graph-context init # Sets up Neo4j via Docker
106
+ ```
107
+
108
+ ### 2. Configure Claude Code
73
109
 
74
- # Set up Neo4j (requires Docker)
75
- code-graph-context init
110
+ Add to Claude Code with your OpenAI API key:
76
111
 
77
- # Add to Claude Code (--scope user makes it available globally)
78
- claude mcp add --scope user code-graph-context code-graph-context
112
+ ```bash
113
+ claude mcp add --scope user code-graph-context \
114
+ -e OPENAI_API_KEY=sk-your-key-here \
115
+ -- code-graph-context
79
116
  ```
80
117
 
81
- Then configure your OpenAI API key in `~/.claude.json`:
118
+ **That's it.** Restart Claude Code and you're ready to go.
119
+
120
+ ### 3. Parse Your Project
121
+
122
+ In Claude Code, say:
123
+ > "Parse this project and build the code graph"
124
+
125
+ Claude will run `parse_typescript_project` and index your codebase.
126
+
127
+ ---
128
+
129
+ ## Configuration Files
130
+
131
+ Claude Code stores MCP server configs in JSON files. The location depends on scope:
132
+
133
+ | Scope | File | Use Case |
134
+ |-------|------|----------|
135
+ | User (global) | `~/.claude.json` | Available in all projects |
136
+ | Project | `.claude.json` in project root | Project-specific config |
137
+ | Local | `.mcp.json` in project root | Git-ignored local overrides |
138
+
139
+ ### Manual Configuration
140
+
141
+ If you prefer to edit the config files directly:
142
+
143
+ **~/.claude.json** (user scope - recommended):
82
144
  ```json
83
145
  {
84
146
  "mcpServers": {
@@ -92,692 +154,470 @@ Then configure your OpenAI API key in `~/.claude.json`:
92
154
  }
93
155
  ```
94
156
 
95
- #### Option 2: From Source
157
+ **From source installation:**
158
+ ```json
159
+ {
160
+ "mcpServers": {
161
+ "code-graph-context": {
162
+ "command": "node",
163
+ "args": ["/absolute/path/to/code-graph-context/dist/cli/cli.js"],
164
+ "env": {
165
+ "OPENAI_API_KEY": "sk-your-key-here"
166
+ }
167
+ }
168
+ }
169
+ }
170
+ ```
96
171
 
97
- ```bash
98
- # Clone and build
99
- git clone https://github.com/drewdrewH/code-graph-context.git
100
- cd code-graph-context
101
- npm install
102
- npm run build
172
+ ### Environment Variables
103
173
 
104
- # Set up Neo4j
105
- code-graph-context init
174
+ | Variable | Required | Default | Description |
175
+ |----------|----------|---------|-------------|
176
+ | `OPENAI_API_KEY` | **Yes** | - | For embeddings and NL queries |
177
+ | `NEO4J_URI` | No | `bolt://localhost:7687` | Neo4j connection URI |
178
+ | `NEO4J_USER` | No | `neo4j` | Neo4j username |
179
+ | `NEO4J_PASSWORD` | No | `PASSWORD` | Neo4j password |
106
180
 
107
- # Add to Claude Code (use absolute path)
108
- claude mcp add code-graph-context node /absolute/path/to/code-graph-context/dist/cli/cli.js
109
- ```
181
+ ---
110
182
 
111
- ### CLI Commands
183
+ ## Core Capabilities
112
184
 
113
- The package includes a CLI for managing Neo4j:
185
+ ### Semantic Code Search
114
186
 
115
- ```bash
116
- code-graph-context init [options] # Set up Neo4j container
117
- code-graph-context status # Check Docker/Neo4j status
118
- code-graph-context stop # Stop Neo4j container
119
- ```
187
+ Find code by describing what you need, not by memorizing file paths:
120
188
 
121
- **Init options:**
122
189
  ```
123
- -p, --port <port> Bolt port (default: 7687)
124
- --http-port <port> Browser port (default: 7474)
125
- --password <password> Neo4j password (default: PASSWORD)
126
- -m, --memory <size> Heap memory (default: 2G)
127
- -f, --force Recreate container
190
+ "Find where user authentication tokens are validated"
191
+ "Show me the database connection pooling logic"
192
+ "What handles webhook signature verification?"
128
193
  ```
129
194
 
130
- ### Alternative Neo4j Setup
195
+ ### Impact Analysis
131
196
 
132
- If you prefer not to use the CLI, you can set up Neo4j manually:
197
+ Before you refactor, understand the blast radius:
133
198
 
134
- **Docker Compose:**
135
- ```bash
136
- docker-compose up -d
137
199
  ```
138
-
139
- **Docker Run:**
140
- ```bash
141
- docker run -d \
142
- --name code-graph-neo4j \
143
- -p 7474:7474 -p 7687:7687 \
144
- -e NEO4J_AUTH=neo4j/PASSWORD \
145
- -e 'NEO4J_PLUGINS=["apoc"]' \
146
- neo4j:5.23
200
+ ┌─────────────────────────────────────────────────────────────┐
201
+ Impact Analysis: UserService.findById() │
202
+ ├─────────────────────────────────────────────────────────────┤
203
+ Risk Level: HIGH │
204
+ │ │
205
+ Direct Dependents (12):
206
+ │ └── AuthController.login() │
207
+ │ └── ProfileController.getProfile() │
208
+ │ └── AdminService.getUserDetails() │
209
+ │ └── ... 9 more │
210
+ │ │
211
+ │ Transitive Dependents (34): │
212
+ │ └── 8 controllers, 15 services, 11 tests │
213
+ │ │
214
+ │ Affected Files: 23 │
215
+ │ Recommendation: Add deprecation warning before changing │
216
+ └─────────────────────────────────────────────────────────────┘
147
217
  ```
148
218
 
149
- **Neo4j Desktop:** Download from [neo4j.com/download](https://neo4j.com/download/) and install APOC plugin.
150
-
151
- **Neo4j Aura (Cloud):** Create account at [neo4j.com/cloud/aura](https://neo4j.com/cloud/platform/aura-graph-database/) and configure connection URI in env vars.
219
+ ### Graph Traversal
152
220
 
153
- ### Verify Installation
221
+ Explore relationships in any direction:
154
222
 
155
- After installation, verify everything is working:
156
-
157
- 1. **Check Neo4j is running:**
158
- ```bash
159
- # Open Neo4j Browser
160
- open http://localhost:7474
161
- # Login: neo4j / PASSWORD
162
223
  ```
163
-
164
- 2. **Test APOC plugin:**
165
- ```cypher
166
- CALL apoc.help("apoc")
167
- ```
168
- Should return a list of APOC functions.
169
-
170
- 3. **Test MCP server connection:**
171
- ```bash
172
- claude mcp list
224
+ UserController
225
+
226
+ ├── INJECTS ──► UserService
227
+ │ │
228
+ │ ├── INJECTS ──► UserRepository
229
+ │ │ │
230
+ │ │ └── MANAGES ──► User (Entity)
231
+ │ │
232
+ │ └── INJECTS ──► CacheService
233
+
234
+ └── EXPOSES ──► POST /users
235
+
236
+ └── ACCEPTS ──► CreateUserDTO
173
237
  ```
174
- Should show: `code-graph-context: ✓ Connected`
175
-
176
- ## Tool Usage Guide
177
-
178
- ### Available Tools
179
-
180
- | Tool | Description | Best For |
181
- |------|-------------|----------|
182
- | `list_projects` | List all parsed projects in database | **Discovery** - see available projects and their status |
183
- | `search_codebase` | Semantic search using vector embeddings | **Starting point** - find code by describing what you need |
184
- | `traverse_from_node` | Explore relationships from a specific node | **Deep dive** - understand dependencies and connections |
185
- | `impact_analysis` | Analyze what depends on a node | **Pre-refactoring** - assess blast radius (LOW/MEDIUM/HIGH/CRITICAL) |
186
- | `parse_typescript_project` | Parse project and build the graph | **Initial setup** - supports async mode for large projects |
187
- | `check_parse_status` | Monitor async parsing job progress | **Monitoring** - track background parsing jobs |
188
- | `start_watch_project` | Start file watching for a project | **Live updates** - auto-update graph on file changes |
189
- | `stop_watch_project` | Stop file watching for a project | **Resource management** - stop monitoring |
190
- | `list_watchers` | List all active file watchers | **Monitoring** - see what's being watched |
191
- | `natural_language_to_cypher` | Convert natural language to Cypher | **Advanced queries** - complex graph queries |
192
- | `detect_dead_code` | Find unreferenced exports, uncalled methods, unused interfaces | **Code cleanup** - identify potentially removable code |
193
- | `detect_duplicate_code` | Find structural and semantic code duplicates | **Refactoring** - identify DRY violations |
194
- | `swarm_pheromone` | Leave pheromone markers on code nodes | **Multi-agent** - stigmergic coordination |
195
- | `swarm_sense` | Query pheromones in the code graph | **Multi-agent** - sense what other agents are doing |
196
- | `swarm_cleanup` | Bulk delete pheromones | **Multi-agent** - cleanup after swarm completion |
197
- | `test_neo4j_connection` | Verify database connectivity | **Health check** - troubleshooting |
198
-
199
- > **Note**: All query tools (`search_codebase`, `traverse_from_node`, `impact_analysis`, `natural_language_to_cypher`) require a `projectId` parameter. Use `list_projects` to discover available projects.
200
238
 
201
- ### Tool Selection Guide
239
+ ### Dead Code Detection
202
240
 
203
- - **`list_projects`**: First step - discover what projects are available
204
- - **`search_codebase`**: Find code by describing what you're looking for
205
- - **`traverse_from_node`**: Use node IDs from search results to explore relationships
206
- - **`impact_analysis`**: Before refactoring - understand what depends on the code you're changing
241
+ Find code that can be safely removed:
207
242
 
208
- ### Multi-Project Workflow
209
-
210
- All query tools require a `projectId` parameter to ensure project isolation. You can provide:
211
-
212
- 1. **Project ID**: `proj_a1b2c3d4e5f6` (auto-generated from path)
213
- 2. **Project Name**: `my-backend` (extracted from package.json or directory name)
214
- 3. **Project Path**: `/path/to/my-backend` (resolved to project ID)
215
-
216
- **Typical Workflow:**
243
+ ```
244
+ Dead Code Analysis: 47 items found
245
+ ├── HIGH confidence (23): Exported but never imported
246
+ │ └── formatLegacyDate() in src/utils/date.ts:45
247
+ │ └── UserV1DTO in src/dto/legacy/user.dto.ts:12
248
+ │ └── ... 21 more
249
+ ├── MEDIUM confidence (18): Private, never called
250
+ └── LOW confidence (6): May be used dynamically
251
+ ```
217
252
 
218
- ```typescript
219
- // Step 1: Discover available projects
220
- list_projects()
221
- // Returns: project names, IDs, status, node/edge counts
253
+ ### Duplicate Code Detection
222
254
 
223
- // Step 2: Parse a new project (if not already parsed)
224
- parse_typescript_project({
225
- projectPath: '/path/to/project',
226
- tsconfigPath: '/path/to/project/tsconfig.json'
227
- })
228
- // Returns: projectId for use in queries
255
+ Identify DRY violations across your codebase:
229
256
 
230
- // Step 3: Query the project using any of these ID formats
231
- search_codebase({ projectId: "my-backend", query: "authentication" })
232
- search_codebase({ projectId: "proj_a1b2c3d4e5f6", query: "authentication" })
233
- search_codebase({ projectId: "/path/to/my-backend", query: "authentication" })
234
257
  ```
258
+ Duplicate Groups Found: 8
235
259
 
236
- **Pro Tips:**
237
- - Use project names instead of full IDs for convenience
238
- - Run `list_projects` first to see what's available
239
- - Each project is completely isolated - queries never cross project boundaries
240
-
241
- ### Sequential Workflow Patterns
260
+ Group 1 (Structural - 100% identical):
261
+ ├── validateEmail() in src/auth/validation.ts:23
262
+ └── validateEmail() in src/user/validation.ts:45
263
+ Recommendation: Extract to shared utils
242
264
 
243
- The MCP tools are designed to work together in powerful workflows. Here are the most effective patterns:
244
-
245
- #### Pattern 1: Discovery → Focus → Deep Dive
246
- ```mermaid
247
- graph LR
248
- A[search_codebase] --> B[traverse_from_node] --> C[traverse_from_node with skip]
249
- A --> D[traverse_from_node] --> E[traverse_from_node deeper]
265
+ Group 2 (Semantic - 94% similar):
266
+ ├── parseUserInput() in src/api/parser.ts:78
267
+ └── sanitizeInput() in src/webhook/parser.ts:34
268
+ Recommendation: Review for consolidation
250
269
  ```
251
270
 
252
- #### Pattern 2: Broad Search → Targeted Analysis
253
- 1. **Start Broad**: Use `search_codebase` to find relevant starting points
254
- 2. **Focus**: Use `traverse_from_node` to explore specific relationships
255
- 3. **Paginate**: Use `skip` parameter to explore different sections of the graph
256
-
257
- ### Tool Deep Dive
271
+ ---
258
272
 
259
- #### 1. `search_codebase` - Your Starting Point
260
- Semantic search using vector embeddings. Returns JSON:API normalized response.
273
+ ## Swarm Coordination
274
+
275
+ **Execute complex, multi-file changes with parallel AI agents.**
276
+
277
+ The swarm system enables multiple Claude agents to work on your codebase simultaneously, coordinating through the code graph without stepping on each other.
278
+
279
+ ```
280
+ ┌──────────────────┐
281
+ │ ORCHESTRATOR │
282
+ │ │
283
+ │ "Add JSDoc to │
284
+ │ all services" │
285
+ └────────┬─────────┘
286
+
287
+ ┌─────────────┼─────────────┐
288
+ │ │ │
289
+ ▼ ▼ ▼
290
+ ┌──────────┐ ┌──────────┐ ┌──────────┐
291
+ │ Worker 1 │ │ Worker 2 │ │ Worker 3 │
292
+ │ │ │ │ │ │
293
+ │ Claiming │ │ Working │ │ Claiming │
294
+ │ AuthSvc │ │ UserSvc │ │ PaySvc │
295
+ └──────────┘ └──────────┘ └──────────┘
296
+ │ │ │
297
+ └─────────────┼─────────────┘
298
+
299
+
300
+ ┌─────────────────────────────┐
301
+ │ PHEROMONE TRAILS │
302
+ │ │
303
+ │ AuthService: [claimed] │
304
+ │ UserService: [modifying] │
305
+ │ PayService: [claimed] │
306
+ │ CacheService: [available] │
307
+ │ │
308
+ └─────────────────────────────┘
309
+ ```
310
+
311
+ ### Two Coordination Mechanisms
312
+
313
+ #### 1. Pheromone System (Stigmergic)
314
+
315
+ Agents leave markers on code nodes that decay over time—like ants leaving scent trails:
316
+
317
+ | Pheromone | Half-Life | Meaning |
318
+ |-----------|-----------|---------|
319
+ | `exploring` | 2 min | "I'm looking at this" |
320
+ | `claiming` | 1 hour | "This is my territory" |
321
+ | `modifying` | 10 min | "I'm actively changing this" |
322
+ | `completed` | 24 hours | "I finished work here" |
323
+ | `warning` | Never | "Don't touch this" |
324
+ | `blocked` | 5 min | "I'm stuck" |
325
+
326
+ **Self-healing**: If an agent crashes, its pheromones decay and the work becomes available again.
327
+
328
+ #### 2. Task Queue (Blackboard)
329
+
330
+ Explicit task management with dependencies:
331
+
332
+ ```
333
+ ┌─────────────────────────────────────────────────────────────┐
334
+ │ TASK QUEUE │
335
+ ├─────────────────────────────────────────────────────────────┤
336
+ │ [available] Add JSDoc to UserService priority: high │
337
+ │ [claimed] Add JSDoc to AuthService agent: worker1 │
338
+ │ [blocked] Update API docs ─────────────────► depends on ──┤
339
+ │ [in_progress] Add JSDoc to PaymentService agent: worker2 │
340
+ │ [completed] Add JSDoc to CacheService ✓ │
341
+ └─────────────────────────────────────────────────────────────┘
342
+ ```
343
+
344
+ ### Swarm Tools
345
+
346
+ | Tool | Purpose |
347
+ |------|---------|
348
+ | `swarm_orchestrate` | Decompose a task and spawn worker agents |
349
+ | `swarm_post_task` | Add a task to the queue |
350
+ | `swarm_get_tasks` | Query tasks with filters |
351
+ | `swarm_claim_task` | Claim/start/release a task |
352
+ | `swarm_complete_task` | Complete/fail/request review |
353
+ | `swarm_pheromone` | Leave a marker on a code node |
354
+ | `swarm_sense` | Query what other agents are doing |
355
+ | `swarm_cleanup` | Remove pheromones after completion |
356
+
357
+ ### Example: Parallel Refactoring
261
358
 
262
359
  ```typescript
263
- search_codebase({ projectId: "my-backend", query: "JWT token validation" })
264
- ```
360
+ // Orchestrator decomposes and creates tasks
361
+ swarm_orchestrate({
362
+ projectId: "backend",
363
+ task: "Rename getUserById to findUserById across the codebase",
364
+ maxAgents: 3
365
+ })
265
366
 
266
- **Response Structure**:
267
- ```json
367
+ // Returns a plan:
268
368
  {
269
- "projectRoot": "/path/to/project",
270
- "totalConnections": 22,
271
- "uniqueFiles": 5,
272
- "maxDepth": 3,
273
- "startNodeId": "proj_xxx:MethodDeclaration:abc123",
274
- "nodes": {
275
- "proj_xxx:MethodDeclaration:abc123": {
276
- "id": "proj_xxx:MethodDeclaration:abc123",
277
- "type": "HttpEndpoint",
278
- "filePath": "src/auth/auth.controller.ts",
279
- "name": "validate",
280
- "sourceCode": "async validate(payload) {...}",
281
- "hasMore": true,
282
- "truncated": 1250
283
- }
369
+ swarmId: "swarm_abc123",
370
+ plan: {
371
+ totalTasks: 12,
372
+ parallelizable: 8,
373
+ sequential: 4, // These have dependencies
374
+ tasks: [
375
+ { id: "task_1", title: "Update UserService.findUserById", status: "available" },
376
+ { id: "task_2", title: "Update UserController references", status: "blocked", depends: ["task_1"] },
377
+ ...
378
+ ]
284
379
  },
285
- "depths": [
286
- {
287
- "depth": 1,
288
- "count": 8,
289
- "chains": [[{ "type": "HAS_MEMBER", "from": "nodeA", "to": "nodeB" }]],
290
- "hasMore": 3
291
- }
292
- ],
293
- "pagination": { "skip": 0, "limit": 50, "returned": 15, "hasNextPage": false }
380
+ workerInstructions: "..." // Copy-paste to spawn workers
294
381
  }
295
382
  ```
296
383
 
297
- **Tips**: Use specific domain terms. Node IDs from `nodes` map can be used with `traverse_from_node`.
384
+ ### Install the Swarm Skill
298
385
 
299
- #### 2. `traverse_from_node` - Deep Relationship Exploration
300
- Explore connections from a specific node with depth, direction, and relationship filtering.
386
+ For optimal swarm execution, install the included Claude Code skill that teaches agents the coordination protocol:
301
387
 
302
- ```typescript
303
- traverse_from_node({
304
- projectId: "my-backend",
305
- nodeId: "proj_xxx:ClassDeclaration:abc123", // From search results
306
- maxDepth: 3, // 1-10, default 3
307
- direction: "OUTGOING", // "INCOMING", "BOTH" (default)
308
- includeCode: true, // false for structure-only
309
- summaryOnly: false, // true for just file paths and stats
310
- relationshipTypes: ["INJECTS", "USES_REPOSITORY"] // Optional filter
311
- })
388
+ ```bash
389
+ # Copy to your global skills directory
390
+ mkdir -p ~/.claude/skills
391
+ cp -r skills/swarm ~/.claude/skills/
392
+ ```
393
+
394
+ Or for a specific project:
395
+ ```bash
396
+ cp -r skills/swarm .claude/skills/
312
397
  ```
313
398
 
314
- Returns the same JSON:API format as `search_codebase`.
399
+ The skill provides:
400
+ - Worker agent protocol with step-by-step workflow
401
+ - Multi-phase orchestration patterns (discovery, contracts, implementation, validation)
402
+ - Common failure modes and how to prevent them
403
+ - Complete tool reference
315
404
 
316
- #### 3. `parse_typescript_project` - Graph Generation
317
- **Purpose**: Parse a TypeScript/NestJS project and build the graph database.
405
+ Once installed, just say "swarm" or "parallel agents" and Claude will use the skill automatically.
318
406
 
319
- **Parameters:**
320
- | Parameter | Type | Default | Description |
321
- |-----------|------|---------|-------------|
322
- | `projectPath` | string | required | Path to project root directory |
323
- | `tsconfigPath` | string | required | Path to tsconfig.json |
324
- | `projectId` | string | auto | Override auto-generated project ID |
325
- | `clearExisting` | boolean | true | Clear existing data (false = incremental) |
326
- | `async` | boolean | false | Run in background Worker thread |
327
- | `useStreaming` | enum | "auto" | "auto", "always", or "never" |
328
- | `chunkSize` | number | 50 | Files per chunk for streaming |
329
- | `projectType` | enum | "auto" | "auto", "nestjs", "vanilla" |
330
- | `watch` | boolean | false | Start file watching after parse (requires `async: false`) |
331
- | `watchDebounceMs` | number | 1000 | Debounce delay for watch mode in ms |
407
+ See [`skills/swarm/SKILL.md`](skills/swarm/SKILL.md) for the full documentation.
332
408
 
333
- ```typescript
334
- // Standard parsing (blocking)
335
- await mcp.call('parse_typescript_project', {
336
- projectPath: '/path/to/project',
337
- tsconfigPath: '/path/to/project/tsconfig.json'
338
- });
339
- // Returns: projectId for use in queries
340
-
341
- // Async parsing for large projects (non-blocking)
342
- await mcp.call('parse_typescript_project', {
343
- projectPath: '/path/to/large-project',
344
- tsconfigPath: '/path/to/large-project/tsconfig.json',
345
- async: true // Returns immediately with job ID
346
- });
347
- // Returns: "Job ID: job_abc123... Use check_parse_status to monitor."
348
-
349
- // Check async job progress
350
- await mcp.call('check_parse_status', { jobId: 'job_abc123' });
351
- // Returns: progress %, phase, nodes/edges imported
352
-
353
- // Incremental parsing (only changed files)
354
- await mcp.call('parse_typescript_project', {
355
- projectPath: '/path/to/project',
356
- tsconfigPath: '/path/to/project/tsconfig.json',
357
- clearExisting: false // Keep existing, only reparse changed files
358
- });
359
-
360
- // Parse and start file watching
361
- await mcp.call('parse_typescript_project', {
362
- projectPath: '/path/to/project',
363
- tsconfigPath: '/path/to/project/tsconfig.json',
364
- watch: true, // Start watching after parse completes
365
- watchDebounceMs: 1000 // Wait 1s after last change before updating
366
- });
367
- // File changes now automatically trigger incremental graph updates
368
- ```
369
-
370
- **Modes:**
371
- - **Standard**: Blocks until complete, best for small-medium projects
372
- - **Async**: Returns immediately, use `check_parse_status` to monitor
373
- - **Streaming**: Auto-enabled for projects >100 files, prevents OOM
374
- - **Incremental**: Set `clearExisting: false` to only reparse changed files
375
- - **Watch**: Set `watch: true` to automatically update graph on file changes (requires sync mode)
376
-
377
- **Performance Notes**:
378
- - Large projects (>1000 files) should use `async: true`
379
- - Streaming is auto-enabled for projects >100 files
380
- - Incremental mode detects changes via mtime, size, and content hash
381
- - Worker threads have 30-minute timeout and 8GB heap limit
382
-
383
- #### 4. `test_neo4j_connection` - Health Check
384
- **Purpose**: Verify database connectivity and APOC plugin availability.
409
+ ---
385
410
 
386
- ```typescript
387
- // Simple health check
388
- await mcp.call('test_neo4j_connection');
411
+ ## All Tools
389
412
 
390
- // Response indicates database status
391
- "Neo4j connected: Connected! at 2025-07-25T19:48:42.676Z
392
- APOC plugin available with 438 functions"
393
- ```
413
+ | Tool | Description |
414
+ |------|-------------|
415
+ | **Discovery** | |
416
+ | `list_projects` | List parsed projects in the database |
417
+ | `search_codebase` | Semantic search using vector embeddings |
418
+ | `traverse_from_node` | Explore relationships from a node |
419
+ | `natural_language_to_cypher` | Convert questions to Cypher queries |
420
+ | **Analysis** | |
421
+ | `impact_analysis` | Assess refactoring risk (LOW/MEDIUM/HIGH/CRITICAL) |
422
+ | `detect_dead_code` | Find unreferenced exports and methods |
423
+ | `detect_duplicate_code` | Find structural and semantic duplicates |
424
+ | **Parsing** | |
425
+ | `parse_typescript_project` | Build the graph from source |
426
+ | `check_parse_status` | Monitor async parsing jobs |
427
+ | `start_watch_project` | Auto-update graph on file changes |
428
+ | `stop_watch_project` | Stop file watching |
429
+ | `list_watchers` | List active file watchers |
430
+ | **Swarm** | |
431
+ | `swarm_orchestrate` | Plan and spawn parallel agents |
432
+ | `swarm_post_task` | Add task to the queue |
433
+ | `swarm_get_tasks` | Query tasks |
434
+ | `swarm_claim_task` | Claim/start/release tasks |
435
+ | `swarm_complete_task` | Complete/fail/review tasks |
436
+ | `swarm_pheromone` | Leave coordination markers |
437
+ | `swarm_sense` | Query what others are doing |
438
+ | `swarm_cleanup` | Clean up after swarm completion |
439
+ | **Utility** | |
440
+ | `test_neo4j_connection` | Verify database connectivity |
394
441
 
395
- #### 5. `detect_dead_code` - Code Cleanup Analysis
396
- Find unreferenced exports, uncalled private methods, and unused interfaces.
442
+ ### Tool Workflow Patterns
397
443
 
398
- ```typescript
399
- detect_dead_code({
400
- projectId: 'my-backend',
401
- minConfidence: 'HIGH', // "LOW", "MEDIUM", "HIGH"
402
- excludePatterns: ['*.seed.ts'], // Additional exclusions
403
- summaryOnly: false // true for stats only
404
- })
444
+ **Pattern 1: Discovery → Focus → Deep Dive**
445
+ ```
446
+ list_projects → search_codebase → traverse_from_node → traverse (with skip for pagination)
405
447
  ```
406
448
 
407
- Returns items with `confidence` (HIGH/MEDIUM/LOW), `category` (internal-unused, library-export, ui-component), and `reason`. Automatically excludes NestJS entry points and common patterns.
408
-
409
- #### 6. `detect_duplicate_code` - DRY Violation Detection
410
- Find structural (identical AST) and semantic (similar embeddings) duplicates.
449
+ **Pattern 2: Pre-Refactoring Safety**
450
+ ```
451
+ search_codebase("function to change") impact_analysis(nodeId) review risk level
452
+ ```
411
453
 
412
- ```typescript
413
- detect_duplicate_code({
414
- projectId: 'my-backend',
415
- type: 'all', // "structural", "semantic", "all"
416
- scope: 'methods', // "methods", "functions", "classes", "all"
417
- minSimilarity: 0.85 // 0.5-1.0 threshold
418
- })
454
+ **Pattern 3: Code Health Audit**
455
+ ```
456
+ detect_dead_code → detect_duplicate_code → prioritize cleanup
419
457
  ```
420
458
 
421
- Returns duplicate groups with `similarity` score, `confidence`, `category` (cross-file, same-file, cross-app), and `recommendation`.
459
+ **Pattern 4: Multi-Agent Work**
460
+ ```
461
+ swarm_orchestrate → spawn workers → swarm_get_tasks(includeStats) → swarm_cleanup
462
+ ```
422
463
 
423
- #### 7. File Watching Tools
424
- **Purpose**: Monitor file changes and automatically update the graph.
464
+ ### Multi-Project Support
425
465
 
426
- ```typescript
427
- // Option 1: Start watching during parse
428
- await mcp.call('parse_typescript_project', {
429
- projectPath: '/path/to/project',
430
- tsconfigPath: '/path/to/project/tsconfig.json',
431
- watch: true // Starts watching after parse completes
432
- });
433
-
434
- // Option 2: Start watching a previously parsed project
435
- await mcp.call('start_watch_project', {
436
- projectId: 'my-backend', // Project name, ID, or path
437
- debounceMs: 2000 // Optional: wait 2s after last change (default: 1000)
438
- });
439
-
440
- // List all active watchers
441
- await mcp.call('list_watchers');
442
- // Returns: watcher status, pending changes, last update time
443
-
444
- // Stop watching a project
445
- await mcp.call('stop_watch_project', {
446
- projectId: 'my-backend'
447
- });
448
- ```
449
-
450
- **How It Works:**
451
- 1. File watcher monitors `.ts` and `.tsx` files using native OS events
452
- 2. Changes are debounced to batch rapid edits
453
- 3. Only modified files are re-parsed (incremental)
454
- 4. Cross-file edges are preserved during updates
455
- 5. Graph updates happen automatically in the background
456
-
457
- **Resource Limits:**
458
- - Maximum 10 concurrent watchers
459
- - 1000 pending events per watcher
460
- - Graceful cleanup on server shutdown
461
-
462
- #### 8. Swarm Coordination Tools
463
- **Purpose**: Enable multiple parallel agents to coordinate work through stigmergic pheromone markers in the code graph—no direct messaging needed.
464
-
465
- **Core Concepts:**
466
- - **Pheromones**: Markers attached to graph nodes that decay over time
467
- - **swarmId**: Groups related agents for bulk cleanup when done
468
- - **Workflow States**: `exploring`, `claiming`, `modifying`, `completed`, `blocked` (mutually exclusive per agent+node)
469
- - **Flags**: `warning`, `proposal`, `needs_review` (can coexist with workflow states)
470
-
471
- **Pheromone Types & Decay:**
472
- | Type | Half-Life | Use |
473
- |------|-----------|-----|
474
- | `exploring` | 2 min | Browsing/reading |
475
- | `modifying` | 10 min | Active work |
476
- | `claiming` | 1 hour | Ownership |
477
- | `completed` | 24 hours | Done |
478
- | `warning` | Never | Danger |
479
- | `blocked` | 5 min | Stuck |
480
- | `proposal` | 1 hour | Awaiting approval |
481
- | `needs_review` | 30 min | Review requested |
466
+ All query tools require `projectId` for isolation. You can use:
467
+ - **Project ID**: `proj_a1b2c3d4e5f6` (auto-generated)
468
+ - **Project name**: `my-backend` (from package.json)
469
+ - **Project path**: `/path/to/project` (resolved automatically)
482
470
 
483
471
  ```typescript
484
- // Orchestrator: Generate swarm ID and spawn agents
485
- const swarmId = `swarm_${Date.now()}`;
486
-
487
- // Agent: Check what's claimed before working
488
- await mcp.call('swarm_sense', {
489
- projectId: 'my-backend',
490
- swarmId,
491
- types: ['claiming', 'modifying']
492
- });
493
-
494
- // Agent: Claim a node before working
495
- await mcp.call('swarm_pheromone', {
496
- projectId: 'my-backend',
497
- nodeId: 'proj_xxx:ClassDeclaration:abc123', // From search_codebase or traverse_from_node
498
- type: 'claiming',
499
- agentId: 'agent_1',
500
- swarmId
501
- });
502
-
503
- // Agent: Mark complete when done
504
- await mcp.call('swarm_pheromone', {
505
- projectId: 'my-backend',
506
- nodeId: 'proj_xxx:ClassDeclaration:abc123',
507
- type: 'completed',
508
- agentId: 'agent_1',
509
- swarmId,
510
- data: { summary: 'Added soft delete support' }
511
- });
512
-
513
- // Orchestrator: Clean up when swarm is done
514
- await mcp.call('swarm_cleanup', {
515
- projectId: 'my-backend',
516
- swarmId,
517
- keepTypes: ['warning'] // Preserve warnings
518
- });
519
- ```
520
-
521
- **Important**: Node IDs must come from graph tool responses (`search_codebase`, `traverse_from_node`). Never fabricate node IDs—they are hash-based strings like `proj_xxx:ClassDeclaration:abc123`.
522
-
523
- ### Workflow Example
472
+ // These all work:
473
+ search_codebase({ projectId: "my-backend", query: "auth" })
474
+ search_codebase({ projectId: "proj_a1b2c3d4e5f6", query: "auth" })
475
+ search_codebase({ projectId: "/path/to/my-backend", query: "auth" })
476
+ ```
524
477
 
525
- ```typescript
526
- // 1. Search for relevant code
527
- const result = await search_codebase({
528
- projectId: 'my-backend',
529
- query: 'JWT token validation'
530
- });
531
-
532
- // 2. Get node ID from results and explore relationships
533
- const nodeId = result.startNodeId;
534
- const connections = await traverse_from_node({
535
- projectId: 'my-backend',
536
- nodeId,
537
- maxDepth: 3,
538
- direction: "OUTGOING" // What this depends on
539
- });
540
-
541
- // 3. Assess refactoring impact
542
- const impact = await impact_analysis({
543
- projectId: 'my-backend',
544
- nodeId
545
- });
546
- // Returns: risk level (LOW/MEDIUM/HIGH/CRITICAL), dependents, affected files
547
- ```
548
-
549
- ### Tips for Managing Large Responses
550
- - Set `includeCode: false` for structure-only view
551
- - Set `summaryOnly: true` for just file paths and statistics
552
- - Use `relationshipTypes: ["INJECTS"]` to filter specific relationships
553
- - Use `direction: "OUTGOING"` or `"INCOMING"` to focus exploration
478
+ ---
554
479
 
555
480
  ## Framework Support
556
481
 
557
- ### NestJS Framework Schema
558
-
559
- The server provides deep understanding of NestJS patterns:
560
-
561
- #### Node Types
562
- - **Controllers**: HTTP endpoint handlers with route analysis
563
- - **Services**: Business logic providers with dependency injection mapping
564
- - **Modules**: Application structure with import/export relationships
565
- - **Guards**: Authentication and authorization components
566
- - **Pipes**: Request validation and transformation
567
- - **Interceptors**: Request/response processing middleware
568
- - **DTOs**: Data transfer objects with validation decorators
569
- - **Entities**: Database models with relationship mapping
570
-
571
- #### Relationship Types
572
- - **Module System**: `MODULE_IMPORTS`, `MODULE_PROVIDES`, `MODULE_EXPORTS`
573
- - **Dependency Injection**: `INJECTS`, `PROVIDED_BY`
574
- - **HTTP API**: `EXPOSES`, `ACCEPTS`, `RESPONDS_WITH`
575
- - **Security**: `GUARDED_BY`, `TRANSFORMED_BY`, `INTERCEPTED_BY`
576
-
577
- ### Example Graph Structure
578
-
579
- ```
580
- ┌─────────────────┐ EXPOSES ┌──────────────────┐
581
- │ UserController│──────────────→│ POST /users │
582
- │ @Controller │ │ @Post() │
583
- └─────────────────┘ └──────────────────┘
584
- │ │
585
- INJECTS ACCEPTS
586
- ↓ ↓
587
- ┌─────────────────┐ ┌──────────────────┐
588
- │ UserService │ │ CreateUserDto │
589
- │ @Injectable │ │ @IsString() │
590
- └─────────────────┘ └──────────────────┘
591
-
592
- MANAGES
593
-
594
- ┌─────────────────┐
595
- │ User Entity │
596
- │ @Entity() │
597
- └─────────────────┘
598
- ```
599
-
600
- ## Configuration
482
+ ### NestJS (Built-in)
601
483
 
602
- ### Environment Variables
484
+ Deep understanding of NestJS patterns:
485
+
486
+ - **Controllers** with route analysis (`@Controller`, `@Get`, `@Post`, etc.)
487
+ - **Services** with dependency injection mapping (`@Injectable`)
488
+ - **Modules** with import/export relationships (`@Module`)
489
+ - **Guards, Pipes, Interceptors** as middleware chains
490
+ - **DTOs** with validation decorators (`@IsString`, `@IsEmail`, etc.)
491
+ - **Entities** with TypeORM relationship mapping
603
492
 
604
- | Variable | Description | Default |
605
- |----------|-------------|---------|
606
- | `OPENAI_API_KEY` | OpenAI API key for embeddings and LLM | Required |
607
- | `OPENAI_ASSISTANT_ID` | Reuse existing OpenAI assistant | Optional |
608
- | `NEO4J_URI` | Neo4j database URI | `bolt://localhost:7687` |
609
- | `NEO4J_USER` | Neo4j username | `neo4j` |
610
- | `NEO4J_PASSWORD` | Neo4j password | `PASSWORD` |
611
- | `NEO4J_QUERY_TIMEOUT_MS` | Neo4j query timeout | `30000` (30s) |
612
- | `NEO4J_CONNECTION_TIMEOUT_MS` | Neo4j connection timeout | `10000` (10s) |
613
- | `OPENAI_EMBEDDING_TIMEOUT_MS` | Embedding API timeout | `60000` (60s) |
614
- | `OPENAI_ASSISTANT_TIMEOUT_MS` | Assistant API timeout | `120000` (120s) |
493
+ **NestJS-Specific Relationships:**
494
+ - `INJECTS` - Dependency injection
495
+ - `EXPOSES` - Controller exposes HTTP endpoint
496
+ - `MODULE_IMPORTS`, `MODULE_PROVIDES`, `MODULE_EXPORTS` - Module system
497
+ - `GUARDED_BY`, `TRANSFORMED_BY`, `INTERCEPTED_BY` - Middleware
615
498
 
616
- ### Parse Options
499
+ ### Custom Framework Schemas
617
500
 
618
- Customize parsing behavior:
501
+ The parser is **config-driven**. Define your own framework patterns:
619
502
 
620
503
  ```typescript
621
- const parseOptions = {
622
- includePatterns: ['**/*.ts', '**/*.tsx'],
623
- excludePatterns: [
624
- 'node_modules/',
625
- 'dist/',
626
- 'coverage/',
627
- '.d.ts',
628
- '.spec.ts',
629
- '.test.ts'
504
+ // Example: Custom React schema
505
+ const REACT_SCHEMA = {
506
+ name: 'react',
507
+ decoratorPatterns: [
508
+ { pattern: /^use[A-Z]/, semanticType: 'ReactHook' },
509
+ { pattern: /^with[A-Z]/, semanticType: 'HOC' },
630
510
  ],
631
- maxFiles: 1000,
632
- frameworkSchemas: [NESTJS_FRAMEWORK_SCHEMA]
511
+ nodeTypes: [
512
+ { coreType: 'FunctionDeclaration', condition: (node) => node.name?.endsWith('Provider'), semanticType: 'ContextProvider' },
513
+ ],
514
+ relationships: [
515
+ { type: 'PROVIDES_CONTEXT', from: 'ContextProvider', to: 'ReactHook' },
516
+ ]
633
517
  };
634
518
  ```
635
519
 
636
- ## Limitations
637
-
638
- ### Current Limitations
639
-
640
- 1. **Language Support**: Currently supports TypeScript/NestJS only
641
- 2. **Framework Support**: Primary focus on NestJS patterns (React, Angular, Vue planned)
642
- 3. **File Size**: Large files (>10MB) may cause parsing performance issues
643
- 4. **Memory Usage**: Mitigated by streaming import for large projects
644
- 5. **Vector Search**: Requires OpenAI API for semantic search functionality
645
- 6. **Response Size**: Large graph traversals can exceed token limits (25,000 tokens max)
646
- 7. **Neo4j Memory**: Database memory limits can cause query failures on large graphs
647
-
648
- ### Performance Considerations
520
+ The dual-schema system means every node has:
521
+ - `coreType`: AST-level (ClassDeclaration, FunctionDeclaration)
522
+ - `semanticType`: Framework meaning (NestController, ReactHook)
649
523
 
650
- - **Large Projects**: Use `async: true` for projects with >1000 files
651
- - **Streaming**: Auto-enabled for >100 files to prevent memory issues
652
- - **Graph Traversal**: Deep traversals (>5 levels) may be slow for highly connected graphs
653
- - **Embedding Generation**: Initial parsing with embeddings can take several minutes for large codebases
654
- - **Neo4j Memory**: Recommend at least 4GB RAM allocation for Neo4j with large graphs
655
- - **Worker Timeout**: Async parsing has 30-minute timeout for safety
524
+ This enables queries like "find all hooks that use context" while maintaining AST precision for refactoring.
656
525
 
657
- ### Known Issues
658
-
659
- 1. **Complex Type Inference**: Advanced TypeScript type gymnastics may not be fully captured
660
- 2. **Dynamic Imports**: Runtime module loading not tracked in static analysis
661
- 3. **Decorator Arguments**: Complex decorator argument patterns may not be fully parsed
526
+ ---
662
527
 
663
528
  ## Troubleshooting
664
529
 
665
- ### Common Issues
530
+ ### MCP Server Not Connecting
666
531
 
667
- #### Neo4j Connection Failed
668
532
  ```bash
669
- # Check if Neo4j is running
670
- docker ps | grep neo4j
533
+ # Check the server is registered
534
+ claude mcp list
671
535
 
672
- # Check Neo4j logs
673
- docker logs codebase-neo4j
536
+ # Verify Neo4j is running
537
+ docker ps | grep neo4j
674
538
 
675
- # Verify APOC plugin
676
- curl -u neo4j:PASSWORD http://localhost:7474/db/neo4j/tx/commit \
677
- -H "Content-Type: application/json" \
678
- -d '{"statements":[{"statement":"CALL apoc.help(\"apoc\") YIELD name RETURN count(name) as count"}]}'
539
+ # Test manually
540
+ code-graph-context status
679
541
  ```
680
542
 
681
- #### Neo4j Memory Issues
682
- If you encounter errors like "allocation of an extra X MiB would use more than the limit":
543
+ ### Missing OPENAI_API_KEY
683
544
 
545
+ Symptoms: "Failed to generate embedding" errors
546
+
547
+ Fix: Ensure the key is in your config file:
684
548
  ```bash
685
- # Increase Neo4j memory limits in docker-compose.yml
686
- NEO4J_server_memory_heap_max__size=8G
687
- NEO4J_server_memory_pagecache_size=4G
688
- NEO4J_dbms_memory_transaction_total_max=8G
549
+ # Check current config
550
+ cat ~/.claude.json | grep -A5 "code-graph-context"
689
551
 
690
- # Restart Neo4j
691
- docker-compose restart neo4j
552
+ # Re-add with key
553
+ claude mcp remove code-graph-context
554
+ claude mcp add --scope user code-graph-context \
555
+ -e OPENAI_API_KEY=sk-your-key-here \
556
+ -- code-graph-context
692
557
  ```
693
558
 
694
- #### Token Limit Exceeded
695
- If responses exceed token limits:
696
-
697
- ```typescript
698
- // Reduce depth or use structure-only view
699
- traverse_from_node({ nodeId: "...", maxDepth: 2, includeCode: false })
559
+ ### Neo4j Memory Issues
700
560
 
701
- // Use pagination with skip
702
- traverse_from_node({ nodeId: "...", maxDepth: 2, skip: 0 })
703
- traverse_from_node({ nodeId: "...", maxDepth: 2, skip: 20 })
704
- ```
561
+ For large codebases, increase memory limits:
705
562
 
706
- #### OpenAI API Issues
707
563
  ```bash
708
- # Test API key
709
- curl https://api.openai.com/v1/models \
710
- -H "Authorization: Bearer $OPENAI_API_KEY"
711
-
712
- # Check embedding model availability
713
- curl https://api.openai.com/v1/models/text-embedding-3-large \
714
- -H "Authorization: Bearer $OPENAI_API_KEY"
564
+ # Stop and recreate with more memory
565
+ code-graph-context stop
566
+ code-graph-context init --memory 4G
715
567
  ```
716
568
 
717
- #### Parsing Failures
718
- ```bash
719
- # Check TypeScript configuration
720
- npx tsc --noEmit --project /path/to/tsconfig.json
721
-
722
- # Verify file permissions
723
- ls -la /path/to/project
569
+ ### Parsing Timeouts
724
570
 
725
- # Check memory usage during parsing
726
- node --max-old-space-size=8192 dist/mcp/mcp.server.js
571
+ Use async mode for large projects:
572
+ ```typescript
573
+ parse_typescript_project({
574
+ projectPath: "/path/to/project",
575
+ tsconfigPath: "/path/to/project/tsconfig.json",
576
+ async: true // Returns immediately, poll with check_parse_status
577
+ })
727
578
  ```
728
579
 
729
- ### Debug Mode
580
+ ---
730
581
 
731
- Enable detailed logging:
582
+ ## CLI Commands
732
583
 
733
584
  ```bash
734
- export DEBUG=mcp:*
735
- export NODE_ENV=development
585
+ code-graph-context init [options] # Set up Neo4j container
586
+ code-graph-context status # Check Docker/Neo4j status
587
+ code-graph-context stop # Stop Neo4j container
736
588
  ```
737
589
 
738
- ## Contributing
590
+ **Init options:**
591
+ - `-p, --port <port>` - Bolt port (default: 7687)
592
+ - `--http-port <port>` - Browser port (default: 7474)
593
+ - `--password <password>` - Neo4j password (default: PASSWORD)
594
+ - `-m, --memory <size>` - Heap memory (default: 2G)
595
+ - `-f, --force` - Recreate container
739
596
 
740
- 1. Fork the repository
741
- 2. Create a feature branch: `git checkout -b feature/amazing-feature`
742
- 3. Commit your changes: `git commit -m 'Add amazing feature'`
743
- 4. Push to the branch: `git push origin feature/amazing-feature`
744
- 5. Open a Pull Request
597
+ ---
745
598
 
746
- ### Development Setup
599
+ ## Contributing
747
600
 
748
601
  ```bash
749
- # Install dependencies
602
+ git clone https://github.com/drewdrewH/code-graph-context.git
603
+ cd code-graph-context
750
604
  npm install
751
-
752
- # Run in development mode
753
- npm run dev
754
-
755
- # Run tests
756
- npm test
757
-
758
- # Lint code
759
- npm run lint
760
-
761
- # Format code
762
- npm run format
605
+ npm run build
606
+ npm run dev # Watch mode
763
607
  ```
764
608
 
765
- ## License
609
+ Conventional Commits: `feat|fix|docs|refactor(scope): description`
766
610
 
767
- This project is proprietary software. All rights reserved - see the [LICENSE](LICENSE) file for details.
611
+ ---
768
612
 
769
- ## Acknowledgments
613
+ ## License
770
614
 
771
- - [Model Context Protocol](https://modelcontextprotocol.io/) by Anthropic
772
- - [Neo4j](https://neo4j.com/) for graph database technology
773
- - [ts-morph](https://ts-morph.com/) for TypeScript AST manipulation
774
- - [OpenAI](https://openai.com/) for embeddings and natural language processing
775
- - [NestJS](https://nestjs.com/) for the framework patterns and conventions
615
+ MIT - see [LICENSE](LICENSE)
776
616
 
777
- ## Support
617
+ ---
778
618
 
779
- - Create an [Issue](https://github.com/drewdrewH/code-graph-context/issues) for bug reports or feature requests
780
- - Join the [MCP Discord](https://discord.gg/mcp) for community support
781
- - Check the [MCP Documentation](https://modelcontextprotocol.io/docs) for MCP-specific questions
619
+ ## Links
782
620
 
783
- ---
621
+ - [Issues](https://github.com/drewdrewH/code-graph-context/issues)
622
+ - [MCP Documentation](https://modelcontextprotocol.io/docs)
623
+ - [Neo4j](https://neo4j.com/)