{"id":35365304,"url":"https://github.com/drewdrewh/code-graph-context","last_synced_at":"2026-03-16T08:07:18.787Z","repository":{"id":324175866,"uuid":"1006677850","full_name":"drewdrewH/code-graph-context","owner":"drewdrewH","description":"A Model Context Protocol (MCP) server that builds rich code graphs to provide deep contextual understanding of TypeScript codebases to Large Language Models.","archived":false,"fork":false,"pushed_at":"2026-03-04T22:47:02.000Z","size":1718,"stargazers_count":9,"open_issues_count":1,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-05T04:28:26.323Z","etag":null,"topics":["ai-code-analysis","claude-code","code-graph-rag","developer-tools","graph-database","graphrag","mcp-server","neo4j","nestjs","openai","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/code-graph-context?activeTab=readme","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/drewdrewH.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-06-22T19:21:54.000Z","updated_at":"2026-03-04T22:46:40.000Z","dependencies_parsed_at":"2026-01-09T02:08:56.049Z","dependency_job_id":null,"html_url":"https://github.com/drewdrewH/code-graph-context","commit_stats":null,"previous_names":["drewdrewh/code-graph-context"],"tags_count":23,"template":false,"template_full_name":null,"purl":"pkg:github/drewdrewH/code-graph-context","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drewdrewH%2Fcode-graph-context","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drewdrewH%2Fcode-graph-context/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drewdrewH%2Fcode-graph-context/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drewdrewH%2Fcode-graph-context/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/drewdrewH","download_url":"https://codeload.github.com/drewdrewH/code-graph-context/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drewdrewH%2Fcode-graph-context/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30373514,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-11T06:09:32.197Z","status":"ssl_error","status_checked_at":"2026-03-11T06:09:17.086Z","response_time":84,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-code-analysis","claude-code","code-graph-rag","developer-tools","graph-database","graphrag","mcp-server","neo4j","nestjs","openai","typescript"],"created_at":"2026-01-02T01:49:06.875Z","updated_at":"2026-03-16T08:07:18.780Z","avatar_url":"https://github.com/drewdrewH.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Code Graph Context\n\n[![npm version](https://badge.fury.io/js/code-graph-context.svg)](https://www.npmjs.com/package/code-graph-context)\n[![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.8-007ACC?logo=typescript\u0026logoColor=white)](https://typescriptlang.org/)\n[![Neo4j](https://img.shields.io/badge/Neo4j-5.23+-018bff?logo=neo4j\u0026logoColor=white)](https://neo4j.com/)\n[![NestJS](https://img.shields.io/badge/NestJS-Compatible-E0234E?logo=nestjs\u0026logoColor=white)](https://nestjs.com/)\n[![OpenAI](https://img.shields.io/badge/OpenAI-Optional-412991?logo=openai\u0026logoColor=white)](https://openai.com/)\n[![MCP](https://img.shields.io/badge/MCP-Server-blue)](https://modelcontextprotocol.io/)\n\n**Give your AI coding assistant a photographic memory of your codebase.**\n\nCode 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.\n\n\u003e **Config-Driven \u0026 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.\n\n```\n                    ┌─────────────────────────────────────────────────────────────┐\n                    │                     YOUR CODEBASE                           │\n                    │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │\n                    │  │ Service  │  │Controller│  │  Module  │  │  Entity  │    │\n                    │  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘    │\n                    └───────┼─────────────┼─────────────┼─────────────┼──────────┘\n                            │             │             │             │\n                            ▼             ▼             ▼             ▼\n                    ┌─────────────────────────────────────────────────────────────┐\n                    │                   CODE GRAPH CONTEXT                        │\n                    │                                                             │\n                    │   AST Parser ──► Neo4j Graph ──► Vector Embeddings          │\n                    │   (ts-morph)     (Relationships)  (Local or OpenAI)         │\n                    │                                                             │\n                    └─────────────────────────────────────────────────────────────┘\n                                                │\n                                                ▼\n                    ┌─────────────────────────────────────────────────────────────┐\n                    │                      CLAUDE CODE                            │\n                    │                                                             │\n                    │   \"What services depend on UserService?\"                    │\n                    │   \"What's the blast radius if I change this function?\"      │\n                    │   \"Find all HTTP endpoints that accept a UserDTO\"           │\n                    │   \"Refactor this across all 47 files that use it\"           │\n                    │                                                             │\n                    └─────────────────────────────────────────────────────────────┘\n```\n\n## Why Code Graph Context?\n\n| Without Code Graph | With Code Graph |\n|---|---|\n| Claude reads files one at a time | Claude understands the entire dependency tree |\n| \"What uses this?\" requires manual searching | Instant impact analysis with risk scoring |\n| Refactoring misses edge cases | Graph traversal finds every reference |\n| Large codebases overwhelm context | Semantic search finds exactly what's relevant |\n| Multi-file changes are error-prone | Swarm agents coordinate parallel changes |\n\n## Features\n\n- **Multi-Project Support**: Parse and query multiple projects in a single database with complete isolation\n- **Semantic Search**: Vector-based search using local or OpenAI embeddings to find relevant code\n- **Natural Language Querying**: Convert questions into Cypher queries\n- **Framework-Aware**: Built-in NestJS schema with ability to define custom framework patterns\n- **Weighted Graph Traversal**: Intelligent traversal scoring paths by importance and relevance\n- **Workspace Support**: Auto-detects Nx, Turborepo, pnpm, Yarn, and npm workspaces\n- **Parallel \u0026 Async Parsing**: Multi-threaded parsing with Worker threads for large codebases\n- **Streaming Import**: Chunked processing for projects with 100+ files\n- **Incremental Parsing**: Only reparse changed files\n- **File Watching**: Real-time graph updates on file changes\n- **Impact Analysis**: Assess refactoring risk (LOW/MEDIUM/HIGH/CRITICAL)\n- **Dead Code Detection**: Find unreferenced exports with confidence scoring\n- **Duplicate Detection**: Structural (AST hash) and semantic (embedding similarity) duplicates\n- **Swarm Coordination**: Multi-agent stigmergic coordination with pheromone decay\n\n## Architecture\n\n```\nTypeScript Source → AST Parser (ts-morph) → Neo4j Graph + Vector Embeddings → MCP Tools\n```\n\n**Core Components:**\n- `src/core/parsers/typescript-parser.ts` - AST parsing with ts-morph\n- `src/storage/neo4j/neo4j.service.ts` - Graph storage and queries\n- `src/core/embeddings/embeddings.service.ts` - Embedding service (local sidecar or OpenAI)\n- `src/mcp/mcp.server.ts` - MCP server and tool registration\n\n**Dual-Schema System:**\n- **Core Schema**: AST-level nodes (ClassDeclaration, MethodDeclaration, ImportDeclaration, etc.)\n- **Framework Schema**: Semantic interpretation (NestController, NestService, HttpEndpoint, etc.)\n\nNodes have both `coreType` (AST) and `semanticType` (framework meaning), enabling queries like \"find all controllers\" while maintaining AST precision.\n\n## Quick Start\n\n### Prerequisites\n\n- **Node.js** \u003e= 18\n- **Python** \u003e= 3.10 (for local embeddings)\n- **Docker** (for Neo4j)\n\n\u003e **No API keys required.** Local embeddings work out of the box using a Python sidecar.\n\n### 1. Install\n\n```bash\nnpm install -g code-graph-context\ncode-graph-context init  # Sets up Neo4j + Python sidecar + downloads embedding model\n```\n\nThe `init` command handles everything:\n- Starts a Neo4j container via Docker\n- Creates a Python virtual environment\n- Installs embedding dependencies (PyTorch, sentence-transformers)\n- Downloads the default embedding model (~3GB)\n\n### 2. Configure Claude Code\n\n```bash\nclaude mcp add --scope user code-graph-context -- code-graph-context\n```\n\n**That's it.** No API keys needed. Restart Claude Code and you're ready to go.\n\n\u003e **Want to use OpenAI instead?** See [Embedding Configuration](#embedding-configuration) below.\n\n### 3. Parse Your Project\n\nIn Claude Code, say:\n\u003e \"Parse this project and build the code graph\"\n\nClaude will run `parse_typescript_project` and index your codebase.\n\n---\n\n## Configuration Files\n\nClaude Code stores MCP server configs in JSON files. The location depends on scope:\n\n| Scope | File | Use Case |\n|-------|------|----------|\n| User (global) | `~/.claude.json` | Available in all projects |\n| Project | `.claude.json` in project root | Project-specific config |\n| Local | `.mcp.json` in project root | Git-ignored local overrides |\n\n### Manual Configuration\n\nIf you prefer to edit the config files directly:\n\n**~/.claude.json** (user scope - recommended):\n```json\n{\n  \"mcpServers\": {\n    \"code-graph-context\": {\n      \"command\": \"code-graph-context\"\n    }\n  }\n}\n```\n\n**With OpenAI (optional):**\n```json\n{\n  \"mcpServers\": {\n    \"code-graph-context\": {\n      \"command\": \"code-graph-context\",\n      \"env\": {\n        \"OPENAI_EMBEDDINGS_ENABLED\": \"true\",\n        \"OPENAI_API_KEY\": \"sk-your-key-here\"\n      }\n    }\n  }\n}\n```\n\n**From source installation:**\n```json\n{\n  \"mcpServers\": {\n    \"code-graph-context\": {\n      \"command\": \"node\",\n      \"args\": [\"/absolute/path/to/code-graph-context/dist/cli/cli.js\"]\n    }\n  }\n}\n```\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `NEO4J_URI` | No | `bolt://localhost:7687` | Neo4j connection URI |\n| `NEO4J_USER` | No | `neo4j` | Neo4j username |\n| `NEO4J_PASSWORD` | No | `PASSWORD` | Neo4j password |\n| `EMBEDDING_MODEL` | No | `codesage/codesage-base-v2` | Local embedding model (see [Embedding Configuration](#embedding-configuration)) |\n| `EMBEDDING_BATCH_SIZE` | No | `8` | Texts per embedding batch (lower = less memory, higher = faster) |\n| `EMBEDDING_SIDECAR_PORT` | No | `8787` | Port for local embedding server |\n| `EMBEDDING_DEVICE` | No | auto (`mps`/`cpu`) | Device for embeddings. Auto-detects MPS on Apple Silicon |\n| `EMBEDDING_HALF_PRECISION` | No | `false` | Set `true` for float16 (uses ~0.5x memory) |\n| `OPENAI_EMBEDDINGS_ENABLED` | No | `false` | Set `true` to use OpenAI instead of local embeddings |\n| `OPENAI_API_KEY` | No* | - | Required when `OPENAI_EMBEDDINGS_ENABLED=true`; also enables `natural_language_to_cypher` |\n\n---\n\n## Core Capabilities\n\n### Semantic Code Search\n\nFind code by describing what you need, not by memorizing file paths:\n\n```\n\"Find where user authentication tokens are validated\"\n\"Show me the database connection pooling logic\"\n\"What handles webhook signature verification?\"\n```\n\n### Impact Analysis\n\nBefore you refactor, understand the blast radius:\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Impact Analysis: UserService.findById()                     │\n├─────────────────────────────────────────────────────────────┤\n│ Risk Level: HIGH                                            │\n│                                                             │\n│ Direct Dependents (12):                                     │\n│   └── AuthController.login()                                │\n│   └── ProfileController.getProfile()                        │\n│   └── AdminService.getUserDetails()                         │\n│   └── ... 9 more                                            │\n│                                                             │\n│ Transitive Dependents (34):                                 │\n│   └── 8 controllers, 15 services, 11 tests                  │\n│                                                             │\n│ Affected Files: 23                                          │\n│ Recommendation: Add deprecation warning before changing     │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Graph Traversal\n\nExplore relationships in any direction:\n\n```\nUserController\n    │\n    ├── INJECTS ──► UserService\n    │                   │\n    │                   ├── INJECTS ──► UserRepository\n    │                   │                   │\n    │                   │                   └── MANAGES ──► User (Entity)\n    │                   │\n    │                   └── INJECTS ──► CacheService\n    │\n    └── EXPOSES ──► POST /users\n                        │\n                        └── ACCEPTS ──► CreateUserDTO\n```\n\n### Dead Code Detection\n\nFind code that can be safely removed:\n\n```\nDead Code Analysis: 47 items found\n├── HIGH confidence (23): Exported but never imported\n│   └── formatLegacyDate() in src/utils/date.ts:45\n│   └── UserV1DTO in src/dto/legacy/user.dto.ts:12\n│   └── ... 21 more\n├── MEDIUM confidence (18): Private, never called\n└── LOW confidence (6): May be used dynamically\n```\n\n### Duplicate Code Detection\n\nIdentify DRY violations across your codebase:\n\n```\nDuplicate Groups Found: 8\n\nGroup 1 (Structural - 100% identical):\n├── validateEmail() in src/auth/validation.ts:23\n└── validateEmail() in src/user/validation.ts:45\n    Recommendation: Extract to shared utils\n\nGroup 2 (Semantic - 94% similar):\n├── parseUserInput() in src/api/parser.ts:78\n└── sanitizeInput() in src/webhook/parser.ts:34\n    Recommendation: Review for consolidation\n```\n\n---\n\n## Swarm Coordination\n\n**Execute complex, multi-file changes with parallel AI agents.**\n\nThe swarm system enables multiple Claude agents to work on your codebase simultaneously, coordinating through the code graph without stepping on each other.\n\n```\n                         ┌──────────────────┐\n                         │   ORCHESTRATOR   │\n                         │                  │\n                         │ \"Add JSDoc to    │\n                         │  all services\"   │\n                         └────────┬─────────┘\n                                  │\n                    ┌─────────────┼─────────────┐\n                    │             │             │\n                    ▼             ▼             ▼\n             ┌──────────┐  ┌──────────┐  ┌──────────┐\n             │ Worker 1 │  │ Worker 2 │  │ Worker 3 │\n             │          │  │          │  │          │\n             │ Claiming │  │ Working  │  │ Claiming │\n             │ AuthSvc  │  │ UserSvc  │  │ PaySvc   │\n             └──────────┘  └──────────┘  └──────────┘\n                    │             │             │\n                    └─────────────┼─────────────┘\n                                  │\n                                  ▼\n                    ┌─────────────────────────────┐\n                    │      PHEROMONE TRAILS       │\n                    │                             │\n                    │  AuthService: [claimed]     │\n                    │  UserService: [modifying]   │\n                    │  PayService:  [claimed]     │\n                    │  CacheService: [available]  │\n                    │                             │\n                    └─────────────────────────────┘\n```\n\n### Two Coordination Mechanisms\n\n#### 1. Pheromone System (Stigmergic)\n\nAgents leave markers on code nodes that decay over time—like ants leaving scent trails:\n\n| Pheromone | Half-Life | Meaning |\n|-----------|-----------|---------|\n| `exploring` | 2 min | \"I'm looking at this\" |\n| `claiming` | 1 hour | \"This is my territory\" |\n| `modifying` | 10 min | \"I'm actively changing this\" |\n| `completed` | 24 hours | \"I finished work here\" |\n| `warning` | Never | \"Don't touch this\" |\n| `blocked` | 5 min | \"I'm stuck\" |\n\n**Self-healing**: If an agent crashes, its pheromones decay and the work becomes available again.\n\n#### 2. Task Queue (Blackboard)\n\nExplicit task management with dependencies:\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│                        TASK QUEUE                           │\n├─────────────────────────────────────────────────────────────┤\n│ [available] Add JSDoc to UserService         priority: high │\n│ [claimed]   Add JSDoc to AuthService         agent: worker1 │\n│ [blocked]   Update API docs ─────────────────► depends on ──┤\n│ [in_progress] Add JSDoc to PaymentService    agent: worker2 │\n│ [completed] Add JSDoc to CacheService        ✓              │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Swarm Tools\n\n| Tool | Purpose |\n|------|---------|\n| `swarm_post_task` | Add a task to the queue |\n| `swarm_get_tasks` | Query tasks with filters |\n| `swarm_claim_task` | Claim/start/release a task |\n| `swarm_complete_task` | Complete/fail/request review |\n| `swarm_pheromone` | Leave a marker on a code node |\n| `swarm_sense` | Query what other agents are doing |\n| `swarm_cleanup` | Remove pheromones after completion |\n\n### Example: Parallel Refactoring\n\n```typescript\n// Orchestrator decomposes the task and creates individual work items\nswarm_post_task({\n  projectId: \"backend\",\n  swarmId: \"swarm_rename_user\",\n  title: \"Update UserService.findUserById\",\n  description: \"Rename getUserById to findUserById in UserService\",\n  type: \"refactor\",\n  createdBy: \"orchestrator\"\n})\n\n// Workers claim and execute tasks\nswarm_claim_task({ projectId: \"backend\", swarmId: \"swarm_rename_user\", agentId: \"worker_1\" })\n// ... do work ...\nswarm_complete_task({ taskId: \"task_1\", agentId: \"worker_1\", action: \"complete\", summary: \"Renamed method\" })\n```\n\n### Install the Swarm Skill\n\nFor optimal swarm execution, install the included Claude Code skill that teaches agents the coordination protocol:\n\n```bash\n# Copy to your global skills directory\nmkdir -p ~/.claude/skills\ncp -r skills/swarm ~/.claude/skills/\n```\n\nOr for a specific project:\n```bash\ncp -r skills/swarm .claude/skills/\n```\n\nThe skill provides:\n- Worker agent protocol with step-by-step workflow\n- Multi-phase orchestration patterns (discovery, contracts, implementation, validation)\n- Common failure modes and how to prevent them\n- Complete tool reference\n\nOnce installed, just say \"swarm\" or \"parallel agents\" and Claude will use the skill automatically.\n\nSee [`skills/swarm/SKILL.md`](skills/swarm/SKILL.md) for the full documentation.\n\n---\n\n## All Tools\n\n| Tool | Description |\n|------|-------------|\n| **Discovery** | |\n| `list_projects` | List parsed projects in the database |\n| `search_codebase` | Semantic search using vector embeddings |\n| `traverse_from_node` | Explore relationships from a node |\n| `natural_language_to_cypher` | Convert questions to Cypher queries |\n| **Analysis** | |\n| `impact_analysis` | Assess refactoring risk (LOW/MEDIUM/HIGH/CRITICAL) |\n| `detect_dead_code` | Find unreferenced exports and methods |\n| `detect_duplicate_code` | Find structural and semantic duplicates |\n| **Parsing** | |\n| `parse_typescript_project` | Build the graph from source |\n| `check_parse_status` | Monitor async parsing jobs |\n| `start_watch_project` | Auto-update graph on file changes |\n| `stop_watch_project` | Stop file watching |\n| `list_watchers` | List active file watchers |\n| **Swarm** | |\n| `swarm_post_task` | Add task to the queue |\n| `swarm_get_tasks` | Query tasks |\n| `swarm_claim_task` | Claim/start/release tasks |\n| `swarm_complete_task` | Complete/fail/review tasks |\n| `swarm_pheromone` | Leave coordination markers |\n| `swarm_sense` | Query what others are doing |\n| `swarm_cleanup` | Clean up after swarm completion |\n| **Utility** | |\n| `test_neo4j_connection` | Verify database connectivity |\n\n### Tool Workflow Patterns\n\n**Pattern 1: Discovery → Focus → Deep Dive**\n```\nlist_projects → search_codebase → traverse_from_node → traverse (with skip for pagination)\n```\n\n**Pattern 2: Pre-Refactoring Safety**\n```\nsearch_codebase(\"function to change\") → impact_analysis(nodeId) → review risk level\n```\n\n**Pattern 3: Code Health Audit**\n```\ndetect_dead_code → detect_duplicate_code → prioritize cleanup\n```\n\n**Pattern 4: Multi-Agent Work**\n```\nswarm_post_task → swarm_claim_task → swarm_complete_task → swarm_get_tasks(includeStats) → swarm_cleanup\n```\n\n### Multi-Project Support\n\nAll query tools require `projectId` for isolation. You can use:\n- **Project ID**: `proj_a1b2c3d4e5f6` (auto-generated)\n- **Project name**: `my-backend` (from package.json)\n- **Project path**: `/path/to/project` (resolved automatically)\n\n```typescript\n// These all work:\nsearch_codebase({ projectId: \"my-backend\", query: \"auth\" })\nsearch_codebase({ projectId: \"proj_a1b2c3d4e5f6\", query: \"auth\" })\nsearch_codebase({ projectId: \"/path/to/my-backend\", query: \"auth\" })\n```\n\n---\n\n## Framework Support\n\n### NestJS (Built-in)\n\nDeep understanding of NestJS patterns:\n\n- **Controllers** with route analysis (`@Controller`, `@Get`, `@Post`, etc.)\n- **Services** with dependency injection mapping (`@Injectable`)\n- **Modules** with import/export relationships (`@Module`)\n- **Guards, Pipes, Interceptors** as middleware chains\n- **DTOs** with validation decorators (`@IsString`, `@IsEmail`, etc.)\n- **Entities** with TypeORM relationship mapping\n\n**NestJS-Specific Relationships:**\n- `INJECTS` - Dependency injection\n- `EXPOSES` - Controller exposes HTTP endpoint\n- `MODULE_IMPORTS`, `MODULE_PROVIDES`, `MODULE_EXPORTS` - Module system\n- `GUARDED_BY`, `TRANSFORMED_BY`, `INTERCEPTED_BY` - Middleware\n\n### Custom Framework Schemas\n\nThe parser is **config-driven**. Define your own framework patterns:\n\n```typescript\n// Example: Custom React schema\nconst REACT_SCHEMA = {\n  name: 'react',\n  decoratorPatterns: [\n    { pattern: /^use[A-Z]/, semanticType: 'ReactHook' },\n    { pattern: /^with[A-Z]/, semanticType: 'HOC' },\n  ],\n  nodeTypes: [\n    { coreType: 'FunctionDeclaration', condition: (node) =\u003e node.name?.endsWith('Provider'), semanticType: 'ContextProvider' },\n  ],\n  relationships: [\n    { type: 'PROVIDES_CONTEXT', from: 'ContextProvider', to: 'ReactHook' },\n  ]\n};\n```\n\nThe dual-schema system means every node has:\n- `coreType`: AST-level (ClassDeclaration, FunctionDeclaration)\n- `semanticType`: Framework meaning (NestController, ReactHook)\n\nThis enables queries like \"find all hooks that use context\" while maintaining AST precision for refactoring.\n\n---\n\n## Embedding Configuration\n\nLocal embeddings are the default — **no API key needed**. The Python sidecar starts automatically on first use and runs a local model for high-quality code embeddings.\n\nThe sidecar uses **MPS (Apple Silicon GPU)** when available, falling back to CPU. It auto-shuts down after 3 minutes of inactivity to free memory, and restarts lazily when needed (~15-20s).\n\n\u003e **Device override:** Set `EMBEDDING_DEVICE=cpu` to force CPU if MPS causes issues.\n\u003e\n\u003e **Half precision:** Set `EMBEDDING_HALF_PRECISION=true` to load the model in float16, roughly halving memory usage.\n\n### Available Models\n\nSet via the `EMBEDDING_MODEL` environment variable:\n\n| Model | Dimensions | RAM (fp16) | Quality | Best For |\n|-------|-----------|-----|---------|----------|\n| `codesage/codesage-base-v2` (default) | 1024 | ~700 MB | Best | Default, code-specific encoder, fast |\n| `Qodo/Qodo-Embed-1-1.5B` | 1536 | ~4.5 GB | Great | Machines with 32+ GB RAM |\n| `BAAI/bge-base-en-v1.5` | 768 | ~250 MB | Good | General purpose, low RAM |\n| `sentence-transformers/all-MiniLM-L6-v2` | 384 | ~100 MB | OK | Minimal RAM, fast |\n| `nomic-ai/nomic-embed-text-v1.5` | 768 | ~300 MB | Good | Code + prose mixed |\n| `sentence-transformers/all-mpnet-base-v2` | 768 | ~250 MB | Good | Balanced quality/speed |\n| `BAAI/bge-small-en-v1.5` | 384 | ~65 MB | OK | Smallest footprint |\n\n**Example:** Use a lightweight model on a low-memory machine:\n```bash\nclaude mcp add --scope user code-graph-context \\\n  -e EMBEDDING_MODEL=BAAI/bge-base-en-v1.5 \\\n  -- code-graph-context\n```\n\n### Switching Models\n\n**Switching models requires re-parsing** — vector index dimensions are locked per model. Drop existing indexes first:\n\n```cypher\nDROP INDEX embedded_nodes_idx IF EXISTS;\nDROP INDEX session_notes_idx IF EXISTS;\n```\n\nThen re-parse your project with the new model configured.\n\n### Using OpenAI Instead\n\nIf you prefer OpenAI embeddings (higher quality, requires API key):\n\n```bash\nclaude mcp add --scope user code-graph-context \\\n  -e OPENAI_EMBEDDINGS_ENABLED=true \\\n  -e OPENAI_API_KEY=sk-your-key-here \\\n  -- code-graph-context\n```\n\n---\n\n## Troubleshooting\n\n### MCP Server Not Connecting\n\n```bash\n# Check the server is registered\nclaude mcp list\n\n# Verify Neo4j is running\ndocker ps | grep neo4j\n\n# Test manually\ncode-graph-context status\n```\n\n### Embedding Errors\n\n**\"Failed to generate embedding\"** — The local sidecar may not have started. Check:\n```bash\n# Verify Python deps are installed\ncode-graph-context status\n\n# Re-run init to fix sidecar setup\ncode-graph-context init\n```\n\n**Out of memory (large model on 16GB machine)** — Switch to a lighter model:\n```bash\nclaude mcp add --scope user code-graph-context \\\n  -e EMBEDDING_MODEL=BAAI/bge-base-en-v1.5 \\\n  -- code-graph-context\n```\n\n**Using OpenAI and getting auth errors** — Ensure your key is configured:\n```bash\nclaude mcp remove code-graph-context\nclaude mcp add --scope user code-graph-context \\\n  -e OPENAI_EMBEDDINGS_ENABLED=true \\\n  -e OPENAI_API_KEY=sk-your-key-here \\\n  -- code-graph-context\n```\n\n### Neo4j Memory Issues\n\nFor large codebases, increase memory limits:\n\n```bash\n# Stop and recreate with more memory\ncode-graph-context stop\ncode-graph-context init --memory 4G\n```\n\n### Parsing Timeouts\n\nUse async mode for large projects:\n```typescript\nparse_typescript_project({\n  projectPath: \"/path/to/project\",\n  tsconfigPath: \"/path/to/project/tsconfig.json\",\n  async: true  // Returns immediately, poll with check_parse_status\n})\n```\n\n---\n\n## CLI Commands\n\n```bash\ncode-graph-context init [options]   # Set up Neo4j + Python sidecar + embedding model\ncode-graph-context status           # Check Docker/Neo4j/sidecar status\ncode-graph-context stop             # Stop Neo4j container\n```\n\n**Init options:**\n- `-p, --port \u003cport\u003e` - Bolt port (default: 7687)\n- `--http-port \u003cport\u003e` - Browser port (default: 7474)\n- `--password \u003cpassword\u003e` - Neo4j password (default: PASSWORD)\n- `-m, --memory \u003csize\u003e` - Heap memory (default: 2G)\n- `-f, --force` - Recreate container\n\n---\n\n## Contributing\n\n```bash\ngit clone https://github.com/drewdrewH/code-graph-context.git\ncd code-graph-context\nnpm install\nnpm run build\nnpm run dev  # Watch mode\n```\n\nConventional Commits: `feat|fix|docs|refactor(scope): description`\n\n---\n\n## License\n\nMIT - see [LICENSE](LICENSE)\n\n---\n\n## Links\n\n- [Issues](https://github.com/drewdrewH/code-graph-context/issues)\n- [MCP Documentation](https://modelcontextprotocol.io/docs)\n- [Neo4j](https://neo4j.com/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdrewdrewh%2Fcode-graph-context","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdrewdrewh%2Fcode-graph-context","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdrewdrewh%2Fcode-graph-context/lists"}