codebase-memory-mcp
The fastest and most efficient code intelligence engine for AI coding agents. Full-indexes an average repository in milliseconds, the Linux kernel (28M LOC, 75K files) in 3 minutes. Answers structural queries in under 1ms. Ships as a native executable with a small verified runtime-asset set for macOS, Linux, and Windows — download, run install, done.
High-quality parsing through tree-sitter AST analysis across all 162 languages, enhanced with Hybrid LSP semantic type resolution for Python, TypeScript / JavaScript / JSX / TSX, PHP, C#, Go, C, C++, Java, Kotlin, Rust, and Perl — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 15 MCP tools. No language runtime, hosted service, or API key. Plug and play across 45 supported automatic/conditional client surfaces.
Research — The design and benchmarks behind this project are described in the preprint Codebase-Memory: Tree-Sitter-Based Knowledge Graphs for LLM Code Exploration via MCP (arXiv:2603.27277). Evaluated across 31 real-world repositories: 83% answer quality, 10× fewer tokens, 2.1× fewer tool calls vs. file-by-file exploration.
Security & Trust — This tool reads your codebase and writes to your agent configuration files. That is what it is designed to do. If you prefer to audit before running, the full source is here. For each release product, three behaviourally identical executable candidates (unstripped, debug-stripped, stripped) are submitted to VirusTotal before testing; the selected candidate is then packaged with its SHA-256 unchanged. Release notes link every measured candidate result. Publication permits only the narrowly documented single-Microsoft !ml tolerance in SECURITY.md. All processing happens 100% locally; your code never leaves your machine. Found a security issue? We want to know — see SECURITY.md. Security is Priority #1 for us.
Why codebase-memory-mcp
- Extreme indexing speed — Linux kernel (28M LOC, 75K files) in 3 minutes. RAM-first pipeline: LZ4 compression, in-memory SQLite, fused Aho-Corasick pattern matching. Memory released after indexing.
- Plug and play — native executable plus authenticated release-owned assets for macOS (arm64/amd64), Linux (arm64/amd64), and Windows (amd64). The native install needs no Docker, language runtime, or API keys. Download →
install → restart agent → done.
- 162 languages — vendored tree-sitter grammars compiled into the binary. Nothing to install, nothing that breaks.
- 120x fewer tokens — 5 structural queries: ~3,400 tokens vs ~412,000 via file-by-file search. One graph query replaces dozens of grep/read cycles.
- 45 supported automatic/conditional client surfaces —
install configures detected clients and safely activates conditional clients only when their documented platform, marker, or explicit existing config path is present. See Multi-Agent Support for the complete matrix and manual/UI-only boundaries.
- Built-in graph visualization — 3D interactive UI at
localhost:9749, served from the binary itself.
- Infrastructure-as-code indexing — Dockerfiles, Kubernetes manifests, and Kustomize overlays indexed as graph nodes with cross-references.
Resource nodes for K8s kinds, Module nodes for Kustomize overlays with IMPORTS edges to referenced resources.
- 15 MCP tools — search, trace, architecture, impact analysis, targeted index-coverage checks, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.
Features
Graph & analysis
- Architecture overview:
get_architecture returns languages, packages, entry points, routes, hotspots, boundaries, layers, and clusters in a single call
- Architecture Decision Records:
manage_adr persists architectural decisions across sessions
- Louvain community detection: Discovers functional modules by clustering call edges
- Git diff impact mapping:
detect_changes maps uncommitted changes to affected symbols with risk classification
- Call graph: Resolves function calls across files and packages (import-aware, type-inferred)
- Dead code detection: Finds functions with zero callers, excluding entry points
- Cypher-like queries:
MATCH (f:Function)-[:CALLS]->(g) WHERE f.name = 'main' RETURN g.name
Search
- Semantic search (
semantic_query): vector search across the entire graph, powered by bundled Nomic nomic-embed-code embeddings (40K tokens, 768d int8) compiled into the binary — no API key, no Ollama, no Docker. 11-signal combined scoring (TF-IDF, RRI, API/Type/Decorator signatures, AST profiles, data flow, Halstead-lite, MinHash, module proximity, graph diffusion).
- BM25 full-text search via SQLite FTS5 with
cbm_camel_split tokenizer (camelCase / snake_case aware)
- Structural search (
search_graph): regex name patterns, label filters, min/max degree, file scoping
- Code search (
search_code): graph-augmented grep over indexed files only
Cross-service linking
- HTTP route ↔ call-site matching with confidence scoring
- gRPC, GraphQL, tRPC service detection with protobuf Route extraction
- Channel detection (
EMITS / LISTENS_ON) for Socket.IO, EventEmitter, and generic pub-sub patterns across 8 languages with constant resolution
Cross-repo intelligence
CROSS_* edges link nodes across multiple repos indexed under the same store
- Multi-galaxy 3D UI layout for cross-repo architecture visualization
- Cross-repo architecture summary combining services, routes, and dependencies across the indexed fleet
Edge types (selected)
CALLS — a callable is invoked at the source site
CALL_REFERENCE — a callable is used at a supported reference site (for example, a direct value argument) and resolves to one exact target
USAGE — an identifier is used, but a unique callable target is not proven (including ambiguous or complex expressions)
IMPORTS, DEFINES, IMPLEMENTS, INHERITS
HTTP_CALLS, ASYNC_CALLS (cross-service)
EMITS, LISTENS_ON (channels)
DATA_FLOWS with arg-to-param mapping + field access chains
SIMILAR_TO (MinHash + LSH near-clone detection, Jaccard scored)
SEMANTICALLY_RELATED (vocabulary-mismatch, same-language, score ≥ 0.80)
Indexing pipeline
- 158 vendored tree-sitter grammars compiled into the binary
- Generic package / module resolution — bare specifiers like
@myorg/pkg, github.com/foo/bar, use my_crate::foo resolved via manifest scanning (package.json, go.mod, Cargo.toml, pyproject.toml, composer.json, pubspec.yaml, pom.xml, build.gradle, mix.exs, *.gemspec)
- Infrastructure-as-code indexing — Dockerfiles, Kubernetes manifests, Kustomize overlays as graph nodes
- Hybrid LSP semantic type resolution for Python, TypeScript / JavaScript / JSX / TSX, PHP, C#, Go, C, C++, Java, Kotlin, Rust, and Perl — a lightweight C implementation of language type-resolution algorithms, structurally inspired by and compatible with major language servers including tsserver / typescript-go, pyright, gopls, Roslyn, Eclipse JDT, and rust-analyzer (parameter binding, return-type inference, generic substitution, JSX component dispatch, JSDoc inference for plain JS files, namespace + trait + late-static-binding resolution for PHP, file-scoped namespaces + records + LINQ method syntax for C#, class-hierarchy + overload + lambda resolution for Java, extension-function + scope-function resolution for Kotlin, trait-method + UFCS resolution for Rust)
- RAM-first pipeline: LZ4 compression, in-memory SQLite, single dump at end. Memory released after.
Distribution & operation
- Native runtime set, zero infrastructure services: SQLite-backed, persists to
~/.cache/codebase-memory-mcp/
- Auto-sync: Background watcher detects file changes and re-indexes automatically
- Route nodes: REST endpoints are first-class graph entities
- CLI mode:
codebase-memory-mcp cli search_graph '{"project": "my-project", "name_pattern": ".*Handler.*"}'
- Available on: npm, PyPI, Homebrew, Scoop, Winget, Chocolatey, AUR,
go install
Team-Shared Graph Artifact
Commit a single compressed file to your repo and your teammates skip the reindex.
.codebase-memory/graph.db.zst is a zstd-compressed snapshot of the knowledge graph that lives next to your source. When you index, the artifact is written or refreshed; when a teammate clones the repo and runs codebase-memory-mcp for the first time, the artifact is decompressed and incremental indexing fills in their local diff.
The result is similar in spirit to graphify's graphify-out/ directory, but as a single compressed file with explicit two-tier export, integrity-checked import, and zero merge friction.
How It Works
codebase-memory-mcp is a structural analysis backend — it builds and queries the knowledge graph. It does not include an LLM. Instead, it relies on your MCP client (Claude Code, or any MCP-compatible agent) to be the intelligence layer.
You: "what calls ProcessOrder?"
Agent calls: trace_path(function_name="ProcessOrder", direction="inbound")
codebase-memory-mcp: executes graph query, returns structured results
Agent: presents the call chain in plain English
Why no built-in LLM? Other code graph tools embed an LLM for natural language → graph query translation. This means extra API keys, extra cost, and another model to configure. With MCP, the agent you're already talking to is the query translator.
Performance
Benchmarked on Apple M3 Pro:
| Operation | Time | Notes |
|---|
| Linux kernel full index | 3 min | 28M LOC, 75K files → 4.81M nodes, 7.72M edges |
| Linux kernel fast index | 1m 12s | 1.88M nodes |
| Django full index | ~6s | 49K nodes, 196K edges |
| Cypher query | <1ms | Relationship traversal |
| Name search (regex) | <10ms | SQL LIKE pre-filtering |
| Dead code detection | ~150ms | Full graph scan with degree filtering |
| Trace call path (depth=5) | <10ms | BFS traversal |
RAM-first pipeline: All indexing runs in memory (LZ4 HC compressed read, in-memory SQLite, single dump at end). Memory is released back to the OS after indexing completes.
Token efficiency: Five structural queries consumed ~3,400 tokens via codebase-memory-mcp versus ~412,000 tokens via file-by-file grep exploration — a 99.2% reduction.
To measure comparable quality, latency, and agent-efficiency metrics on your own workload, see Measuring quality, latency, and agent savings. Exact reproduction of the figures above requires the original inputs and raw artifacts.
Troubleshooting & Diagnostics
codebase-memory-mcp runs 100% locally and collects no telemetry — your code, queries, environment, and usage never leave your machine. That privacy guarantee also means that when you hit something we can't reproduce on our side (a slow memory climb over hours, a performance regression, a leak that only appears after days of real use), we have no data at all unless you choose to send it. Here is how to capture it yourself.
Capture a diagnostics log
Set CBM_DIAGNOSTICS=1 before the first daemon-backed MCP session starts, then reproduce the problem (let it run as long as it takes — a slow leak needs time to show in the trend). The shared daemon captures this setting from the session that starts it. If it is already running, close all daemon-backed sessions so it exits before changing the setting. The daemon creates a fresh owner-private cbm-diagnostics-<pid>-<random> directory below the system temp directory ($TMPDIR or /tmp on macOS/Linux, %TEMP% on Windows). The exact paths are recorded by the diagnostics.start event in ${CBM_CACHE_DIR}/logs/cbm-daemon.log:
| File | What it is |
|---|
trajectory.ndjson | The memory trajectory — one JSON line every 5 s with rss, committed (Windows commit charge), peak_*, page_faults, fd, and queries. This is the file we need for memory/leak reports — the trend over time is what pinpoints a leak. It is kept on disk after the server exits (so you can grab it post-mortem) and rotates to trajectory.ndjson.1 past ~8 MB. |
snapshot.json | The latest snapshot only — handy for a quick live check. Removed on clean exit. |
The private randomized directory prevents another local account from pre-placing a link or special file at a predictable diagnostics path. Its <pid> component is the shared daemon's process ID, also recorded by the daemon.start event. Set the variable consistently in the env block of each agent's MCP server config, or export it before launching the first session.
What to share
When you open a memory/performance issue, attach the .ndjson trajectory — it contains no source code or query text, only resource counters. If you'd rather not attach a file, paste it (or an agent's summary of it) into the issue: your assistant can read the NDJSON directly and report whether rss/committed grow monotonically, how fast, and relative to query count — which is exactly what we need to find the cause.
AUR (Arch Linux)
yay -S codebase-memory-mcp-bin
paru -S codebase-memory-mcp-bin
The codebase-memory-mcp-bin package is available at: https://aur.archlinux.org/packages/codebase-memory-mcp-bin
Nix (flake)
The flake exposes two server packages plus the standalone frontend:
| Package | Contents |
|---|
default (codebase-memory-mcp) | Standard server, no UI |
codebase-memory-mcp-ui | Server with the graph UI embedded (--ui=true works) |
graph-ui | Just the built frontend assets (dist/) |
Run directly without installing:
# Standard server
nix run github:DeusData/codebase-memory-mcp
# Server with the embedded graph UI
nix run github:DeusData/codebase-memory-mcp#codebase-memory-mcp-ui -- --ui=true --port=9749
# then open http://127.0.0.1:9749
Or build a binary into ./result/bin/codebase-memory-mcp:
nix build github:DeusData/codebase-memory-mcp # standard
nix build github:DeusData/codebase-memory-mcp#codebase-memory-mcp-ui # with UI
Working in a clone? Use . in place of the flake URL, e.g. nix run .#codebase-memory-mcp-ui -- --ui=true, or drop into a shell that puts the binary on PATH with nix shell .#codebase-memory-mcp-ui.
Note: launched by hand (not from an MCP client) the server exits as soon as stdin closes — that's normal MCP behaviour. Keep stdin open while testing the UI, e.g. sleep infinity | codebase-memory-mcp --ui=true --port=9749. The codebase-memory-mcp-ui package embeds the UI at build time; nix run'ing the standard default package with --ui=true will refuse to start the HTTP server.
Build from Source
| Requirement | Check | Install |
|---|
| C compiler (gcc or clang) | gcc --version or clang --version | macOS: xcode-select --install, Linux: apt install build-essential |
| C++ compiler | g++ --version or clang++ --version | Same as above |
| zlib | — | macOS: included, Linux: apt install zlib1g-dev |
| Git | git --version | Pre-installed on most systems |
git clone https://github.com/DeusData/codebase-memory-mcp.git
cd codebase-memory-mcp
scripts/build.sh --with-ui # the shipped composition (graph UI embedded)
scripts/build.sh # without the UI (development only)
# Binary at: build/c/codebase-memory-mcp (codebase-memory-mcp.exe on Windows)
Every platform ships one self-contained executable: the graph UI and the agent integration templates are linked into the binary, so an extracted archive is immediately complete.
Run the test suite (6,768 tests across 120 suites):
scripts/test.sh # full: clean sanitizer build + all suites + guards
scripts/test.sh --suites <name> # one suite, incremental, seconds
build/c/test-runner --list-suites # what is available
scripts/test.sh is the same entry the CI gates run, so a local pass means the same thing a CI pass does. The canonical local artifact-flow check builds both stripped/unstripped candidates, defaults to the stripped candidate for this explicitly unscanned local run, packages those exact bytes, extracts the archive, and smokes it:
scripts/ci/smoke-artifact.sh <linux|darwin|windows> <amd64|arm64>
scripts/package-release.sh is intentionally a lower-level immutable boundary:
it accepts only an already-final --selected-binary plus its
--expected-sha256; it never builds, strips, signs, or relinks the executable.
Manual MCP Configuration
Add to ~/.claude.json (user scope) or project .mcp.json:
{
"mcpServers": {
"codebase-memory-mcp": {
"command": "/path/to/codebase-memory-mcp",
"args": []
}
}
}
Restart your agent. Verify with /mcp — you should see codebase-memory-mcp with 15 tools.
Multi-Agent Support
install configures 45 client surfaces: 39 detected automatically and 6
conditional or explicit. “Conditional” means the installer writes only when the
documented platform or an explicit, already-existing config path proves the
target is active. It never flips experimental feature flags, enables plugins,
YOLO modes, global permission bypasses, or third-party instruction trust.
Where a client has a documented custom-agent format, the installer creates three
exact-owned definitions from one canonical contract:
- Scout (Tier 1) — about 3–4 narrow calls for fast positive, provisional discovery; no absence, exhaustive-impact, or dead-code claims.
- Verify (Tier 2, default) — task-directed graph evidence, exact source checks, path coverage for every cited file, and scope coverage before negative claims.
- Auditor (Tier 3) — bounded scope, current index generation, complete relevant pagination, broader relationship checks, and explicit unresolved limitations.
Every direct tier batches check_index_coverage for its evidence paths and reads
flagged ranges or skipped/excluded files directly. A clean coverage result means
only “no recorded gap,” never proof of completeness. Clients without safe child
MCP access receive the same three tiers as parent-handoff agents; the parent must
supply project, generation, pagination state, graph evidence, and coverage
results. Updates migrate only byte-identical prior Verify definitions and never
overwrite user-modified agents.
| Agent | Activation | MCP config | Durable context / augmentation |
|---|
| Claude Code | Detected | ~/.claude.json | Skill + three exact-tool graph agents; SessionStart, SubagentStart, non-blocking PreToolUse for Grep/Glob/Bash, and post-Read coverage |
| Codex CLI | Detected | $CODEX_HOME/config.toml | AGENTS.md, skill, three read-only agents; SessionStart + SubagentStart |
| Gemini CLI | Detected | .gemini/settings.json | GEMINI.md, three explicit read/graph-tool subagents; BeforeTool, coverage, and |
Sessions, compaction, and subagents
Hooks installed by this project are fail-open and context-only. Claude Code's
PreToolUse observes Grep/Glob/Bash and injects matching graph symbols as
additionalContext; PostToolUse on Read adds targeted coverage context when
the graph could not fully parse or index that file. It never denies or replaces
the requested tool call.
Claude Code, Codex CLI, Qwen Code, GitHub Copilot CLI, and VS Code's Copilot
runtime receive paired session/subagent context where the vendor exposes a
documented context-output contract. Codex users must review and trust installed
hooks through /hooks; changing a hook definition changes its trust hash, so an
update can require re-trust. Qoder uses SessionStart, SubagentStart, and
post-Read coverage, including its documented PowerShell executor on Windows.
Kimi uses UserPromptSubmit, while Hermes uses pre_llm_call; both retain their
documented Windows execution paths. Devin installs
UserPromptSubmit and PostCompaction on macOS/Linux and adds SessionStart
only when Claude's equivalent managed hook is not present. GitLab Duo gets a
narrowly scoped macOS/Linux user SessionStart entry on its experimental hook
surface. GitLab Duo, Devin, and Factory hooks are withheld on Windows
because those vendors do not document a deterministic shell/executor contract
there. Gemini CLI, Factory Droid, and Augment also add documented post-read/view
coverage context but expose no equivalent documented child-start context.
For runtimes without a stable context-producing lifecycle event, durable files
carry the contract across fresh sessions and compaction: verify the graph project
and index freshness, query structural facts in the parent, then pass the project,
qualified symbols, paths, and call-chain evidence in every delegated task.
Claude, Codex, Gemini, Kiro, Qwen, Copilot, CodeBuddy, OpenCode, Kilo, Vibe,
Qoder, Junie, Factory, and Grok Build receive Scout, Verify, and Auditor graph profiles.
Kiro embeds this MCP server with --tool-profile scout for Scout and
--tool-profile analysis for Verify/Auditor. Junie registers equivalent named
server aliases because its subagent schema filters by server rather than by
individual tool. Both process profiles use positive allowlists: Scout exposes
seven fast inspection tools, Analysis exposes eleven, and future or mutating
tools remain unavailable until explicitly reviewed. If either Junie alias
collides with user configuration, the installer preserves it and installs
parent-handoff profiles instead. Qoder combines its documented named-server
selection with exact tier-specific MCP tool IDs. Factory uses exact registered
MCP tool IDs without its additive mcpServers field, which would expose the
whole server. Codex, Kilo, Vibe, and other capable formats likewise enumerate
the narrowest supported tool set. Rovo, Cursor, Augment, Pochi, and Cline use parent handoff where direct
child MCP is unavailable or unsafe; Pochi is limited to readFile, and Cline
child agents cannot use MCP.
Cline's file hooks auto-activate when present, and current Cline does not
reliably consume their context output, so automatic adapters are withheld and
older owned adapters are cleaned up. CodeBuddy's beta, version-gated hooks are
not auto-installed. Junie's EAP
SessionStart output is documented as ignored, so no context hook is installed.
Junie custom agents remain EAP-dependent. Qoder can resolve higher-priority
project or plugin agents before user agents with the same name; reload the
client after installation or profile changes.
Cursor context
hooks are withheld: session context injection has a known race, subagentStart
is control-only, and read-only subagents cannot safely receive MCP access. Grok Build's
passive hook events (SessionStart, SubagentStart, PostToolUse) discard
stdout and PreToolUse honors only deny/rewrite decisions, so its context hooks
are withheld; Grok also reads Claude and Cursor MCP, skill, and hook files
through its compat layer, and the native config.toml entry shadows that copy
by name. Rovo
has no documented session context-output hook, and Bob
documents neither a suitable hook nor a custom-agent surface. Those surfaces are
not approximated with invented augmentation. Kimi plugins, Amp plugins, and
GitLab experimental global skills remain opt-in.
OpenClaw reinjects the Codebase Knowledge Graph (codebase-memory-mcp) AGENTS
section after compaction and places the same guidance in TOOLS.md, the bootstrap
files inherited by its subagents. Automatic augmentation covers the active/default
workspace. Separate agents.list[].workspace directories require making that
workspace active for installation or copying the managed block there.
The installed Claude shim is named cbm-code-discovery-gate for backward
compatibility; despite the legacy name, it never gates or blocks.
Manual or UI-managed integrations
These are intentionally not counted as automatic installs: Qodo MCP is added
through its UI and may be governed by enterprise allowlists; Warp MCP is managed
through Warp Drive/UI or per invocation (only the shared skill is automatic);
JetBrains AI Assistant / ACP is IDE-managed; GitHub Copilot coding agent, Jules,
and CodeRabbit are cloud/repository-managed; Replit exposes a remote/service
integration rather than a stable local user-global client; BLACKBOX AI does not
document a stable arbitrary user-global MCP/instruction/agent schema; Plandex has
no stable global registry safe to mutate; and SWE-agent uses explicit YAML and is
no longer a suitable automatic global target.
CLI Mode
Every MCP tool can be invoked as a local, one-shot command. CLI tools neither start nor connect to the coordination daemon and leave no standing process behind. They hold a crash-safe exact-build admission lease only for the command lifetime. index_repository is the only exception internally: it starts a temporary, exact-build supervised worker for the index, then stops that worker before the CLI command exits; the worker holds its own lease until exit.
Commands that mutate graph data use shared OS-backed, per-project locks. This serializes conflicting work from CLI and MCP sessions on the same project while allowing unrelated projects to proceed independently.
When stderr is an interactive terminal, the CLI automatically shows lifecycle and indexing progress. Pass --progress to force the same feedback when stderr is redirected or the command is run non-interactively. Pass --quiet to disable automatic terminal progress and ordinary diagnostics while retaining errors; it cannot be combined with --progress or outer cli --verbose. Routine informational logs are quiet by default; pass outer cli --verbose to include them. Progress and logs use stderr while stdout remains reserved for the command result. Read tools return a compact tree by default; pass a tool's --format json for machine-readable payload JSON, or outer --json for the full MCP envelope.
Large compact-tree tables may start with a response-local <section>_refs directory and an explicit <section>_ref_rule. A cell such as @0+handler.go reconstructs to ref 0's prefix plus handler.go. References are local to that sibling <section> table and expansion is non-recursive: entries inside <section>_refs are always literal prefixes. This is limited to declared path and qualified-name columns and activates only when the exact rendered table is at least 15% and 64 bytes smaller and a conservative model-neutral token-shape proxy also improves by at least 1%. Search and trace likewise render direct and prefix-grouped tree shapes and keep the smaller complete representation, so singleton or scattered answers do not pay directory overhead. Keys are declared once per table but never cryptically abbreviated, and --format json keeps stable literal strings for machine consumers. Both gates are deterministic; exact token counts still depend on the caller's tokenizer.
Lean responses truncate semantically, never by cutting arbitrary bytes from code or identifiers. Ranked graph rows are retained ahead of raw grep rows and diagnostic summaries; omitted rows/sections report totals, has_more, and a strictly advancing continuation offset or cursor. If even the first whole row cannot fit, CBM asks for a higher budget and emits no self-looping cursor. max_output_tokens is model-neutral sizing guidance: CBM enforces a deterministic ceiling of four UTF-8 bytes per requested token, so it is not a tokenizer-exact count. Detail flags such as diagnostics, source_mode, and detail opt into heavier fields. search_code pages ranked rows with result_limit/result_offset (limit remains a compatibility alias), raw rows with raw_limit/raw_offset, and directory summaries with directory_limit/directory_offset. Raw lines default to a UTF-8-safe match-centered preview; each row reports content_start_byte, returned/total byte counts, match byte bounds when known, and a content continuation offset. Pass raw_content_offset to page the original line without moving the raw-row cursor. match_limit and source_max_lines bound per-result details, with exact omission metadata. detect_changes pages changed files, impacted symbols, and module summaries independently; prefer its snapshot-bound *_cursor continuations, which reject changed commits, worktree bytes, graph generation, or semantic arguments instead of silently skipping or duplicating rows.
Every response is standard UTF-8. Identifiers, paths, and raw search previews preserve POSIX byte-string identities: a preserved value containing malformed UTF-8 is emitted reversibly as @bytes:<lowercase hex of every original byte>. A valid preserved value that literally begins with the reserved @bytes: or @utf8: prefix is emitted as @utf8:<original value>, so decoding is unambiguous: strip one @utf8: prefix for literal UTF-8, or hex-decode one @bytes: prefix for original bytes. Ordinary valid UTF-8 is unchanged and pays no output-token overhead. To keep code readable, source bodies replace malformed UTF-8 with U+FFFD; use the pageable raw search preview when byte-exact source inspection is required.
Use cli <tool> --help to see the flags generated from that tool's input schema:
codebase-memory-mcp cli index_repository --repo-path /path/to/repo
codebase-memory-mcp cli list_projects
# Use the "name" returned by list_projects as the project value.
codebase-memory-mcp cli search_graph --project my-project --name-pattern '.*Handler.*' --label Function
codebase-memory-mcp cli trace_path --project my-project --function-name Search --direction both
codebase-memory-mcp cli query_graph --project my-project --query 'MATCH (f:Function) RETURN f.name LIMIT 5'
# Force human-readable progress without contaminating stdout.
codebase-memory-mcp cli --progress index_repository --repo-path /path/to/repo
# Suppress automatic terminal progress and non-error diagnostics.
codebase-memory-mcp cli --quiet list_projects --format json
codebase-memory-mcp cli search_graph --project my-project --label Function --format json
codebase-memory-mcp cli list_projects --format json --detail stats | jq '.projects[].name'
JSON arguments can also be piped on stdin, for tools that take arguments. A tool whose input schema declares none — list_projects — never reads stdin, so it stays responsive when it inherits a pipe the caller never closes (the default for child_process.spawn and similar wrappers). Inline JSON remains accepted for backward compatibility but is deprecated in favor of flags, --args-file, or stdin.
MCP Tools
Indexing
| Tool | Description |
|---|
index_repository | Index a repository into the graph. Auto-sync keeps it fresh after that. |
list_projects | List all indexed projects with node/edge counts. |
delete_project | Remove a project and all its graph data. |
index_status | Check indexing status of a project. |
Querying
| Tool | Description |
|---|
search_graph | Structural, BM25, and semantic search. Page structural rows with offset/limit and ranked semantic rows independently with semantic_offset/semantic_limit. |
trace_path | BFS traversal — who calls a function and what it calls (alias: trace_call_path). Depth 1-5. |
detect_changes | Map git diff to affected symbols + blast radius with risk classification. |
query_graph | Execute Cypher-like graph queries (read-only). |
get_graph_schema | Node/edge counts, relationship patterns, property definitions per label. Run this first. |
get_code_snippet | Read source code for a function by qualified name. |
get_architecture | Codebase overview: languages, packages, routes, hotspots, clusters, ADR. |
|
manage_adr(mode='set_sections') writes one or more sections by name and splices them into the stored document, so text outside the named sections — including a preamble, code fences and section ordering — is preserved byte-for-byte. Any ## Heading works, not just the conventional PURPOSE / STACK / ARCHITECTURE / PATTERNS / TRADEOFFS / PHILOSOPHY set; names match exactly, including case. Writing the same section twice is a no-op, so a retry after a lost response cannot duplicate content.
manage_adr query modes (get and sections) use the server's cached query store so they can proceed while a same-project reindex is running. If another process publishes a replacement store during reindexing, they can return the pre-publication ADR until idle eviction refreshes that cache. Updates remain serialized through the project mutation guard.
Graph Data Model
Node Labels
Project, Package, Folder, File, Module, Class, Function, Method, Interface, Enum, Type, Route, Resource
Edge Types
CONTAINS_PACKAGE, CONTAINS_FOLDER, CONTAINS_FILE, DEFINES, DEFINES_METHOD, IMPORTS, CALLS, CALL_REFERENCE, HTTP_CALLS, ASYNC_CALLS, IMPLEMENTS, HANDLES, USAGE, CONFIGURES, WRITES, MEMBER_OF, TESTS, USES_TYPE, FILE_CHANGES_WITH
Qualified Names
get_code_snippet uses qualified names: <project>.<path_parts>.<name>. Use search_graph to discover them first.
Supported Cypher (openCypher read subset)
query_graph is a read-only openCypher subset:
- Clauses:
MATCH, OPTIONAL MATCH, multiple MATCH, WHERE, WITH (+ WITH … WHERE), RETURN, ORDER BY, SKIP, LIMIT, DISTINCT, UNWIND, UNION / UNION ALL, CASE.
- Patterns: labelled nodes, label alternation
(n:A|B), relationship types/direction, variable-length paths [*1..3], inline property maps.
- WHERE:
= <> < <= > >=, AND/OR/XOR/NOT, IN, CONTAINS, STARTS WITH, ENDS WITH, IS [NOT] NULL, regex =~, label test n:Label, and EXISTS { (n)-[:TYPE]->() } (single-hop existence — great for dead-code, e.g. ).
Anything outside this subset (write/MERGE/CALL clauses, unsupported functions, list/map literals, comprehensions, path functions, parameters) fails with a clear unsupported … error rather than returning empty results.
Ignoring Files
Layered: hardcoded patterns (.git, node_modules, etc.) → .gitignore hierarchy → .cbmignore (project-specific, gitignore syntax). Symlinks are always skipped.
See docs/cbmignore.md for the full .cbmignore how-to: syntax, precedence across the ignore layers, and negation semantics.
Configuration
codebase-memory-mcp config list # show all settings
codebase-memory-mcp config set auto_index true # auto-index on session start
codebase-memory-mcp config set auto_index_limit 50000 # max files for auto-index
codebase-memory-mcp config set auto_watch false # don't register background git watcher (default: true)
codebase-memory-mcp config set watcher_enabled false # stop the watcher thread entirely (default: true)
codebase-memory-mcp config reset auto_index # reset to default
Environment Variables
| Variable | Default | Description |
|---|
CBM_ALLOWED_ROOT | (unset) | Confine index_repository to paths within this directory. When set, a repo_path that resolves (after symlink / .. resolution) outside this root is refused, and the same check now applies to the graph UI's POST /api/index route rather than only to the MCP tool. Unset imposes no containment restriction — but see the always-on limits below, which apply whether or not this is set. Useful when the server may be driven by an untrusted caller, e.g. agentic or multi-tenant deployments. |
CBM_CACHE_DIR | ~/.cache/codebase-memory-mcp | Override the database storage directory. All project indexes and config are stored here. One account can use only one canonical cache root at a time; close active CBM sessions/commands before switching it. |
CBM_DIAGNOSTICS | false | Set to 1 or true to enable the shared daemon's periodic snapshot.json and retained trajectory.ndjson below a fresh owner-private directory in the system temp directory. Exact paths are logged by . |
Environment used by daemon-owned components—such as diagnostics, daemon logging, and process-wide indexing resource limits—is captured from the first daemon-backed session that starts the daemon. Later sessions join that process and cannot replace those values. To change them, close all daemon-backed sessions, update the relevant agent configurations consistently, and restart a session. CBM_ALLOWED_ROOT remains session-specific, a conflicting CBM_CACHE_DIR is rejected, and one-shot CLI commands read their own environment without starting the daemon.
# Store indexes in a custom directory
export CBM_CACHE_DIR=~/my-projects/cbm-data
Custom File Extensions
The JSON config files support a single key, extra_extensions, which maps additional file extensions to supported languages. Useful for framework-specific extensions like .blade.php (Laravel) or .mjs (ES modules). (For other tunables, see Environment Variables and the config subcommand above.)
Need the full config-file reference? See docs/CONFIGURATION.md.
Per-project (in your repo root):
// .codebase-memory.json
{"extra_extensions": {".blade.php": "php", ".mjs": "javascript"}}
Global (applies to all projects):
// ~/.config/codebase-memory-mcp/config.json (or $XDG_CONFIG_HOME/...)
{"extra_extensions": {".twig": "html", ".phtml": "php"}}
Each entry maps an extension (which must start with .) to a language name. Language names are matched case-insensitively. Accepted values (aliases in parentheses) are:
bash (sh), c, c++ (cpp), c# (csharp), clojure, cmake, cobol, common lisp (commonlisp, lisp), css, cuda, dart, dockerfile, elixir, elm, emacs lisp (emacslisp), erlang, f# (fsharp), form, fortran, glsl, go, graphql, groovy, haskell, (), , , , , , , , , , , , , , , , (), , , , , , , , , , , , , , , , , , , , , , , .
Project config overrides global for conflicting extensions. An entry whose language name is unknown, or whose extension does not start with ., is skipped and a warning is logged to stderr (shown at the default info log level). Missing config files are ignored.
Persistence
SQLite databases stored at ~/.cache/codebase-memory-mcp/. Persists across restarts (WAL mode, ACID-safe). To reset: rm -rf ~/.cache/codebase-memory-mcp/.
Troubleshooting
| Problem | Fix |
|---|
/mcp doesn't show the server | Check .mcp.json path is absolute. Restart agent. Test: echo '{}' | /path/to/binary should output JSON. |
index_repository fails | Pass absolute path: index_repository(repo_path="/absolute/path") |
trace_path returns 0 results | Use search_graph(name_pattern=".*PartialName.*") first to find the exact name. |
| Queries return wrong project results | Add project="name" parameter. Use list_projects to see names. |
| Binary not found after install | Add to PATH: export PATH="$HOME/.local/bin:$PATH" |
| UI not loading | Ensure you ran --ui=true. Check http://localhost:9749. |
Hybrid LSP
Semantic type resolution beyond tree-sitter.
Tree-sitter alone gives a syntactic AST. That handles naming, structure, and call sites well, but it can't tell you that user.profile.display_name() resolves to Profile.display_name declared three modules away — tree-sitter doesn't track imports, generics, inheritance, or stdlib types.
codebase-memory-mcp ships a lightweight C implementation of language type-resolution algorithms, structurally inspired by and compatible with major language servers (tsserver / typescript-go, pyright, gopls, Roslyn, Eclipse JDT, rust-analyzer), embedded directly into the native executable. No language server process, no per-project setup, no API key. We call this layer Hybrid LSP: it runs alongside tree-sitter on every parse and refines invocation resolution (CALLS / RESOLVED_CALLS) and callable-value resolution (CALL_REFERENCE, with ambiguous values retained as USAGE) using type information, so the resulting graph mirrors what an IDE "Go to Definition" would resolve.
Languages with full Hybrid LSP:
| Language | What it handles |
|---|
| Python (new in v0.7.0) | imports + dotted submodule walks, dataclasses, Self return types, generics, @property, match/case class patterns, SQLAlchemy 2.0 Mapped[T], Pydantic BaseModel, typing.Annotated / ClassVar / Final / InitVar, async/await, classmethod/staticmethod, narrowing (isinstance / is not None / walrus), typing.cast / assert_type, common stdlib (logging, pathlib, json, functools). Target ~95% resolution on idiomatic code. |
| TypeScript / JavaScript / JSX / TSX | generics, JSX component dispatch, JSDoc inference for plain JS, .d.ts declarations, module re-exports, method chaining via return-type propagation, per-file overlay chained to a shared cross-file registry |
| PHP (new in v0.7.0) | namespaces, traits, late-static-binding, PHPDoc inference, parameter binding, return-type inference |
| C# |
Two-layer architecture:
- Tree-sitter pass — fast, syntactic, runs for every one of the 162 languages. Extracts definitions, calls, imports.
- Hybrid LSP pass — type-aware, runs above the tree-sitter pass per-language. Refines call edges using the import graph plus a per-file or pre-built cross-file definition registry. Languages without a Hybrid LSP pass yet fall back to textual resolution, so you always get some answer.
The result is a knowledge graph accurate enough to drive trace_path across packages, inheritance hierarchies, and stdlib calls — without paying for a language server process per project.
Language Support
162 languages, all parsed via vendored tree-sitter grammars compiled into the binary. Benchmarked against 64 real open-source repositories (78 to 49K nodes):
| Tier | Score | Languages |
|---|
| Excellent (>= 90%) | | Lua, Kotlin, C++, Perl, Objective-C, Groovy, C, Bash, Zig, Swift, CSS, YAML, TOML, HTML, SCSS, HCL, Dockerfile |
| Good (75-89%) | | Python, TypeScript, TSX, Go, Rust, Java, R, Dart, JavaScript, Erlang, Elixir, Scala, Ruby, PHP, C#, SQL |
| Functional (< 75%) | | OCaml, Haskell |
Also supported (not yet benchmarked): Ada, Agda, Apex, Assembly (NASM), Astro, AWK, Beancount, BibTeX, Bicep, Bitbake, Blade, Cairo, Cap'n Proto, Clojure, CMake, COBOL, Common Lisp, Crystal, CSV, CUDA, D, Devicetree, Diff, .env, Elm, Emacs Lisp, F#, Fennel, Fish, FORM, Fortran, FunC, GDScript, .gitattributes, .gitignore, Gleam, GLSL, GN, Go module, Go template, GraphQL, Hare, HLSL, Hyprlang, INI, ISPC, Janet, Jinja2, JSDoc, JSON, JSON5, Jsonnet, Julia, Just, Kconfig, KDL, Lean 4, Linker Script, Liquid, LLVM IR, Luau, Magma, Makefile, Markdown, MATLAB, Mermaid, Meson, Move, Nickel, Nim, Nix, Odin, Pascal, Pkl, PO (gettext), Pony, PowerShell, Prisma, .properties, Protobuf, Puppet, PureScript, Racket, Regex, requirements.txt, ReScript, RON, reStructuredText, Scheme, Slang, Smali, Smithy, Solidity, SOQL, SOSL, Squirrel, SSH config, Starlark, Svelte, Sway, SystemVerilog, TableGen, Tcl, Teal, Templ, Thrift, TLA+, Typst, Verilog, VHDL, Vim script, Vue, WGSL, WIT, Wolfram, XML, Zsh.
Architecture
src/
main.c Entry point (MCP stdio server + CLI + install/update/config)
daemon/ Per-account session coordination, IPC, lifecycle, shared jobs/watchers
mcp/ MCP server (15 tools, JSON-RPC 2.0, session detection, auto-index)
cli/ Install/uninstall/update/config (45 client surfaces, hooks, instructions)
store/ SQLite graph storage (nodes, edges, traversal, search, Louvain)
pipeline/ Multi-pass indexing (structure → definitions → calls → HTTP links → config → tests)
cypher/ Cypher query lexer, parser, planner, executor
discover/ File discovery (.gitignore, .cbmignore, symlink handling)
watcher/ Background auto-sync (git polling, adaptive intervals)
traces/ Runtime trace ingestion
ui/ Local HTTP server + verified external 3D-UI asset pack
foundation/ Platform abstractions (threads, filesystem, logging, memory)
internal/cbm/ Vendored tree-sitter grammars (162 languages) + AST extraction engine
Security
Every release is verified through a multi-layer pipeline before publication:
- VirusTotal — all 24 executable candidates (unstripped, debug-stripped and stripped) across the eight release products are scanned before smoke/soak (clean is preferred and only the single-Microsoft
!ml tolerance documented in SECURITY.md may pass; the number of engines that returned a decisive result is recorded as evidence but is VirusTotal fleet availability, not a pass condition). The selected executable is packaged without changing its SHA-256, release notes link the verdict for the exact bytes shipped, and the full per-candidate evidence is published alongside the release as TSVs for anyone auditing the selection. Every distinct object extracted from the shipped containers — install.sh, install.ps1, LICENSE, THIRD_PARTY_NOTICES.md, the MCPB manifest.json and the unpacked UI assets — is then scanned as well, so the full published surface is covered, not just the executables.
- SLSA Level 3 — cryptographic build provenance generated by the trusted GitHub Actions build workflow; verify with
gh attestation verify <file> --repo DeusData/codebase-memory-mcp --signer-workflow DeusData/codebase-memory-mcp/.github/workflows/_build.yml
- Sigstore cosign — keyless signatures on all artifacts; bundles included in every release
- SHA-256 checksums —
checksums.txt published with every release; verified by both install scripts before extraction
- CodeQL SAST — blocks release pipeline if any open alerts remain
- No language-runtime dependency chain — libraries are vendored at compile time; the small release-owned runtime assets are checksum-verified and content-addressed
v0.7.0 VirusTotal scans
| Binary | SHA-256 | VirusTotal |
|---|
linux-amd64 | 8e12bb2d6ead7f20a6d3... | 0/72 ✅ |
linux-arm64 | 10f7136bfbf3950c6b2a... | 0/72 ✅ |
darwin-arm64 | 7062a7408906344bf4f8... | 0/72 ✅ |
darwin-amd64 | 28c6d640e1a0ac7bfcab... | 0/72 ✅ |
Scan links for every release are also included in the GitHub Release notes automatically.
License
MIT