code-graph-context 2.4.4 → 2.5.0

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-v2.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
+ ```
73
107
 
74
- # Set up Neo4j (requires Docker)
75
- code-graph-context init
108
+ ### 2. Configure Claude Code
76
109
 
77
- # Add to Claude Code
78
- claude mcp add code-graph-context code-graph-context
110
+ Add to Claude Code with your OpenAI API key:
111
+
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 `~/.config/claude/config.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,1187 +154,476 @@ Then configure your OpenAI API key in `~/.config/claude/config.json`:
92
154
  }
93
155
  ```
94
156
 
95
- #### Option 2: From Source
96
-
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
103
-
104
- # Set up Neo4j
105
- code-graph-context init
106
-
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
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
+ }
109
170
  ```
110
171
 
111
- ### CLI Commands
172
+ ### Environment Variables
112
173
 
113
- The package includes a CLI for managing Neo4j:
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 |
114
180
 
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
- ```
181
+ ---
120
182
 
121
- **Init options:**
122
- ```
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
128
- ```
183
+ ## Core Capabilities
129
184
 
130
- ### Alternative Neo4j Setup
185
+ ### Semantic Code Search
131
186
 
132
- If you prefer not to use the CLI, you can set up Neo4j manually:
187
+ Find code by describing what you need, not by memorizing file paths:
133
188
 
134
- **Docker Compose:**
135
- ```bash
136
- docker-compose up -d
137
189
  ```
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
190
+ "Find where user authentication tokens are validated"
191
+ "Show me the database connection pooling logic"
192
+ "What handles webhook signature verification?"
147
193
  ```
148
194
 
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.
152
-
153
- ### Verify Installation
195
+ ### Impact Analysis
154
196
 
155
- After installation, verify everything is working:
197
+ Before you refactor, understand the blast radius:
156
198
 
157
- 1. **Check Neo4j is running:**
158
- ```bash
159
- # Open Neo4j Browser
160
- open http://localhost:7474
161
- # Login: neo4j / PASSWORD
162
199
  ```
163
-
164
- 2. **Test APOC plugin:**
165
- ```cypher
166
- CALL apoc.help("apoc")
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
+ └─────────────────────────────────────────────────────────────┘
167
217
  ```
168
- Should return a list of APOC functions.
169
218
 
170
- 3. **Test MCP server connection:**
171
- ```bash
172
- claude mcp list
173
- ```
174
- Should show: `code-graph-context: ✓ Connected`
175
-
176
- ### Troubleshooting
219
+ ### Graph Traversal
177
220
 
178
- **"APOC plugin not found"**
179
- ```bash
180
- # Check Neo4j logs
181
- docker logs code-graph-neo4j
221
+ Explore relationships in any direction:
182
222
 
183
- # Verify APOC loaded
184
- docker exec code-graph-neo4j cypher-shell -u neo4j -p PASSWORD "CALL apoc.help('apoc')"
185
-
186
- # Restart if needed
187
- docker restart code-graph-neo4j
223
+ ```
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
188
237
  ```
189
238
 
190
- **"OPENAI_API_KEY environment variable is required"**
191
- - Get your API key from: https://platform.openai.com/api-keys
192
- - Add to Claude Code MCP config `env` section
193
- - Verify with: `echo $OPENAI_API_KEY` (if using shell env)
194
-
195
- **"Connection refused bolt://localhost:7687"**
196
- ```bash
197
- # Check Neo4j is running
198
- docker ps | grep neo4j
199
-
200
- # Check ports are not in use
201
- lsof -i :7687
239
+ ### Dead Code Detection
202
240
 
203
- # Start Neo4j if stopped
204
- docker start code-graph-neo4j
241
+ Find code that can be safely removed:
205
242
 
206
- # Check Neo4j logs
207
- docker logs code-graph-neo4j
208
243
  ```
209
-
210
- **"Neo4j memory errors"**
211
- ```bash
212
- # Increase memory in docker-compose.yml or docker run:
213
- -e NEO4J_server_memory_heap_max__size=8G
214
- -e NEO4J_dbms_memory_transaction_total_max=8G
215
-
216
- docker restart code-graph-neo4j
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
217
251
  ```
218
252
 
219
- **"MCP server not responding"**
220
- ```bash
221
- # Check Claude Code logs
222
- cat ~/Library/Logs/Claude/mcp*.log
253
+ ### Duplicate Code Detection
223
254
 
224
- # Test server directly
225
- node /path/to/code-graph-context/dist/mcp/mcp.server.js
255
+ Identify DRY violations across your codebase:
226
256
 
227
- # Rebuild if needed
228
- npm run build
229
257
  ```
258
+ Duplicate Groups Found: 8
230
259
 
231
- ## Tool Usage Guide
232
-
233
- ### Available Tools
234
-
235
- | Tool | Description | Best For |
236
- |------|-------------|----------|
237
- | `list_projects` | List all parsed projects in database | **Discovery** - see available projects and their status |
238
- | `search_codebase` | Semantic search using vector embeddings | **Starting point** - find code by describing what you need |
239
- | `traverse_from_node` | Explore relationships from a specific node | **Deep dive** - understand dependencies and connections |
240
- | `impact_analysis` | Analyze what depends on a node | **Pre-refactoring** - assess blast radius (LOW/MEDIUM/HIGH/CRITICAL) |
241
- | `parse_typescript_project` | Parse project and build the graph | **Initial setup** - supports async mode for large projects |
242
- | `check_parse_status` | Monitor async parsing job progress | **Monitoring** - track background parsing jobs |
243
- | `start_watch_project` | Start file watching for a project | **Live updates** - auto-update graph on file changes |
244
- | `stop_watch_project` | Stop file watching for a project | **Resource management** - stop monitoring |
245
- | `list_watchers` | List all active file watchers | **Monitoring** - see what's being watched |
246
- | `natural_language_to_cypher` | Convert natural language to Cypher | **Advanced queries** - complex graph queries |
247
- | `detect_dead_code` | Find unreferenced exports, uncalled methods, unused interfaces | **Code cleanup** - identify potentially removable code |
248
- | `detect_duplicate_code` | Find structural and semantic code duplicates | **Refactoring** - identify DRY violations |
249
- | `swarm_pheromone` | Leave pheromone markers on code nodes | **Multi-agent** - stigmergic coordination |
250
- | `swarm_sense` | Query pheromones in the code graph | **Multi-agent** - sense what other agents are doing |
251
- | `swarm_cleanup` | Bulk delete pheromones | **Multi-agent** - cleanup after swarm completion |
252
- | `test_neo4j_connection` | Verify database connectivity | **Health check** - troubleshooting |
253
-
254
- > **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.
255
-
256
- ### Tool Selection Guide
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
257
264
 
258
- - **`list_projects`**: First step - discover what projects are available
259
- - **`search_codebase`**: Find code by describing what you're looking for
260
- - **`traverse_from_node`**: Use node IDs from search results to explore relationships
261
- - **`impact_analysis`**: Before refactoring - understand what depends on the code you're changing
262
-
263
- ### Multi-Project Workflow
264
-
265
- All query tools require a `projectId` parameter to ensure project isolation. You can provide:
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
269
+ ```
266
270
 
267
- 1. **Project ID**: `proj_a1b2c3d4e5f6` (auto-generated from path)
268
- 2. **Project Name**: `my-backend` (extracted from package.json or directory name)
269
- 3. **Project Path**: `/path/to/my-backend` (resolved to project ID)
271
+ ---
270
272
 
271
- **Typical Workflow:**
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
272
358
 
273
359
  ```typescript
274
- // Step 1: Discover available projects
275
- list_projects()
276
- // Returns: project names, IDs, status, node/edge counts
277
-
278
- // Step 2: Parse a new project (if not already parsed)
279
- parse_typescript_project({
280
- projectPath: '/path/to/project',
281
- tsconfigPath: '/path/to/project/tsconfig.json'
360
+ // Orchestrator decomposes and creates tasks
361
+ swarm_orchestrate({
362
+ projectId: "backend",
363
+ task: "Rename getUserById to findUserById across the codebase",
364
+ maxAgents: 3
282
365
  })
283
- // Returns: projectId for use in queries
284
-
285
- // Step 3: Query the project using any of these ID formats
286
- search_codebase({ projectId: "my-backend", query: "authentication" })
287
- search_codebase({ projectId: "proj_a1b2c3d4e5f6", query: "authentication" })
288
- search_codebase({ projectId: "/path/to/my-backend", query: "authentication" })
289
- ```
290
-
291
- **Pro Tips:**
292
- - Use project names instead of full IDs for convenience
293
- - Run `list_projects` first to see what's available
294
- - Each project is completely isolated - queries never cross project boundaries
295
-
296
- ### Sequential Workflow Patterns
297
-
298
- The MCP tools are designed to work together in powerful workflows. Here are the most effective patterns:
299
-
300
- #### Pattern 1: Discovery → Focus → Deep Dive
301
- ```mermaid
302
- graph LR
303
- A[search_codebase] --> B[traverse_from_node] --> C[traverse_from_node with skip]
304
- A --> D[traverse_from_node] --> E[traverse_from_node deeper]
305
- ```
306
-
307
- #### Pattern 2: Broad Search → Targeted Analysis
308
- 1. **Start Broad**: Use `search_codebase` to find relevant starting points
309
- 2. **Focus**: Use `traverse_from_node` to explore specific relationships
310
- 3. **Paginate**: Use `skip` parameter to explore different sections of the graph
311
366
 
312
- ### Tool Deep Dive
313
-
314
- #### 1. `search_codebase` - Your Starting Point
315
- **Purpose**: Semantic search using vector embeddings to find the most relevant code nodes.
316
-
317
- **Response Structure**: Returns normalized JSON using JSON:API pattern to eliminate duplication:
318
- - **nodes**: Map of unique nodes (stored once, referenced by ID)
319
- - **depths**: Array of depth levels with relationship chains
320
- - **Source Code**: Included by default (truncated to 1000 chars: first 500 + last 500)
321
- - **Statistics**: Total connections, unique files, max depth
322
-
323
- **Real Response Example**:
324
- ```json
325
- // Query: "JWT token validation"
326
- // Returns:
367
+ // Returns a plan:
327
368
  {
328
- "totalConnections": 22,
329
- "uniqueFiles": 2,
330
- "maxDepth": 3,
331
- "startNodeId": "MethodDeclaration:697d2c96-1f91-4894-985d-1eece117b72b",
332
- "nodes": {
333
- "MethodDeclaration:697d2c96-1f91-4894-985d-1eece117b72b": {
334
- "id": "MethodDeclaration:697d2c96-1f91-4894-985d-1eece117b72b",
335
- "type": "MethodDeclaration",
336
- "filePath": "/packages/jwt-validation/src/lib/jwt.strategy.ts",
337
- "name": "validate",
338
- "sourceCode": "validate(payload: EmJwtPayload): EmJwtPayload {\n ...\n\n... [truncated] ...\n\n return payload;\n}",
339
- "hasMore": true,
340
- "truncated": 1250
341
- },
342
- "ClassDeclaration:abc-123": {
343
- "id": "ClassDeclaration:abc-123",
344
- "type": "Service",
345
- "filePath": "/packages/jwt-validation/src/lib/jwt.strategy.ts",
346
- "name": "JwtStrategy"
347
- }
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
+ ]
348
379
  },
349
- "depths": [
350
- {
351
- "depth": 1,
352
- "count": 8,
353
- "chains": [
354
- {
355
- "via": "HAS_MEMBER",
356
- "direction": "INCOMING",
357
- "count": 1,
358
- "nodeIds": ["ClassDeclaration:abc-123"]
359
- },
360
- {
361
- "via": "HAS_PARAMETER",
362
- "direction": "OUTGOING",
363
- "count": 2,
364
- "nodeIds": ["Parameter:xyz-456", "Parameter:def-789"]
365
- }
366
- ]
367
- },
368
- {
369
- "depth": 2,
370
- "count": 14,
371
- "chains": [
372
- {
373
- "via": "HAS_MEMBER → INJECTS",
374
- "direction": "INCOMING",
375
- "count": 3,
376
- "nodeIds": ["Service:auth-service", "Service:user-service", "Repository:user-repo"],
377
- "hasMore": 2
378
- }
379
- ]
380
- }
381
- ]
380
+ workerInstructions: "..." // Copy-paste to spawn workers
382
381
  }
383
382
  ```
384
383
 
385
- **Key Features**:
386
- - **JSON:API Normalization**: Nodes stored once in `nodes` map, referenced by ID to eliminate duplication
387
- - **Source Code Truncation**: Max 1000 chars per snippet (first 500 + last 500 chars)
388
- - **Relationship Chains**: Shows full path like "HAS_MEMBER → INJECTS → USES_REPOSITORY"
389
- - **Direction Indicators**: OUTGOING (what this calls), INCOMING (who calls this)
390
-
391
- **Pro Tips**:
392
- - Use specific domain terms: "JWT token validation" vs "authentication"
393
- - Start with limit=1-3 for initial exploration to avoid token limits
394
- - Look for node IDs in `nodes` map to use with `traverse_from_node`
395
- - Check `truncated` field to see how many bytes were hidden from source code
384
+ ### Install the Swarm Skill
396
385
 
397
- #### 2. `traverse_from_node` - Deep Relationship Exploration
398
- **Purpose**: Explore all connections from a specific node with precise control over depth and pagination.
386
+ For optimal swarm execution, install the included Claude Code skill that teaches agents the coordination protocol:
399
387
 
400
- **Response Structure**: Identical JSON:API format to search_codebase:
401
- - **Focused Traversal**: Starts from your specified node
402
- - **Depth Control**: Configurable max depth (1-10, default 3)
403
- - **Pagination**: Skip parameter for exploring large graphs in chunks
404
- - **Source Code Included by Default**: Set `includeCode: false` for structure-only view
405
-
406
- **Real Response Example**:
407
- ```json
408
- // Starting from a Service class
409
- // maxDepth: 2, skip: 0, includeCode: true
410
- {
411
- "totalConnections": 15,
412
- "uniqueFiles": 4,
413
- "maxDepth": 2,
414
- "startNodeId": "ClassDeclaration:credit-check-service",
415
- "nodes": {
416
- "ClassDeclaration:credit-check-service": {
417
- "id": "ClassDeclaration:credit-check-service",
418
- "type": "Service",
419
- "filePath": "/src/modules/credit/credit-check.service.ts",
420
- "name": "CreditCheckService",
421
- "sourceCode": "@Injectable([CreditCheckRepository, OscilarClient])\nexport class CreditCheckService {\n ...\n\n... [truncated] ...\n\n}",
422
- "truncated": 3200
423
- },
424
- "Repository:credit-check-repo": {
425
- "id": "Repository:credit-check-repo",
426
- "type": "Repository",
427
- "filePath": "/src/modules/credit/credit-check.repository.ts",
428
- "name": "CreditCheckRepository"
429
- }
430
- },
431
- "depths": [
432
- {
433
- "depth": 1,
434
- "count": 5,
435
- "chains": [
436
- {
437
- "via": "INJECTS",
438
- "direction": "OUTGOING",
439
- "count": 2,
440
- "nodeIds": ["Repository:credit-check-repo", "VendorClient:oscilar"]
441
- },
442
- {
443
- "via": "HAS_MEMBER",
444
- "direction": "OUTGOING",
445
- "count": 3,
446
- "nodeIds": ["Method:processCheck", "Method:getResult", "Method:rerun"]
447
- }
448
- ]
449
- },
450
- {
451
- "depth": 2,
452
- "count": 10,
453
- "chains": [
454
- {
455
- "via": "INJECTS → USES_DAL",
456
- "direction": "OUTGOING",
457
- "count": 1,
458
- "nodeIds": ["DAL:application-dal"]
459
- }
460
- ]
461
- }
462
- ]
463
- }
388
+ ```bash
389
+ # Copy to your global skills directory
390
+ mkdir -p ~/.claude/skills
391
+ cp -r skills/swarm ~/.claude/skills/
464
392
  ```
465
393
 
466
- **Parameters**:
467
- - `nodeId` (required): Node ID from search_codebase results
468
- - `maxDepth` (default: 3): Traversal depth (1-10)
469
- - `skip` (default: 0): Pagination offset
470
- - `includeCode` (default: **true**): Include source code snippets
471
- - `summaryOnly` (default: false): Just file paths and statistics
472
- - `direction` (default: BOTH): Filter by OUTGOING/INCOMING/BOTH
473
- - `relationshipTypes` (optional): Filter by specific relationships like ["INJECTS", "USES_REPOSITORY"]
474
-
475
- **Pagination Strategy**:
476
- ```typescript
477
- // Note: Pagination removed in recent commits - all results returned
478
- // Use depth and relationship filtering instead
479
- traverse_from_node({
480
- nodeId,
481
- maxDepth: 2,
482
- relationshipTypes: ["INJECTS"] // Focus on dependency injection only
483
- })
394
+ Or for a specific project:
395
+ ```bash
396
+ cp -r skills/swarm .claude/skills/
484
397
  ```
485
398
 
486
- #### 3. `parse_typescript_project` - Graph Generation
487
- **Purpose**: Parse a TypeScript/NestJS project and build the graph database.
488
-
489
- **Parameters:**
490
- | Parameter | Type | Default | Description |
491
- |-----------|------|---------|-------------|
492
- | `projectPath` | string | required | Path to project root directory |
493
- | `tsconfigPath` | string | required | Path to tsconfig.json |
494
- | `projectId` | string | auto | Override auto-generated project ID |
495
- | `clearExisting` | boolean | true | Clear existing data (false = incremental) |
496
- | `async` | boolean | false | Run in background Worker thread |
497
- | `useStreaming` | enum | "auto" | "auto", "always", or "never" |
498
- | `chunkSize` | number | 50 | Files per chunk for streaming |
499
- | `projectType` | enum | "auto" | "auto", "nestjs", "vanilla" |
500
- | `watch` | boolean | false | Start file watching after parse (requires `async: false`) |
501
- | `watchDebounceMs` | number | 1000 | Debounce delay for watch mode in ms |
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
502
404
 
503
- ```typescript
504
- // Standard parsing (blocking)
505
- await mcp.call('parse_typescript_project', {
506
- projectPath: '/path/to/project',
507
- tsconfigPath: '/path/to/project/tsconfig.json'
508
- });
509
- // Returns: projectId for use in queries
510
-
511
- // Async parsing for large projects (non-blocking)
512
- await mcp.call('parse_typescript_project', {
513
- projectPath: '/path/to/large-project',
514
- tsconfigPath: '/path/to/large-project/tsconfig.json',
515
- async: true // Returns immediately with job ID
516
- });
517
- // Returns: "Job ID: job_abc123... Use check_parse_status to monitor."
518
-
519
- // Check async job progress
520
- await mcp.call('check_parse_status', { jobId: 'job_abc123' });
521
- // Returns: progress %, phase, nodes/edges imported
522
-
523
- // Incremental parsing (only changed files)
524
- await mcp.call('parse_typescript_project', {
525
- projectPath: '/path/to/project',
526
- tsconfigPath: '/path/to/project/tsconfig.json',
527
- clearExisting: false // Keep existing, only reparse changed files
528
- });
529
-
530
- // Parse and start file watching
531
- await mcp.call('parse_typescript_project', {
532
- projectPath: '/path/to/project',
533
- tsconfigPath: '/path/to/project/tsconfig.json',
534
- watch: true, // Start watching after parse completes
535
- watchDebounceMs: 1000 // Wait 1s after last change before updating
536
- });
537
- // File changes now automatically trigger incremental graph updates
538
- ```
405
+ Once installed, just say "swarm" or "parallel agents" and Claude will use the skill automatically.
539
406
 
540
- **Modes:**
541
- - **Standard**: Blocks until complete, best for small-medium projects
542
- - **Async**: Returns immediately, use `check_parse_status` to monitor
543
- - **Streaming**: Auto-enabled for projects >100 files, prevents OOM
544
- - **Incremental**: Set `clearExisting: false` to only reparse changed files
545
- - **Watch**: Set `watch: true` to automatically update graph on file changes (requires sync mode)
407
+ See [`skills/swarm/SKILL.md`](skills/swarm/SKILL.md) for the full documentation.
546
408
 
547
- **Performance Notes**:
548
- - Large projects (>1000 files) should use `async: true`
549
- - Streaming is auto-enabled for projects >100 files
550
- - Incremental mode detects changes via mtime, size, and content hash
551
- - Worker threads have 30-minute timeout and 8GB heap limit
409
+ ---
552
410
 
553
- #### 4. `test_neo4j_connection` - Health Check
554
- **Purpose**: Verify database connectivity and APOC plugin availability.
411
+ ## All Tools
555
412
 
556
- ```typescript
557
- // Simple health check
558
- await mcp.call('test_neo4j_connection');
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 |
559
441
 
560
- // Response indicates database status
561
- "Neo4j connected: Connected! at 2025-07-25T19:48:42.676Z
562
- APOC plugin available with 438 functions"
563
- ```
442
+ ### Tool Workflow Patterns
564
443
 
565
- #### 5. `detect_dead_code` - Code Cleanup Analysis
566
- **Purpose**: Identify potentially dead code including unreferenced exports, uncalled private methods, and unused interfaces.
567
-
568
- **Parameters:**
569
- | Parameter | Type | Default | Description |
570
- |-----------|------|---------|-------------|
571
- | `projectId` | string | required | Project ID, name, or path |
572
- | `excludePatterns` | string[] | [] | Additional file patterns to exclude (e.g., `["*.config.ts"]`) |
573
- | `excludeSemanticTypes` | string[] | [] | Additional semantic types to exclude (e.g., `["EntityClass"]`) |
574
- | `minConfidence` | enum | "LOW" | Minimum confidence: "LOW", "MEDIUM", "HIGH" |
575
- | `summaryOnly` | boolean | false | Return only statistics, not full list |
576
- | `limit` | number | 100 | Maximum items to return |
577
- | `offset` | number | 0 | Pagination offset |
578
-
579
- **Response Structure:**
580
- ```json
581
- {
582
- "summary": "Found 15 potentially dead code items",
583
- "riskLevel": "MEDIUM",
584
- "statistics": {
585
- "total": 15,
586
- "byConfidence": { "HIGH": 5, "MEDIUM": 7, "LOW": 3 },
587
- "byCategory": { "internal-unused": 10, "library-export": 3, "ui-component": 2 },
588
- "byType": { "FunctionDeclaration": 8, "InterfaceDeclaration": 4, "MethodDeclaration": 3 }
589
- },
590
- "deadCode": [
591
- {
592
- "nodeId": "proj_xxx:FunctionDeclaration:abc123",
593
- "name": "unusedHelper",
594
- "type": "FunctionDeclaration",
595
- "filePath": "/src/utils/helpers.ts",
596
- "lineNumber": 42,
597
- "confidence": "HIGH",
598
- "confidenceReason": "Exported but never imported anywhere",
599
- "category": "internal-unused",
600
- "reason": "Exported but never imported or referenced"
601
- }
602
- ]
603
- }
444
+ **Pattern 1: Discovery Focus Deep Dive**
604
445
  ```
605
-
606
- **Framework-Aware Exclusions:**
607
- - Automatically excludes NestJS entry points (controllers, modules, guards, etc.)
608
- - Excludes common entry point files (`main.ts`, `*.module.ts`, `*.controller.ts`)
609
- - Excludes Next.js/React patterns (`page.tsx`, `layout.tsx`, `route.tsx`)
610
-
611
- ```typescript
612
- // Basic usage
613
- await mcp.call('detect_dead_code', {
614
- projectId: 'my-backend'
615
- });
616
-
617
- // High confidence only with custom exclusions
618
- await mcp.call('detect_dead_code', {
619
- projectId: 'my-backend',
620
- minConfidence: 'HIGH',
621
- excludePatterns: ['*.seed.ts', '*.fixture.ts'],
622
- excludeSemanticTypes: ['EntityClass', 'DTOClass']
623
- });
446
+ list_projects → search_codebase → traverse_from_node → traverse (with skip for pagination)
624
447
  ```
625
448
 
626
- #### 6. `detect_duplicate_code` - DRY Violation Detection
627
- **Purpose**: Identify duplicate code using structural (identical AST) and semantic (similar embeddings) analysis.
628
-
629
- **Parameters:**
630
- | Parameter | Type | Default | Description |
631
- |-----------|------|---------|-------------|
632
- | `projectId` | string | required | Project ID, name, or path |
633
- | `type` | enum | "all" | Detection type: "structural", "semantic", "all" |
634
- | `scope` | enum | "all" | Scope: "methods", "functions", "classes", "all" |
635
- | `minSimilarity` | number | 0.8 | Minimum similarity threshold (0.5-1.0) |
636
- | `maxResults` | number | 50 | Maximum duplicate groups to return |
637
- | `includeCode` | boolean | true | Include source code snippets |
638
- | `summaryOnly` | boolean | false | Return only statistics |
639
-
640
- **Response Structure:**
641
- ```json
642
- {
643
- "summary": "Found 8 duplicate code groups across 12 files",
644
- "statistics": {
645
- "totalGroups": 8,
646
- "totalDuplicates": 24,
647
- "byType": {
648
- "structural": { "groups": 3, "items": 9 },
649
- "semantic": { "groups": 5, "items": 15 }
650
- },
651
- "byConfidence": { "HIGH": 4, "MEDIUM": 3, "LOW": 1 }
652
- },
653
- "duplicates": [
654
- {
655
- "groupId": "dup_1",
656
- "type": "structural",
657
- "similarity": 1.0,
658
- "confidence": "HIGH",
659
- "category": "cross-file",
660
- "recommendation": "Extract to shared utility",
661
- "items": [
662
- {
663
- "nodeId": "proj_xxx:MethodDeclaration:abc",
664
- "name": "formatDate",
665
- "filePath": "/src/utils/date.ts",
666
- "lineNumber": 15,
667
- "sourceCode": "formatDate(date: Date): string { ... }"
668
- },
669
- {
670
- "nodeId": "proj_xxx:MethodDeclaration:def",
671
- "name": "formatDate",
672
- "filePath": "/src/helpers/formatting.ts",
673
- "lineNumber": 42,
674
- "sourceCode": "formatDate(date: Date): string { ... }"
675
- }
676
- ]
677
- }
678
- ]
679
- }
449
+ **Pattern 2: Pre-Refactoring Safety**
680
450
  ```
681
-
682
- **Detection Types:**
683
- - **Structural**: Identical normalized code (same AST after removing comments, normalizing names)
684
- - **Semantic**: Similar logic via vector embeddings (requires embeddings enabled during parse)
685
-
686
- **Categories:**
687
- - `ui-component`: Duplicates in UI component directories
688
- - `cross-app`: Duplicates across monorepo apps
689
- - `same-file`: Duplicates within the same file
690
- - `cross-file`: Duplicates across different files
691
-
692
- ```typescript
693
- // Find all duplicates
694
- await mcp.call('detect_duplicate_code', {
695
- projectId: 'my-backend'
696
- });
697
-
698
- // Only structural duplicates in methods
699
- await mcp.call('detect_duplicate_code', {
700
- projectId: 'my-backend',
701
- type: 'structural',
702
- scope: 'methods'
703
- });
704
-
705
- // High similarity semantic duplicates
706
- await mcp.call('detect_duplicate_code', {
707
- projectId: 'my-backend',
708
- type: 'semantic',
709
- minSimilarity: 0.9
710
- });
711
- ```
712
-
713
- #### 7. File Watching Tools
714
- **Purpose**: Monitor file changes and automatically update the graph.
715
-
716
- ```typescript
717
- // Option 1: Start watching during parse
718
- await mcp.call('parse_typescript_project', {
719
- projectPath: '/path/to/project',
720
- tsconfigPath: '/path/to/project/tsconfig.json',
721
- watch: true // Starts watching after parse completes
722
- });
723
-
724
- // Option 2: Start watching a previously parsed project
725
- await mcp.call('start_watch_project', {
726
- projectId: 'my-backend', // Project name, ID, or path
727
- debounceMs: 2000 // Optional: wait 2s after last change (default: 1000)
728
- });
729
-
730
- // List all active watchers
731
- await mcp.call('list_watchers');
732
- // Returns: watcher status, pending changes, last update time
733
-
734
- // Stop watching a project
735
- await mcp.call('stop_watch_project', {
736
- projectId: 'my-backend'
737
- });
738
- ```
739
-
740
- **How It Works:**
741
- 1. File watcher monitors `.ts` and `.tsx` files using native OS events
742
- 2. Changes are debounced to batch rapid edits
743
- 3. Only modified files are re-parsed (incremental)
744
- 4. Cross-file edges are preserved during updates
745
- 5. Graph updates happen automatically in the background
746
-
747
- **Resource Limits:**
748
- - Maximum 10 concurrent watchers
749
- - 1000 pending events per watcher
750
- - Graceful cleanup on server shutdown
751
-
752
- #### 8. Swarm Coordination Tools
753
- **Purpose**: Enable multiple parallel agents to coordinate work through stigmergic pheromone markers in the code graph—no direct messaging needed.
754
-
755
- **Core Concepts:**
756
- - **Pheromones**: Markers attached to graph nodes that decay over time
757
- - **swarmId**: Groups related agents for bulk cleanup when done
758
- - **Workflow States**: `exploring`, `claiming`, `modifying`, `completed`, `blocked` (mutually exclusive per agent+node)
759
- - **Flags**: `warning`, `proposal`, `needs_review` (can coexist with workflow states)
760
-
761
- **Pheromone Types & Decay:**
762
- | Type | Half-Life | Use |
763
- |------|-----------|-----|
764
- | `exploring` | 2 min | Browsing/reading |
765
- | `modifying` | 10 min | Active work |
766
- | `claiming` | 1 hour | Ownership |
767
- | `completed` | 24 hours | Done |
768
- | `warning` | Never | Danger |
769
- | `blocked` | 5 min | Stuck |
770
- | `proposal` | 1 hour | Awaiting approval |
771
- | `needs_review` | 30 min | Review requested |
772
-
773
- ```typescript
774
- // Orchestrator: Generate swarm ID and spawn agents
775
- const swarmId = `swarm_${Date.now()}`;
776
-
777
- // Agent: Check what's claimed before working
778
- await mcp.call('swarm_sense', {
779
- projectId: 'my-backend',
780
- swarmId,
781
- types: ['claiming', 'modifying']
782
- });
783
-
784
- // Agent: Claim a node before working
785
- await mcp.call('swarm_pheromone', {
786
- projectId: 'my-backend',
787
- nodeId: 'proj_xxx:ClassDeclaration:abc123', // From search_codebase or traverse_from_node
788
- type: 'claiming',
789
- agentId: 'agent_1',
790
- swarmId
791
- });
792
-
793
- // Agent: Mark complete when done
794
- await mcp.call('swarm_pheromone', {
795
- projectId: 'my-backend',
796
- nodeId: 'proj_xxx:ClassDeclaration:abc123',
797
- type: 'completed',
798
- agentId: 'agent_1',
799
- swarmId,
800
- data: { summary: 'Added soft delete support' }
801
- });
802
-
803
- // Orchestrator: Clean up when swarm is done
804
- await mcp.call('swarm_cleanup', {
805
- projectId: 'my-backend',
806
- swarmId,
807
- keepTypes: ['warning'] // Preserve warnings
808
- });
451
+ search_codebase("function to change") → impact_analysis(nodeId) → review risk level
809
452
  ```
810
453
 
811
- **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`.
812
-
813
- ### Workflow Examples
814
-
815
- #### Example 1: Understanding Authentication Flow
816
- ```typescript
817
- // Step 1: Find authentication-related code
818
- const searchResult = await mcp.call('search_codebase', {
819
- projectId: 'my-backend', // Required: project name, ID, or path
820
- query: 'JWT token validation authentication'
821
- });
822
-
823
- // Step 2: Extract node ID from most relevant result
824
- const nodeId = "proj_abc123:MethodDeclaration:697d2c96";
825
-
826
- // Step 3: Explore immediate relationships
827
- const immediateConnections = await mcp.call('traverse_from_node', {
828
- projectId: 'my-backend',
829
- nodeId,
830
- maxDepth: 2
831
- });
832
-
833
- // Step 4: Go deeper to understand full authentication chain
834
- const deepConnections = await mcp.call('traverse_from_node', {
835
- projectId: 'my-backend',
836
- nodeId,
837
- maxDepth: 4
838
- });
839
-
840
- // Step 5: Assess refactoring impact
841
- const impact = await mcp.call('impact_analysis', {
842
- projectId: 'my-backend',
843
- nodeId
844
- });
845
- // Returns: risk level (LOW/MEDIUM/HIGH/CRITICAL), dependents, affected files
454
+ **Pattern 3: Code Health Audit**
846
455
  ```
847
-
848
- #### Example 2: API Endpoint Analysis
849
- ```typescript
850
- // Step 1: Search for controller endpoints
851
- const controllerSearch = await mcp.call('search_codebase', {
852
- projectId: 'my-backend',
853
- query: 'HTTP controller endpoints routes POST GET'
854
- });
855
-
856
- // Step 2: Find a controller node ID from results
857
- const controllerNodeId = "proj_abc123:ClassDeclaration:controller-uuid";
858
-
859
- // Step 3: Explore what endpoints this controller exposes
860
- const endpoints = await mcp.call('traverse_from_node', {
861
- projectId: 'my-backend',
862
- nodeId: controllerNodeId,
863
- maxDepth: 2
864
- });
865
-
866
- // Step 4: For each endpoint found, explore its dependencies
867
- const endpointNodeId = "proj_abc123:MethodDeclaration:endpoint-uuid";
868
- const endpointDeps = await mcp.call('traverse_from_node', {
869
- projectId: 'my-backend',
870
- nodeId: endpointNodeId,
871
- maxDepth: 3
872
- });
456
+ detect_dead_code → detect_duplicate_code → prioritize cleanup
873
457
  ```
874
458
 
875
- #### Example 3: Service Dependency Mapping
876
- ```typescript
877
- // Step 1: Find a specific service
878
- const serviceSearch = await mcp.call('search_codebase', {
879
- projectId: 'my-backend',
880
- query: 'UserService injectable dependency injection'
881
- });
882
-
883
- // Step 2: Map all its dependencies (what it injects)
884
- const serviceDeps = await mcp.call('traverse_from_node', {
885
- projectId: 'my-backend',
886
- nodeId: "proj_abc123:ClassDeclaration:user-service-uuid",
887
- maxDepth: 2,
888
- direction: "OUTGOING" // What this service depends on
889
- });
890
-
891
- // Step 3: Impact analysis - what depends on this service
892
- const impact = await mcp.call('impact_analysis', {
893
- projectId: 'my-backend',
894
- nodeId: "proj_abc123:ClassDeclaration:user-service-uuid"
895
- });
896
- // Returns: risk level, all dependents, affected files
459
+ **Pattern 4: Multi-Agent Work**
897
460
  ```
898
-
899
- ### Advanced Usage Tips
900
-
901
- #### Understanding Response Format (JSON:API Normalization)
902
-
903
- **Key Insight**: All responses use JSON:API pattern to eliminate duplication by storing each node once and referencing by ID.
904
-
905
- **How to Read Responses**:
906
- 1. **Start with `nodes` map**: All unique nodes are stored here once
907
- 2. **Look at `depths` array**: Shows how nodes are connected at each depth level
908
- 3. **Follow `nodeIds` references**: Use IDs to look up full node data in `nodes` map
909
- 4. **Check `truncated` field**: Indicates how many bytes of source code were hidden
910
-
911
- **Example Reading Pattern**:
912
- ```typescript
913
- const response = await search_codebase({
914
- projectId: "my-backend",
915
- query: "authentication"
916
- });
917
-
918
- // 1. Get overview statistics
919
- console.log(`Found ${response.totalConnections} connections across ${response.uniqueFiles} files`);
920
-
921
- // 2. Examine the starting node
922
- const startNode = response.nodes[response.startNodeId];
923
- console.log(`Starting from: ${startNode.name} in ${startNode.filePath}`);
924
-
925
- // 3. Explore first depth level
926
- const firstDepth = response.depths[0];
927
- firstDepth.chains.forEach(chain => {
928
- console.log(`Via ${chain.via}: ${chain.count} connections (${chain.direction})`);
929
-
930
- // 4. Look up actual node details
931
- chain.nodeIds.forEach(nodeId => {
932
- const node = response.nodes[nodeId];
933
- console.log(` - ${node.name} (${node.type})`);
934
- });
935
- });
461
+ swarm_orchestrate → spawn workers → swarm_get_tasks(includeStats) → swarm_cleanup
936
462
  ```
937
463
 
938
- #### Managing Large Responses
939
- - **Relationship Filtering**: Use `relationshipTypes` to focus on specific connections
940
- - **Structure-Only View**: Set `includeCode: false` to exclude source code snippets
941
- - **Summary Mode**: Use `summaryOnly: true` for just file paths and statistics
942
-
943
- #### Efficient Graph Exploration
944
- - **Breadth First**: Start with low `maxDepth` (1-2) to get overview
945
- - **Depth Second**: Increase `maxDepth` (3-5) for detailed analysis
946
- - **Direction Filtering**: Use `direction: "OUTGOING"` or `"INCOMING"` to focus exploration
947
- - **Source Code on Demand**: Source code included by default but truncated to 1000 chars
464
+ ### Multi-Project Support
948
465
 
949
- #### Weighted Traversal
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)
950
470
 
951
- 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.
952
-
953
- **How Scoring Works**:
954
-
955
- Each potential path is scored using three factors multiplied together:
956
-
957
- 1. **Edge Weight** (0.0-1.0): How important is this relationship type?
958
- - Critical (0.9-0.95): `INJECTS`, `EXPOSES`, `ROUTES_TO` - core architectural relationships
959
- - High (0.8-0.88): `EXTENDS`, `IMPLEMENTS`, `USES_REPOSITORY` - important semantic links
960
- - Medium (0.5-0.6): `IMPORTS`, `EXPORTS`, `HAS_MEMBER` - structural relationships
961
- - Low (0.3-0.4): `DECORATED_WITH`, `HAS_PARAMETER` - metadata relationships
962
-
963
- 2. **Node Similarity**: Cosine similarity between the node's embedding and your query embedding. Nodes semantically related to your search rank higher.
964
-
965
- 3. **Depth Penalty**: Exponential decay (default 0.85 per level). Closer nodes are preferred:
966
- - Depth 1: 1.0 (no penalty)
967
- - Depth 2: 0.85
968
- - Depth 3: 0.72
969
-
970
- **When to Disable**:
971
471
  ```typescript
972
- // Use standard traversal for exhaustive exploration
973
- search_codebase({
974
- projectId: "my-backend",
975
- query: "...",
976
- useWeightedTraversal: false
977
- })
978
- ```
979
-
980
- #### Performance Optimization
981
- - **Token Efficiency**: JSON:API normalization eliminates duplicate nodes in responses
982
- - **Code Truncation**: Source code limited to 1000 chars (first 500 + last 500) to prevent token overflow
983
- - **Memory**: Large traversals may hit Neo4j memory limits (increase heap size if needed)
984
- - **Caching**: Node IDs are persistent; save interesting ones for later exploration
985
-
986
- ## Claude Code Integration Tips
987
-
988
- ### Guiding Tool Usage with claude.md
989
-
990
- 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:
991
-
992
- #### Trigger Word Hints
993
-
994
- ```markdown
995
- ## Code Search Tools
996
-
997
- **Use `search_codebase` for:**
998
- - "Where is...", "Find...", "Show me [specific thing]"
999
- - Example: "Where is the authentication middleware?"
1000
-
1001
- **Use `natural_language_to_cypher` for:**
1002
- - "List all...", "How many...", "Count..."
1003
- - Example: "List all API controllers"
1004
-
1005
- **Use `traverse_from_node` for:**
1006
- - Deep dependency analysis after initial search
1007
- - "What depends on X?", "Trace the flow..."
1008
- ```
1009
-
1010
- #### Weighted Traversal Hints
1011
-
1012
- ```markdown
1013
- **Use `useWeightedTraversal: true` for:**
1014
- - Service/Controller classes with many dependencies
1015
- - Queries with depth > 3
1016
- - Cleaner, more relevant results
1017
-
1018
- **Recommended settings:**
1019
- - Default: `maxDepth: 5, snippetLength: 900`
1020
- - Simple lookups: `maxDepth: 2`
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" })
1021
476
  ```
1022
477
 
1023
- #### Framework-Specific Patterns
1024
-
1025
- Document your custom node types and relationships so Claude knows what to search for:
1026
-
1027
- ```markdown
1028
- **Custom Node Types:**
1029
- - `PaymentProcessor` - Payment integrations
1030
- - `EmailTemplate` - Email templates
1031
-
1032
- **Custom Relationships:**
1033
- - `PROCESSES_PAYMENT` - Service → PaymentProcessor
1034
- - `SENDS_EMAIL` - Service → EmailTemplate
1035
- ```
1036
-
1037
- #### Common Query Examples
1038
-
1039
- ```markdown
1040
- **Finding authentication:**
1041
- search_codebase({ projectId: "my-project", query: "JWT authentication middleware" })
1042
-
1043
- **Tracing dependencies:**
1044
- traverse_from_node({ projectId: "my-project", nodeId: "...", direction: "OUTGOING", maxDepth: 5 })
1045
-
1046
- **Impact analysis:**
1047
- impact_analysis({ projectId: "my-project", nodeId: "..." })
1048
- ```
478
+ ---
1049
479
 
1050
480
  ## Framework Support
1051
481
 
1052
- ### NestJS Framework Schema
482
+ ### NestJS (Built-in)
1053
483
 
1054
- The server provides deep understanding of NestJS patterns:
484
+ Deep understanding of NestJS patterns:
1055
485
 
1056
- #### Node Types
1057
- - **Controllers**: HTTP endpoint handlers with route analysis
1058
- - **Services**: Business logic providers with dependency injection mapping
1059
- - **Modules**: Application structure with import/export relationships
1060
- - **Guards**: Authentication and authorization components
1061
- - **Pipes**: Request validation and transformation
1062
- - **Interceptors**: Request/response processing middleware
1063
- - **DTOs**: Data transfer objects with validation decorators
1064
- - **Entities**: Database models with relationship mapping
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
1065
492
 
1066
- #### Relationship Types
1067
- - **Module System**: `MODULE_IMPORTS`, `MODULE_PROVIDES`, `MODULE_EXPORTS`
1068
- - **Dependency Injection**: `INJECTS`, `PROVIDED_BY`
1069
- - **HTTP API**: `EXPOSES`, `ACCEPTS`, `RESPONDS_WITH`
1070
- - **Security**: `GUARDED_BY`, `TRANSFORMED_BY`, `INTERCEPTED_BY`
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
1071
498
 
1072
- ### Example Graph Structure
499
+ ### Custom Framework Schemas
1073
500
 
1074
- ```
1075
- ┌─────────────────┐ EXPOSES ┌──────────────────┐
1076
- │ UserController│──────────────→│ POST /users │
1077
- │ @Controller │ │ @Post() │
1078
- └─────────────────┘ └──────────────────┘
1079
- │ │
1080
- INJECTS ACCEPTS
1081
- ↓ ↓
1082
- ┌─────────────────┐ ┌──────────────────┐
1083
- │ UserService │ │ CreateUserDto │
1084
- │ @Injectable │ │ @IsString() │
1085
- └─────────────────┘ └──────────────────┘
1086
-
1087
- MANAGES
1088
-
1089
- ┌─────────────────┐
1090
- │ User Entity │
1091
- │ @Entity() │
1092
- └─────────────────┘
1093
- ```
1094
-
1095
- ## Configuration
1096
-
1097
- ### Environment Variables
1098
-
1099
- | Variable | Description | Default |
1100
- |----------|-------------|---------|
1101
- | `OPENAI_API_KEY` | OpenAI API key for embeddings and LLM | Required |
1102
- | `OPENAI_ASSISTANT_ID` | Reuse existing OpenAI assistant | Optional |
1103
- | `NEO4J_URI` | Neo4j database URI | `bolt://localhost:7687` |
1104
- | `NEO4J_USER` | Neo4j username | `neo4j` |
1105
- | `NEO4J_PASSWORD` | Neo4j password | `PASSWORD` |
1106
- | `NEO4J_QUERY_TIMEOUT_MS` | Neo4j query timeout | `30000` (30s) |
1107
- | `NEO4J_CONNECTION_TIMEOUT_MS` | Neo4j connection timeout | `10000` (10s) |
1108
- | `OPENAI_EMBEDDING_TIMEOUT_MS` | Embedding API timeout | `60000` (60s) |
1109
- | `OPENAI_ASSISTANT_TIMEOUT_MS` | Assistant API timeout | `120000` (120s) |
1110
-
1111
- ### Parse Options
1112
-
1113
- Customize parsing behavior:
501
+ The parser is **config-driven**. Define your own framework patterns:
1114
502
 
1115
503
  ```typescript
1116
- const parseOptions = {
1117
- includePatterns: ['**/*.ts', '**/*.tsx'],
1118
- excludePatterns: [
1119
- 'node_modules/',
1120
- 'dist/',
1121
- 'coverage/',
1122
- '.d.ts',
1123
- '.spec.ts',
1124
- '.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' },
510
+ ],
511
+ nodeTypes: [
512
+ { coreType: 'FunctionDeclaration', condition: (node) => node.name?.endsWith('Provider'), semanticType: 'ContextProvider' },
1125
513
  ],
1126
- maxFiles: 1000,
1127
- frameworkSchemas: [NESTJS_FRAMEWORK_SCHEMA]
514
+ relationships: [
515
+ { type: 'PROVIDES_CONTEXT', from: 'ContextProvider', to: 'ReactHook' },
516
+ ]
1128
517
  };
1129
518
  ```
1130
519
 
1131
- ## Limitations
1132
-
1133
- ### Current Limitations
1134
-
1135
- 1. **Language Support**: Currently supports TypeScript/NestJS only
1136
- 2. **Framework Support**: Primary focus on NestJS patterns (React, Angular, Vue planned)
1137
- 3. **File Size**: Large files (>10MB) may cause parsing performance issues
1138
- 4. **Memory Usage**: Mitigated by streaming import for large projects
1139
- 5. **Vector Search**: Requires OpenAI API for semantic search functionality
1140
- 6. **Response Size**: Large graph traversals can exceed token limits (25,000 tokens max)
1141
- 7. **Neo4j Memory**: Database memory limits can cause query failures on large graphs
520
+ The dual-schema system means every node has:
521
+ - `coreType`: AST-level (ClassDeclaration, FunctionDeclaration)
522
+ - `semanticType`: Framework meaning (NestController, ReactHook)
1142
523
 
1143
- ### Performance Considerations
524
+ This enables queries like "find all hooks that use context" while maintaining AST precision for refactoring.
1144
525
 
1145
- - **Large Projects**: Use `async: true` for projects with >1000 files
1146
- - **Streaming**: Auto-enabled for >100 files to prevent memory issues
1147
- - **Graph Traversal**: Deep traversals (>5 levels) may be slow for highly connected graphs
1148
- - **Embedding Generation**: Initial parsing with embeddings can take several minutes for large codebases
1149
- - **Neo4j Memory**: Recommend at least 4GB RAM allocation for Neo4j with large graphs
1150
- - **Worker Timeout**: Async parsing has 30-minute timeout for safety
1151
-
1152
- ### Known Issues
1153
-
1154
- 1. **Complex Type Inference**: Advanced TypeScript type gymnastics may not be fully captured
1155
- 2. **Dynamic Imports**: Runtime module loading not tracked in static analysis
1156
- 3. **Decorator Arguments**: Complex decorator argument patterns may not be fully parsed
526
+ ---
1157
527
 
1158
528
  ## Troubleshooting
1159
529
 
1160
- ### Common Issues
530
+ ### MCP Server Not Connecting
1161
531
 
1162
- #### Neo4j Connection Failed
1163
532
  ```bash
1164
- # Check if Neo4j is running
1165
- docker ps | grep neo4j
533
+ # Check the server is registered
534
+ claude mcp list
1166
535
 
1167
- # Check Neo4j logs
1168
- docker logs codebase-neo4j
536
+ # Verify Neo4j is running
537
+ docker ps | grep neo4j
1169
538
 
1170
- # Verify APOC plugin
1171
- curl -u neo4j:PASSWORD http://localhost:7474/db/neo4j/tx/commit \
1172
- -H "Content-Type: application/json" \
1173
- -d '{"statements":[{"statement":"CALL apoc.help(\"apoc\") YIELD name RETURN count(name) as count"}]}'
539
+ # Test manually
540
+ code-graph-context status
1174
541
  ```
1175
542
 
1176
- #### Neo4j Memory Issues
1177
- If you encounter errors like "allocation of an extra X MiB would use more than the limit":
543
+ ### Missing OPENAI_API_KEY
544
+
545
+ Symptoms: "Failed to generate embedding" errors
1178
546
 
547
+ Fix: Ensure the key is in your config file:
1179
548
  ```bash
1180
- # Increase Neo4j memory limits in docker-compose.yml
1181
- NEO4J_server_memory_heap_max__size=8G
1182
- NEO4J_server_memory_pagecache_size=4G
1183
- NEO4J_dbms_memory_transaction_total_max=8G
549
+ # Check current config
550
+ cat ~/.claude.json | grep -A5 "code-graph-context"
1184
551
 
1185
- # Restart Neo4j
1186
- 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
1187
557
  ```
1188
558
 
1189
- #### Token Limit Exceeded
1190
- If responses exceed token limits:
559
+ ### Neo4j Memory Issues
1191
560
 
1192
- ```typescript
1193
- // Reduce depth or use structure-only view
1194
- traverse_from_node({ nodeId: "...", maxDepth: 2, includeCode: false })
1195
-
1196
- // Use pagination with skip
1197
- traverse_from_node({ nodeId: "...", maxDepth: 2, skip: 0 })
1198
- traverse_from_node({ nodeId: "...", maxDepth: 2, skip: 20 })
1199
- ```
561
+ For large codebases, increase memory limits:
1200
562
 
1201
- #### OpenAI API Issues
1202
563
  ```bash
1203
- # Test API key
1204
- curl https://api.openai.com/v1/models \
1205
- -H "Authorization: Bearer $OPENAI_API_KEY"
1206
-
1207
- # Check embedding model availability
1208
- curl https://api.openai.com/v1/models/text-embedding-3-large \
1209
- -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
1210
567
  ```
1211
568
 
1212
- #### Parsing Failures
1213
- ```bash
1214
- # Check TypeScript configuration
1215
- npx tsc --noEmit --project /path/to/tsconfig.json
1216
-
1217
- # Verify file permissions
1218
- ls -la /path/to/project
569
+ ### Parsing Timeouts
1219
570
 
1220
- # Check memory usage during parsing
1221
- 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
+ })
1222
578
  ```
1223
579
 
1224
- ### Debug Mode
580
+ ---
1225
581
 
1226
- Enable detailed logging:
582
+ ## CLI Commands
1227
583
 
1228
584
  ```bash
1229
- export DEBUG=mcp:*
1230
- 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
1231
588
  ```
1232
589
 
1233
- ## 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
1234
596
 
1235
- 1. Fork the repository
1236
- 2. Create a feature branch: `git checkout -b feature/amazing-feature`
1237
- 3. Commit your changes: `git commit -m 'Add amazing feature'`
1238
- 4. Push to the branch: `git push origin feature/amazing-feature`
1239
- 5. Open a Pull Request
597
+ ---
1240
598
 
1241
- ### Development Setup
599
+ ## Contributing
1242
600
 
1243
601
  ```bash
1244
- # Install dependencies
602
+ git clone https://github.com/drewdrewH/code-graph-context.git
603
+ cd code-graph-context
1245
604
  npm install
605
+ npm run build
606
+ npm run dev # Watch mode
607
+ ```
1246
608
 
1247
- # Run in development mode
1248
- npm run dev
1249
-
1250
- # Run tests
1251
- npm test
1252
-
1253
- # Lint code
1254
- npm run lint
609
+ Conventional Commits: `feat|fix|docs|refactor(scope): description`
1255
610
 
1256
- # Format code
1257
- npm run format
1258
- ```
611
+ ---
1259
612
 
1260
613
  ## License
1261
614
 
1262
- This project is proprietary software. All rights reserved - see the [LICENSE](LICENSE) file for details.
1263
-
1264
- ## Acknowledgments
615
+ MIT - see [LICENSE](LICENSE)
1265
616
 
1266
- - [Model Context Protocol](https://modelcontextprotocol.io/) by Anthropic
1267
- - [Neo4j](https://neo4j.com/) for graph database technology
1268
- - [ts-morph](https://ts-morph.com/) for TypeScript AST manipulation
1269
- - [OpenAI](https://openai.com/) for embeddings and natural language processing
1270
- - [NestJS](https://nestjs.com/) for the framework patterns and conventions
617
+ ---
1271
618
 
1272
- ## Support
619
+ ## Documentation
1273
620
 
1274
- - Create an [Issue](https://github.com/drewdrewH/code-graph-context/issues) for bug reports or feature requests
1275
- - Join the [MCP Discord](https://discord.gg/mcp) for community support
1276
- - Check the [MCP Documentation](https://modelcontextprotocol.io/docs) for MCP-specific questions
621
+ - [Graph + LLM Inference Research](docs/GRAPH_LLM_INFERENCE_RESEARCH.md) - Research on GNN embeddings, Graph Neural Prompting, and inference integration
1277
622
 
1278
623
  ---
624
+
625
+ ## Links
626
+
627
+ - [Issues](https://github.com/drewdrewH/code-graph-context/issues)
628
+ - [MCP Documentation](https://modelcontextprotocol.io/docs)
629
+ - [Neo4j](https://neo4j.com/)