# code-graph-context [Health: Active]

**Category:** 💻 Developer Tools  
**Repository:** https://github.com/andrew-hernandez-paragon/code-graph-context  
**GitHub Stars:** 18  
**npm Downloads (last month):** 1404  
**Views:** 1  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/code-graph-context

## Description
MCP server that builds code graphs to provide rich context to LLMs

## Tools
Capabilities this server exposes over MCP:

- **hello** — Checks that the code-graph-context MCP server is running. Diagnostic only.
- **test_neo4j_connection** — Checks that Neo4j is reachable and the APOC plugin is installed. Diagnostic only; use it when other tools fail with connection errors.
- **search_codebase** — Finds code in a parsed codebase from a natural language query, by meaning and by keyword, then follows the best match's callers and dependencies. Start here for any code question: where something is defined, how a feature works, what uses a symbol.

Needs a codebase project (list_projects shows each project's kind). Returns normalized JSON with a nodes map and relationship chains, plus `matches`: every hit in rank order (rank 1 is the traversal's start node) with its id, name, filePath and scores (`fusedScore`, `vectorScore` as Neo4j reports it, `vectorCosine`, `lexicalScore`). Pass a match's id to traverse_from_node (callers with INCOMING, dependencies with OUTGOING), to impact_analysis before changing it, or as aboutNodeIds on session_save. Node ids come only from this tool and traverse_from_node. If output is too large: reduce maxDepth, set includeCode=false, or reduce snippetLength.
- **query_signals** — Answers "what do we know about X?" in one call, with sectioned results from code, notes (memory) and pheromones for one or more projects. Replaces search_codebase + session_recall + swarm_sense when you want all three.

Returns per-source sections (code, notes, pheromones), each ranked by that source's native score. No cross-source fusion: you decide how to weight the sections.

Multi-project: pass projectIds (array) for cross-boundary search. groupBy:'project' pivots the response to project-keyed top-level.

Graceful degradation: if the embedding provider is unavailable, code section returns skipped:'embedding-provider-unavailable'; notes falls back to Cypher-only (no semantic ranking) with skipped:'semantic-ranking-unavailable'; pheromones section is always available.

Sources: code (vector search), notes (vector + Cypher), pheromones (intensity-ranked, query-independent).

Feedback loop: the response includes a queryId. If you cite one or more results in your next response, pass that queryId and the cited result IDs to query_signals_outcome to close the ranking-feedback loop.
- **query_signals_outcome** — Records which results of a query_signals call you cited, so future ranking can improve. Call it after query_signals when you cite one or more results in your response.

Pass the queryId from the query_signals response and an array of cited results (resultId + source + sourceRank). Each citation is persisted as a QueryOutcome node and linked to the underlying cited node via a CITED edge.

Idempotent: calling with the same queryId + resultId twice does not double-record.

citationKind: 'direct' (quoted or closely paraphrased), 'paraphrase' (restated in own words), 'background' (influenced reasoning without explicit citation). Omit if unsure.
- **traverse_from_node** — Shows what calls a code node, what it calls and what it depends on, starting from a node id or a file path. Use it after search_codebase to look at a match other than the best one, or to follow one direction further: INCOMING for callers, OUTGOING for dependencies.

Takes nodeId (from search_codebase results) or filePath. Set summaryOnly=true for file paths and statistics only.
- **natural_language_to_cypher** — Answers aggregate and structural questions about a parsed codebase by generating a Cypher query from your question and running it: counts ('how many services exist'), lists, bulk property filters, complex relationship patterns. Use search_codebase to find code. Requires OPENAI_API_KEY.

The generated query runs in a read-only transaction, so it cannot change the graph.

**Node types:** SourceFile, Class, Function, Method, Interface, Property, Parameter, Import, Export, Enum, TypeAlias
**Key relationships:** CONTAINS, HAS_MEMBER, HAS_PARAMETER, IMPORTS, EXTENDS, IMPLEMENTS, CALLS, TYPED_AS
**NestJS:** Use semanticType property (e.g., semanticType='NestController'). Relationships: INJECTS, EXPOSES, MODULE_IMPORTS/PROVIDES/EXPORTS
**Tips:** Use concrete properties (filePath, name) not abstract concepts.
- **impact_analysis** — Shows what depends on a code node or file, and how far a change would spread, before you modify shared code. Returns a risk level (LOW/MEDIUM/HIGH/CRITICAL), direct and transitive dependents, affected files and critical paths.

Takes nodeId (from search_codebase or traverse_from_node) or filePath, in a parsed codebase. Follows dependents 2 hops from the target by default; pass maxDepth (up to 6) for a deeper search.
- **detect_dead_code** — Finds unused exports, uncalled methods and orphan interfaces in a parsed codebase. Returns items with confidence scores grouped by type and category.

Auto-excludes NestJS entry points. Use filterCategory=internal-unused for actionable cleanup.
- **detect_duplicate_code** — Finds duplicated code in a parsed codebase by structure (AST hash) and by meaning (embeddings). Returns groups of duplicates with similarity scores.
- **parse_typescript_project** — Parses a TypeScript or NestJS repository into the code graph and registers it as a codebase project, so search_codebase, traverse_from_node and impact_analysis work on it. Run once per repository; start_watch_project keeps the graph current afterwards.

A directory project already registered at projectPath becomes the codebase and keeps its memories. Set clearExisting=true to replace an existing graph. Use async=true (the default): it returns a jobId immediately; poll check_parse_status with it.
- **check_parse_status** — Reports the status, progress and final result of a parse started by parse_typescript_project. Pass the jobId that call returned.
- **list_projects** — Lists every project (codebase, directory or collection) with its id, name, kind, path, description, parse status and memory counts (live notes, bookmarks, last save). Use it to find the projectId other tools take, or to see where memories already live. Filter with kinds.
- **create_project** — Creates a place to keep memories (notes and bookmarks) outside a parsed codebase. kind 'directory' registers an existing local directory that is not parsed, such as Terraform, Python or docs (pass path); kind 'collection' creates a named set of memories with no directory (pass name and description). Calling it again for the same directory or collection returns the existing project with created=false. Then pass its id to session_save and session_recall. Parse a TypeScript repository with parse_typescript_project instead.
- **start_watch_project** — Keeps a codebase's graph current by re-parsing .ts files as they change. Needs a codebase parsed with parse_typescript_project. Skips what the parser skips (node_modules, dist, build, coverage, test files) and .git. Stop it with stop_watch_project; list_watchers shows active watchers.
- **stop_watch_project** — Stops watching a codebase for file changes. The graph stays as it was at the last update.
- **list_watchers** — Lists active file watchers started with start_watch_project, with their status and pending changes.
- **ingest_cursordiff_session** — Ingests cursordiff JSONL files (router / lineage / decisions) into the graph.

mode="one-shot": read all rows currently on disk, run idempotent MERGEs, return a summary.
mode="watch":    start a live fs-watcher on the three files; new rows are ingested within ~500ms of write. Returns {watchId, paths, started} immediately. Use stop_ingest_cursordiff_session to stop.

dataDir defaults to ~/.local/share/nvim/cursordiff/.
dryRun=true plans but does not write to Neo4j (useful for smoke-testing fixtures).
tailOnly=true (watch mode only) skips existing rows and only ingests new writes.
- **stop_ingest_cursordiff_session** — Stops a running cursordiff fs-watch session. Provide watchId (from ingest_cursordiff_session) or dataDir. Use list_ingest_cursordiff_watchers to see active sessions.
- **list_ingest_cursordiff_watchers** — Lists all active cursordiff fs-watch sessions. Returns watchId, dataDir, rowsProcessed, lastActivityAt, lastErrorAt, lastError, and isProcessing for each watcher.
- **ingest_deliberate_session** — Ingests deliberation.jsonl (Deliberation / Position / Verdict events) into the graph.

mode="one-shot": read all rows currently on disk, run idempotent MERGEs, return a summary.
mode="watch":    start a live fs-watcher on deliberation.jsonl; new rows are ingested within ~500ms of write. Returns {watchId, paths, started} immediately. Use stop_ingest_deliberate_session to stop.

dataDir defaults to ~/.local/share/nvim/cursordiff/ (same dir as cursordiff JSONLs).
dryRun=true plans but does not write to Neo4j (useful for smoke-testing fixtures).
tailOnly=true (watch mode only) skips existing rows and only ingests new writes.
- **stop_ingest_deliberate_session** — Stops a running deliberate fs-watch session. Provide watchId (from ingest_deliberate_session) or dataDir. Use list_ingest_deliberate_watchers to see active sessions.
- **list_ingest_deliberate_watchers** — Lists all active deliberation fs-watch sessions. Returns watchId, dataDir, rowsProcessed, lastActivityAt, lastErrorAt, lastError, and isProcessing for each watcher.
- **swarm_pheromone** — Marks a code node with a pheromone so other agents see what you are doing to it. Workflow states (exploring/claiming/modifying/completed/blocked) are mutually exclusive per agent+node. Flag types (warning/proposal/needs_review/session_context) can coexist. Pheromones decay automatically; swarm_sense reads them.
- **swarm_sense** — Shows which pheromones other agents have left on code nodes, to see what they are working on. Filter by swarmId, types, nodeIds, agentIds. Returns pheromones with current intensity after decay.
- **swarm_cleanup** — Deletes pheromones, tasks and messages for a swarm or an agent in bulk. Warning pheromones are preserved by default. Use dryRun=true to preview.
- **swarm_post_task** — Adds a task to the swarm queue for another agent to claim with swarm_claim_task. Use the dependencies array for task ordering; tasks with incomplete dependencies block until ready.

Question primitive: post with type='question' to ask a synchronous question that another agent (typically the orchestrator or a domain-expert subagent) must answer before the asker proceeds. Asker polls swarm_get_tasks({ taskId }) every ~10s for up to 5 polls, then either reads the answer (status=completed; answer arrives via swarm_message with category='answer' linked to this taskId) or halts with BLOCKED.md. Set metadata.askerAgentId so the answerer knows where to direct the answer message.
- **swarm_claim_task** — Claims a task from the swarm queue. Without taskId, claims the highest-priority available task. Set startImmediately=false to claim without starting.

Flow: swarm_claim_task → do work → swarm_complete_task. Use swarm_release_task to give up work, swarm_advance_task for state transitions. swarm_post_task adds tasks.
- **swarm_advance_task** — Starts a task you claimed. Use it after swarm_claim_task with startImmediately=false, or set force=true to recover from a stuck claimed state.
- **swarm_release_task** — Releases a task you claimed and can no longer complete, so another agent can claim it. Set trackAbandonment=true to record the abandonment for retry tracking.
- **swarm_complete_task** — Marks a task you claimed as completed or failed, or requests review. Completing unblocks dependent tasks. Failed tasks can be retried if retryable=true.
- **swarm_get_tasks** — Lists swarm tasks. Use taskId for a single task, or filter by swarmId, statuses, types, claimedBy. Add includeStats=true for aggregate counts.

Question polling: pass types=['question'] to find unanswered questions. Askers poll a specific question via taskId until status='completed', then read the linked answer message.
- **swarm_message** — Sends, reads and acknowledges direct messages between agents in a swarm. Unlike pheromones (passive, decay-based), messages are explicit and delivered when agents claim tasks. Use for critical coordination signals.

Actions: send (post or broadcast), read (retrieve), acknowledge (mark read).

Categories (coordination): blocked, conflict, finding, request, alert, handoff, answer.
Categories (consensus dialogue): position, agree, dissent. Generic multi-agent consensus primitives; any protocol that needs N agents to converge on a stance can use them (current primary consumer is the /deliberate skill).

Answer convention: when answering a type='question' task, send with category='answer', toAgentId=<askerAgentId from question metadata>, and taskId=<question taskId>. After sending, the answerer should call swarm_complete_task({ action: 'complete', taskId }) so the asker's poll sees status='completed' and reads the linked answer message.
- **session_save** — Remembers a discovery, decision or risk as a note, or saves your working state as a bookmark, in any project: codebase, directory or collection. The type is detected from the input. A note needs topic, content and category. A bookmark needs summary, taskContext and workingSetNodeIds or workingSetPaths; give both sets of fields to save a bookmark with a note.

Anchor a note to what it is about with aboutNodeIds (ids from search_codebase) or aboutPaths (files and folders); session_recall then reports when an anchor has gone or changed. To replace older notes, pass supersedes with their ids: the new note stays current and each old note is marked superseded by it. A path inside a git repository that is not registered registers that repository as a directory project. Retrieve with session_recall.
- **session_recall** — Recalls saved notes and bookmarks (memory) from one or more projects. Pass query to search notes by meaning; pass sessionId to restore that session's latest bookmark and its notes. Call it before working in an area. projectIds recalls across several projects in one call, such as a repository and a collection. A query can return fewer notes than limit, or none, when nothing is close enough; an empty result means no relevant note, not a broken tool.

Each note reports staleAboutNodeIds, missingAboutPaths and changedAboutPaths when its anchors no longer match the code. Check the code, then fix the note with session_update or replace it with session_save and supersedes. Superseded notes are hidden unless includeSuperseded=true.
- **session_update** — Revises a saved note in place: fix a typo, change severity or category, correct content, replace its aboutNodeIds or aboutPaths, mark it superseded, or move it to another project or collection with moveToProjectId. Every update refreshes the note's lastValidated time. For a substantive change or a reversed decision, use session_save with supersedes: [<oldId>] instead, which keeps the old note as history. Find note ids with session_recall.
- **cleanup_session** — Deletes expired notes and old bookmarks (memory) in a project, keeping the most recent bookmarks per session. Use dryRun=true to preview what would be deleted.

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `npx` (confidence: high):

```json
"mcpServers": {
  "code-graph-context": {
    "command": "npx",
    "args": ["-y","code-graph-context"]
  }
}
```

## Documentation

## What code-graph-context does

code-graph-context indexes TypeScript projects into a Neo4j-backed graph that represents source structure and relationships. It captures AST entities such as classes, methods, imports, and declarations, then adds semantic classifications for supported frameworks. The included framework schema covers NestJS concepts such as controllers, services, and HTTP endpoints; custom schemas can describe other architectural patterns, decorators, and relationships.

The resulting graph is available to coding assistants through MCP. Agents can ask questions about dependencies, references, endpoint inputs, and the likely scope of a change without manually searching each file. Multi-project indexing is supported while keeping project data isolated within the same database.

## How it works

The indexing pipeline parses TypeScript with ts-morph, writes graph relationships to Neo4j, and generates vector embeddings for semantic retrieval. Embeddings can be produced locally through a Python sidecar using the default BGE-base model, or through OpenAI when configured. Natural-language questions can be translated into Cypher queries, while weighted graph traversal ranks paths by relevance and importance.

Parsing supports workspace layouts used by Nx, Turborepo, pnpm, Yarn, and npm. Worker threads enable parallel parsing, streaming import handles larger projects, and incremental parsing limits reprocessing to changed files. File watching can update the graph as files change.

## Setup and configuration

Install the package globally with npm, then run `code-graph-context init`. Initialization prepares Neo4j and the Python embedding sidecar, creates the required virtual environment, installs embedding dependencies, and downloads the default model. On macOS, Neo4j can run through Homebrew; other platforms use Docker, with `--native` and `--docker` available to select a provider. The data location can be changed with `CGC_DATA_DIR`.

The prerequisites are Node.js 18 or newer, Python 3.10 or newer for local embeddings, and either Homebrew on macOS or Docker on other platforms. Add the executable to an MCP client as a stdio server. For Claude Code, the setup command is `claude mcp add --scope user code-graph-context -- code-graph-context`. Projects are indexed by asking the assistant to parse the project; the server invokes `parse_typescript_project` for that operation.

OpenAI embeddings are optional. They use `OPENAI_EMBEDDINGS_ENABLED=true` together with `OPENAI_API_KEY`; local embeddings require neither setting. Neo4j connection settings can also be supplied through the server's environment configuration.

## Tools and capabilities

- Parse and index TypeScript projects into a graph.
- Search code semantically with local or OpenAI embeddings.
- Query relationships using natural-language questions and Cypher generation.
- Traverse dependencies with weighted relevance scoring.
- Analyze refactoring impact with LOW, MEDIUM, HIGH, and CRITICAL risk levels.
- Detect unreferenced exports and structural or semantic duplicates.
- Watch files and incrementally update changed code.
- Coordinate parallel agent work through stigmergic coordination with pheromone decay.

## Limitations and notes

The primary parser targets TypeScript, and framework-specific semantic interpretation depends on the configured schema. Neo4j is required for graph storage. Local embedding setup also requires Python and downloads a model with its dependencies, while the OpenAI path requires an API key. Large repositories may need the streaming and parallel parsing options during initial import.

_Full upstream README: https://allmcps.com/mcp/code-graph-context/readme_

