Important
This repository is a fork of the original DeusData/codebase-memory-mcp. It tracks upstream loosely: useful fixes and features are adopted selectively, but this fork does not mirror upstream releases or preserve identical storage behavior.
This fork combines codebase-memory-mcp's tree-sitter/LSP indexing and MCP tools with a Zova-native shared database. Zova owns graph topology and vector search in full-authority mode, enabling fast incremental publication, native traversal, compact large-repository storage, and searches spanning several indexed repositories.
High-quality parsing through tree-sitter AST analysis across all 158 languages, enhanced with Hybrid LSP semantic type resolution for Python, TypeScript / JavaScript / JSX / TSX, PHP, C#, Go, C, C++, Java, Kotlin, and Rust — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 14 MCP tools. Zero dependencies. Plug and play across 11 coding agents.
The current development version uses CBM schema 7 with a pinned Zova format 9 / ABI 0.25.0 SDK. Compared with the original pure-SQLite implementation, it adds:
- One shared database — multiple repositories live as isolated workspaces in
cbm.zova. - Cross-repository discovery — one
search_graphrequest can search selected projects or every healthy workspace and identifies the owning project for each result. - Native graph and vectors — topology, edge payloads, traversal indexes, and int8 vector collections use Zova's native stores rather than duplicate SQLite projections.
- Incremental-first performance — unchanged records are not republished; native delta APIs update only the affected graph, metadata, FTS, and vector records.
- Exact compatibility checks — benchmarked Zova results are required to match the pure-SQLite CBM result set exactly, with no unexpected fallback.
The shared Zova full-authority route is the default for indexing and queries. The original per-project SQLite route is retained only as an explicit compatibility and benchmark mode selected with CBM_ZOVA_MODE=off.
ReleaseSafe medians compare this fork's Zova-native mode with the same CBM build using pure SQLite. Lower indexing time, storage, and vector p95 are better.
| Area | TOPS vs pure SQLite | Deno vs pure SQLite |
|---|---|---|
| Full indexing | 5.7% slower | 6.1% slower |
| Incremental indexing | 76.9% faster | 51.6% faster |
| Storage | 12.9% larger | 2.4% smaller |
| Vector p95 | 76.6% faster | 86.2% faster |
| Correctness | Exact | Exact |
Full indexing remains the current tradeoff. Zova's advantage is strongest for repeated indexing and vector retrieval; its fixed database overhead is more visible on a small repository such as TOPS, while it is already smaller than pure SQLite on Deno.
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. Audit the fork source before running if required. Indexing and queries run locally; source code is not sent to a hosted service. Report security issues through SECURITY.md.
Built-in 3D graph visualization (UI variant) — explore your knowledge graph at localhost:9749
- Fast updates after the first index — native delta publication makes incremental indexing 51.6%–76.9% faster in the current TOPS and Deno benchmarks.
- Cross-repository context — search frontend, backend, libraries, or any other selected project set in one query without requiring repository names such as
frontendorbackend. - Exact results — Zova-native benchmark parity is checked against the pure-SQLite implementation.
- Plug and play — release binaries for macOS, Linux, and Windows on amd64 and arm64. No Docker, hosted service, or API key. Download → install → restart agent → done.
- 158 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.
- 11 agents, one command —
installauto-detects Claude Code, Codex CLI, Gemini CLI, Zed, OpenCode, Antigravity, Aider, KiloCode, VS Code, OpenClaw, and Kiro — configures MCP entries, instruction files, and pre-tool hooks for each. - Built-in graph visualization — 3D interactive UI at
localhost:9749(optional UI binary variant). - Infrastructure-as-code indexing — Dockerfiles, Kubernetes manifests, and Kustomize overlays indexed as graph nodes with cross-references.
Resourcenodes for K8s kinds,Modulenodes for Kustomize overlays withIMPORTSedges to referenced resources. - 14 MCP tools — search, trace, architecture, impact analysis, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.
One-line install (macOS / Linux):
curl -fsSL https://raw.githubusercontent.com/0ctacity/codebase-memory-mcp/main/install.sh | bashThe installer is non-destructive by default. If a different binary or MCP
configuration already exists, replacement must be authorized explicitly with
--replace or --replace-config.
With graph visualization UI:
curl -fsSL https://raw.githubusercontent.com/0ctacity/codebase-memory-mcp/main/install.sh | bash -s -- --uiWindows (PowerShell):
# 1. Download the installer
Invoke-WebRequest -Uri https://raw.githubusercontent.com/0ctacity/codebase-memory-mcp/main/install.ps1 -OutFile install.ps1
# 2. (Optional but recommended) Inspect the script
notepad install.ps1
# 3. Unblock the downloaded file (removes Mark-of-the-Web restriction added by browsers/Invoke-WebRequest)
Unblock-File .\install.ps1
# 4. Run it
.\install.ps1
Note: If you see a script execution policy error, run
Set-ExecutionPolicy -Scope Process Bypassfirst, or invoke withPowerShell -ExecutionPolicy Bypass -File .\install.ps1.
Options: --ui (graph visualization), --skip-config (binary only, no agent setup), --dir=<path> (custom location).
Restart your coding agent. Say "Index this project" — done.
Manual install
-
Download the archive for your platform from the latest release:
codebase-memory-mcp-<os>-<arch>.tar.gz(macOS/Linux) or.zip(Windows) — standardcodebase-memory-mcp-ui-<os>-<arch>.tar.gz/.zip— with graph visualization
-
Extract and install (each archive includes
install.shorinstall.ps1):macOS / Linux:
tar xzf codebase-memory-mcp-*.tar.gz ./install.shWindows (PowerShell):
Expand-Archive codebase-memory-mcp-windows-amd64.zip -DestinationPath . Unblock-File .\install.ps1 .\install.ps1
-
Restart your coding agent.
The install command automatically strips macOS quarantine attributes and ad-hoc signs the binary — no manual xattr/codesign needed.
The install command auto-detects all installed coding agents and configures MCP server entries, instruction files, skills, and pre-tool hooks for each.
If you downloaded the ui variant:
codebase-memory-mcp --ui=true --port=9749Open http://localhost:9749 in your browser. The UI runs as a background thread alongside the MCP server — it's available whenever your agent is connected.
Enable automatic indexing on MCP session start:
codebase-memory-mcp config set auto_index trueWhen enabled, new projects are indexed automatically on first connection. Previously-indexed projects are registered with the background watcher for ongoing git-based change detection. Configurable file limit: config set auto_index_limit 50000.
Watcher registration is controlled separately by auto_watch (default true). Set config set auto_watch false to keep a session from registering its project with the background watcher — useful when working across many projects and you want each session contained to explicit indexing.
codebase-memory-mcp updateThe MCP server also checks for updates on startup and notifies on the first tool call if a newer release is available.
codebase-memory-mcp uninstallRemoves the installed binary, agent configs, skills, hooks, and instructions. The shared cbm.zova database is kept.
- Architecture overview:
get_architecturereturns languages, packages, entry points, routes, hotspots, boundaries, layers, and clusters in a single call - Architecture Decision Records:
manage_adrpersists architectural decisions across sessions - Louvain community detection: Discovers functional modules by clustering call edges
- Git diff impact mapping:
detect_changesmaps 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
- Semantic search (
semantic_query): vector search across the entire graph, powered by bundled Nomicnomic-embed-codeembeddings (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_splittokenizer (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
- 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_*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
CALLS,IMPORTS,DEFINES,IMPLEMENTS,INHERITSHTTP_CALLS,ASYNC_CALLS(cross-service)EMITS,LISTENS_ON(channels)DATA_FLOWSwith arg-to-param mapping + field access chainsSIMILAR_TO(MinHash + LSH near-clone detection, Jaccard scored)SEMANTICALLY_RELATED(vocabulary-mismatch, same-language, score ≥ 0.80)
- 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::fooresolved 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, and Rust — 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)
- Prepared Zova publication: finalized nodes, grouped topology edges with compact payloads, metadata, FTS rows, and vectors are published atomically into the shared database.
- Single self-contained application, zero infrastructure: Zova embeds SQLite and persists the shared full-authority store at
~/.cache/codebase-memory-mcp/cbm.zova. - 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 '{"name_pattern": ".*Handler.*"}' - Release archives: signed-by-checksum binaries and installers for macOS, Linux, and Windows on amd64 and arm64.
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.
- Format: SQLite database, indexes stripped,
VACUUM INTOcompacted, then zstd 1.5.7 compressed (8–13:1 ratio typical) - Two tiers:
- Best (
zstd -9+ index strip +VACUUM INTO) — written on explicitindex_repository - Fast (
zstd -3) — written by the watcher for low-latency incremental updates
- Best (
- Bootstrap: when no local DB exists but the artifact is present,
index_repositoryimports the artifact first, then runs incremental indexing — avoiding the full reindex cost - No merge pain: a
.gitattributesline withmerge=oursis auto-created on first export, so concurrent edits don't produce conflicts on the binary artifact - Optional: never committed unless you want it. Add
.codebase-memory/to.gitignoreif you prefer everyone to reindex from scratch.
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.
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.
The Zova-native comparison above is the current fork benchmark. The following upstream-scale figures remain useful as parser and query reference points, but they are not measurements of the current Zova full-authority route:
| 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.
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.
Set CBM_DIAGNOSTICS=1 before the MCP server starts, then reproduce the problem (let it run as long as it takes — a slow leak needs time to show in the trend). The server writes two files to your system temp directory ($TMPDIR or /tmp on macOS/Linux, %TEMP% on Windows):
| File | What it is |
|---|---|
cbm-diagnostics-<pid>.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 .ndjson.1 past ~8 MB. |
cbm-diagnostics-<pid>.json |
The latest snapshot only — handy for a quick live check. Removed on clean exit. |
The startup log prints both paths, e.g.:
level=info msg=diagnostics.start snapshot=/tmp/cbm-diagnostics-12345.json trajectory=/tmp/cbm-diagnostics-12345.ndjson interval=5s
Set the variable in the env block of your agent's MCP server config, or export it before launching the server.
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.
| Platform | Standard | With Graph UI |
|---|---|---|
| macOS (Apple Silicon) | codebase-memory-mcp-darwin-arm64.tar.gz |
codebase-memory-mcp-ui-darwin-arm64.tar.gz |
| macOS (Intel) | codebase-memory-mcp-darwin-amd64.tar.gz |
codebase-memory-mcp-ui-darwin-amd64.tar.gz |
| Linux (x86_64) | codebase-memory-mcp-linux-amd64.tar.gz |
codebase-memory-mcp-ui-linux-amd64.tar.gz |
| Linux (ARM64) | codebase-memory-mcp-linux-arm64.tar.gz |
codebase-memory-mcp-ui-linux-arm64.tar.gz |
| Linux portable (x86_64) | codebase-memory-mcp-linux-amd64-portable.tar.gz |
codebase-memory-mcp-ui-linux-amd64-portable.tar.gz |
| Linux portable (ARM64) | codebase-memory-mcp-linux-arm64-portable.tar.gz |
codebase-memory-mcp-ui-linux-arm64-portable.tar.gz |
| Windows (x86_64) | codebase-memory-mcp-windows-amd64.zip |
codebase-memory-mcp-ui-windows-amd64.zip |
| Windows (ARM64) | codebase-memory-mcp-windows-arm64.zip |
codebase-memory-mcp-ui-windows-arm64.zip |
Every release includes checksums.txt with SHA-256 hashes, and the canonical
installer refuses an unverified network download. The portable Linux archives
are statically linked; the standard Linux archives target the release runner's
glibc. The installer selects portable Linux by default.
Windows note: SmartScreen may show a warning for unsigned software. Click "More info" → "Run anyway". Verify integrity with
checksums.txt.
Prerequisites: C compiler + zlib
| 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/0ctacity/codebase-memory-mcp.git
cd codebase-memory-mcp
scripts/build.sh # standard binary
scripts/build.sh --with-ui # with graph visualization
# Binary at: build/c/codebase-memory-mcpIf you prefer not to use the install command
Add to ~/.claude/.mcp.json (global) 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 14 tools.
install auto-detects and configures all installed agents:
| Agent | MCP Config | Instructions | Hooks |
|---|---|---|---|
| Claude Code | .claude/.mcp.json |
4 Skills | PreToolUse (Grep/Glob graph augment, non-blocking) |
| Codex CLI | .codex/config.toml |
.codex/AGENTS.md |
SessionStart reminder |
| Gemini CLI | .gemini/settings.json |
.gemini/GEMINI.md |
BeforeTool (grep reminder) + SessionStart reminder |
| Zed | settings.json (JSONC) |
— | — |
| OpenCode | opencode.json |
AGENTS.md |
— |
| Antigravity | .gemini/config/mcp_config.json (shared) |
antigravity-cli/AGENTS.md |
SessionStart reminder |
| Aider | — | CONVENTIONS.md |
— |
| KiloCode | mcp_settings.json |
~/.kilocode/rules/ |
— |
| VS Code | Code/User/mcp.json |
— | — |
| OpenClaw | openclaw.json |
— | — |
| Kiro | .kiro/settings/mcp.json |
— | — |
Hooks are structurally non-blocking (exit code 0, every failure path).
For Claude Code, the PreToolUse hook intercepts Grep/Glob (never Read —
gating Read breaks the read-before-edit invariant) and, when the search
token matches indexed symbols, injects them as additionalContext via
search_graph so the agent gets structured context alongside its normal
search results. For Codex, Gemini CLI, and Antigravity, a SessionStart hook
injects a one-line code-discovery reminder as session context (Gemini CLI also
keeps its BeforeTool reminder).
The installed Claude shim file is named cbm-code-discovery-gate for
backward compatibility with existing installs; despite the legacy name it
never gates and never blocks.
Every MCP tool can be invoked from the command line:
codebase-memory-mcp cli index_repository '{"repo_path": "/path/to/repo"}'
codebase-memory-mcp cli search_graph '{"name_pattern": ".*Handler.*", "label": "Function"}'
codebase-memory-mcp cli trace_path '{"function_name": "Search", "direction": "both"}'
codebase-memory-mcp cli query_graph '{"query": "MATCH (f:Function) RETURN f.name LIMIT 5"}'
codebase-memory-mcp cli list_projects
codebase-memory-mcp cli --raw search_graph '{"label": "Function"}' | jq '.results[].name'Section 7 migration is an explicit operator action. It discovers the existing
project .db and sibling .zova in the resolved CBM cache and publishes their
verified generation into cbm.zova. Migrate, status, and rollback preserve the
source artifacts.
codebase-memory-mcp zova-migrate migrate --repo-path /absolute/path/to/repository --json
codebase-memory-mcp zova-migrate status --repo-path /absolute/path/to/repository --json
codebase-memory-mcp zova-migrate rollback --repo-path /absolute/path/to/repository --json
codebase-memory-mcp zova-migrate cleanup --repo-path /absolute/path/to/repository \
--confirm-workspace w1_0123456789abcdef0123456789abcdef --jsonThe command prints one compact JSON object. Exit 0 means success or an
idempotent no-op, exit 1 means an operational failure, and exit 2 means a
usage error. Cleanup requires the exact reported workspace ID. It removes the
verified legacy bundle and permanently ends rollback availability for that
migration.
The wrapper exposes the same lifecycle:
scripts/zova-migrate-repo.sh migrate /absolute/path/to/repository
scripts/zova-migrate-repo.sh status /absolute/path/to/repository
scripts/zova-migrate-repo.sh rollback /absolute/path/to/repository
scripts/zova-migrate-repo.sh cleanup /absolute/path/to/repository \
--confirm-workspace w1_0123456789abcdef0123456789abcdefThe historical scripts/zova-migrate-repo.sh REPOSITORY [RUN_ROOT] form is a
migrate alias. The wrapper holds a run-root lock and retains the exact compact
JSON response as runs/<run>/migration.json; the default run root is
build/zova-migrate.
The one-file cbm.zova schema is documented in
docs/zova-single-file-schema.md.
The shared-database operator commands act only on
${CBM_CACHE_DIR:-$HOME/.cache/codebase-memory-mcp}/cbm.zova and emit exactly
one compact JSON object. Exit 0 means success or no-op, exit 1 means an
operational refusal/failure, and exit 2 means invalid command syntax.
codebase-memory-mcp zova-ops status --json
codebase-memory-mcp zova-ops backup --output /safe/path/cbm-backup.zova --json
codebase-memory-mcp zova-ops restore --input /safe/path/cbm-backup.zova --confirm-replace --json
codebase-memory-mcp zova-ops export-database --output /safe/path/database-archive --json
codebase-memory-mcp zova-ops import-database --input /safe/path/database-archive --confirm-replace --json
codebase-memory-mcp zova-ops export-workspace --workspace-id WORKSPACE_ID --output /safe/path/workspace-archive --json
codebase-memory-mcp zova-ops import-workspace --input /safe/path/workspace-archive --json
codebase-memory-mcp zova-ops delete-workspace --workspace-id WORKSPACE_ID --confirm-workspace WORKSPACE_ID --json
codebase-memory-mcp zova-ops compact --json
codebase-memory-mcp zova-ops health --workspace-id WORKSPACE_ID --json
codebase-memory-mcp zova-ops recover-workspace --workspace-id WORKSPACE_ID --repo-path /absolute/repository --jsonFull-database archives contain a versioned manifest and verified data.zova.
Workspace archives contain one workspace's metadata, canonical FTS, native
graph and vector payloads, file hashes, summary, generation, and integrity
digests; import rebuilds and verifies the native objects. Restore and database import
require the literal --confirm-replace flag. Workspace deletion requires the
exact target ID as --confirm-workspace.
Replacement is same-directory and resumable: the candidate is verified before the live file moves, and interruption leaves either the preceding verified live database or a retryable recovery artifact. Compaction runs only when reclaimable space is at least both 64 MiB and 10 percent of the database, and requires free space of at least the larger of 8 GiB or database bytes plus 1 GiB.
Health distinguishes workspace_rebuild from whole_file_recovery. A confined
workspace defect blocks only that flagged workspace until a full source rebuild
publishes successfully. Shared-schema, open, quick-check, foreign-key, or other
unattributable damage requires a verified full backup restore; without one,
explicit recovery quarantines the corrupt file and creates no replacement.
The wrapper builds once, applies the disk guard, serializes operations, writes
progress to stderr, and retains JSON reports under build/zova-operations:
scripts/zova-operations.sh status
scripts/zova-operations.sh backup --output /safe/path/cbm-backup.zovaThe compact real-repository validation runner is:
scripts/zova-single-file-validation.shIt retains only a JSON report on success.
The current schema is CBM v7 on Zova format v9. It removes projection
tables, duplicate workspace FTS/rowmaps, compatibility-vector tables, and the
separate native norm table. Native topology edges carry compact CBM payloads,
and fresh full publication uses Zova's prepared builder;
CBM_MODE_INCREMENTAL computes and commits an atomic delta without clearing
the workspace or rewriting unchanged rows. Migration from v5/v7 uses a
verified temporary database and resumable atomic replacement. The final
same-binary TOPS → motive → rvault → CBM optimization gate
passes; storage is 45.0%–60.1% lower than the documented pre-v6 Zova baseline,
and true incremental publication performs no full clear or unchanged-row rewrite.
CBM builds against an immutable local snapshot in .zova-sdk, not the live
neighboring Zova checkout. Pin the currently built Zova library and headers
once, build the production binary, then build and run only the test groups you
request:
scripts/zova-pin-current.sh
scripts/zova-build-once.sh
scripts/zova-run-tests.sh zova mcpzova-build-once.sh does not compile tests. zova-run-tests.sh selects a
focused Zova, MCP, or pipeline runner when possible; running it without suite
arguments builds and executes the complete C test runner used by CI. Focused
runners share one cached production-support library, so later groups compile
only their own test sources.
Later changes under ../zova are ignored. Refresh the snapshot only when a
Zova update is intentionally being adopted:
scripts/zova-pin-current.sh --refreshThe wrapper keeps both CBM's Zig cache and the global Zig cache under
build/.zova-build-cache, and uses a build lock to reject overlapping builds.
It never writes the repository .zig-cache, so interrupted builds do not
poison the working tree. Real-repository validation keeps compact JSON
reports and deletes successful temporary databases, sidecars, logs, and caches.
It refuses to start with less than 8 GiB free by default; adjust that guard with
CBM_ZOVA_MIN_FREE_GB when necessary. Full four-repository, three-run gates are
promotion tests, not routine development tests.
| 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. |
| Tool | Description |
|---|---|
search_graph |
Structured search by label, name pattern, file pattern, degree filters. Pagination via limit/offset. |
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. |
search_code |
Grep-like text search within indexed project files. |
manage_adr |
CRUD for Architecture Decision Records. |
ingest_traces |
Ingest runtime traces to validate HTTP_CALLS edges. |
When Zova full authority is enabled, search_graph can search several repositories stored in the
shared Zova database in one request:
{"projects":["codebase-memory-mcp","AnotherFolder/codebase-memory-mcp"],"query":"update user profile"}Use {"projects":["*"]} to search every ready, healthy workspace. BM25, structural filters, and
semantic_query are ranked and paginated across the combined scope. Every result includes its
owning project; pass that value and the returned qualified_name to get_code_snippet.
Selectors come from canonical repository paths. The first registered repository claims its
directory basename. A later basename collision receives the shortest unique parent-qualified
name, such as AnotherFolder/codebase-memory-mcp. list_projects reports these selectors,
canonical roots, generations, and health.
This feature provides cross-repository discovery, not cross-workspace topology. query_graph and
trace_path remain scoped to one repository; sharing a database does not create graph edges
between unrelated workspaces.
Project, Package, Folder, File, Module, Class, Function, Method, Interface, Enum, Type, Route, Resource
CONTAINS_PACKAGE, CONTAINS_FOLDER, CONTAINS_FILE, DEFINES, DEFINES_METHOD, IMPORTS, CALLS, HTTP_CALLS, ASYNC_CALLS, IMPLEMENTS, HANDLES, USAGE, CONFIGURES, WRITES, MEMBER_OF, TESTS, USES_TYPE, FILE_CHANGES_WITH
get_code_snippet uses qualified names: <project>.<path_parts>.<name>. Use search_graph to discover them first.
query_graph is a read-only openCypher subset:
- Clauses:
MATCH,OPTIONAL MATCH, multipleMATCH,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 testn:Label, andEXISTS { (n)-[:TYPE]->() }(single-hop existence — great for dead-code, e.g.WHERE NOT EXISTS { (f)<-[:CALLS]-() }). - Aggregates:
count(+DISTINCT),sum,avg,min,max,collect. - Functions:
labels,type,id,keys,properties;toLower/toUpper/toString/toInteger/toFloat/toBoolean;size,length,trim/ltrim/rtrim,reverse;coalesce,substring,replace,left,right.
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.
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.
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 reset auto_index # reset to default| Variable | Default | Description |
|---|---|---|
CBM_ALLOWED_ROOT |
(unset) | Restrict index_repository to paths within this directory. When set, a repo_path that resolves (after symlink / .. resolution) outside this root is refused; unset imposes no restriction. 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. |
CBM_DIAGNOSTICS |
false |
Set to 1 or true to enable periodic diagnostics output to /tmp/cbm-diagnostics-<pid>.json. |
CBM_DOWNLOAD_URL |
(GitHub releases) | Override the download URL for updates. Used for testing or self-hosted deployments. |
CBM_LOG_LEVEL |
info |
Set the minimum log level. Accepted values (case-insensitive): debug, info, warn, error, none — or their numeric equivalents 0–4 matching the internal enum. Logs go to stderr; stdout is reserved for MCP JSON-RPC. |
CBM_WORKERS |
(detected) | Set the indexing worker count. 0 selects the sequential path; 1–256 selects an explicit worker count. Unset or invalid values use automatic detection. |
CBM_DUMP_VERIFY_MIN_RATIO |
0.5 |
After indexing, compare persisted SQLite node count to the in-memory dump count. When persisted nodes fall below this fraction of committed nodes (and committed > 50), index_repository returns status:"degraded" instead of silent indexed. Range 0–1; set 0 to disable. Invalid values are ignored with a warning. |
# Store indexes in a custom directory
export CBM_CACHE_DIR=~/my-projects/cbm-dataThe 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, hcl (terraform), html, ini, java, javascript, json, julia, kotlin, lean, lua, magma, makefile, markdown, matlab, meson, nix, objective-c (objc), ocaml, perl, php, protobuf, python, r, ruby, rust, scala, scss, sql, svelte, swift, toml, tsx, typescript, verilog, vimscript, vue, wolfram, xml, yaml, zig.
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.
All indexed projects persist as isolated workspaces in the shared
${CBM_CACHE_DIR:-$HOME/.cache/codebase-memory-mcp}/cbm.zova database. The
database uses WAL mode and survives agent and machine restarts. Pure-SQLite
per-project .db files are used only when the explicit compatibility mode
CBM_ZOVA_MODE=off is selected.
| 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 downloaded the ui variant and ran --ui=true. Check http://localhost:9749. |
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 static binary. 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 CALLS, USAGE, and RESOLVED_CALLS edges with 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# (new in v0.7.0) | global usings, file-scoped namespaces, records (incl. C# 12 primary constructors), LINQ method syntax, async Task<T> / ValueTask<T> unwrap, generic methods, this / base dispatch, var inference, common BCL stdlib |
| Go (sharpened in v0.7.0) | pre-built per-package cross-file registry, generics, embedded structs, interface satisfaction, package-aware import resolution |
| C / C++ (sharpened in v0.7.0) | pre-built per-language cross-file registry shared across C and C++; C side handles macros + typedef chains + header-vs-source linking; C++ side handles templates, namespaces, auto inference, and method resolution via class hierarchy |
| Java (new in v0.8.0) | imports (single-type, on-demand, static), class hierarchies with this / super dispatch, generics, annotations, overload matching by arity and parameter types, lambdas / method references bound to functional interfaces, field-type inference, common JDK stdlib |
| Kotlin (new in v0.8.0) | imports + same-package resolution, classes / objects / companion objects, extension functions, data classes, nullable-type unwrapping, scope functions (let / apply / run / also / with), infix calls, common stdlib |
| Rust (new in v0.8.0) | use declarations + module paths, impl blocks and trait methods, struct fields, generics with trait bounds, operator-trait desugaring, derive-macro method synthesis, UFCS static paths, common std prelude |
Two-layer architecture:
- Tree-sitter pass — fast, syntactic, runs for every one of the 158 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.
158 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.
src/
main.c Entry point (MCP stdio server + CLI + install/update/config)
mcp/ MCP server (14 tools, JSON-RPC 2.0, session detection, auto-index)
cli/ Install/uninstall/update/config (10 agents, hooks, instructions)
store/ Query/storage compatibility layer and cross-workspace search
zova/ Shared database, native graph/vector publication, migration, and operations
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/ Embedded HTTP server + 3D graph visualization
foundation/ Platform abstractions (threads, filesystem, logging, memory)
internal/cbm/ Vendored tree-sitter grammars (158 languages) + AST extraction engine
Indexing, storage, vector search, and graph queries run locally. The project does not upload source code or require a hosted database, API key, or model service. Release archives include SHA-256 checksums, and the installers verify the selected archive before extraction. See SECURITY.md for vulnerability reporting and the current security policy.
MIT