Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

Add comprehensive --help, update README with gitignore/LSP hybrid docs

Martin Vogelf92fff86d430
diff --git a/README.md b/README.md
index 500cb55e2..b249922fd 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
Single Go binary. No Docker, no external databases, no API keys. One command to install, say *"Index this project"* — done.
-Parses source code with [tree-sitter](https://tree-sitter.github.io/tree-sitter/), extracts functions, classes, modules, call relationships, and cross-service HTTP links. Exposes the graph through 12 MCP tools for use with Claude Code, Codex CLI, Cursor, Windsurf, Gemini CLI, VS Code, Zed, or any MCP-compatible client. Also includes a **CLI mode** for direct tool invocation from the shell — no MCP client needed.
+Parses source code with [tree-sitter](https://tree-sitter.github.io/tree-sitter/), extracts functions, classes, modules, call relationships, and cross-service HTTP links. Exposes the graph through 14 MCP tools for use with Claude Code, Codex CLI, Cursor, Windsurf, Gemini CLI, VS Code, Zed, or any MCP-compatible client. Also includes a **CLI mode** for direct tool invocation from the shell — no MCP client needed.
## Features
@@ -18,6 +18,8 @@ Parses source code with [tree-sitter](https://tree-sitter.github.io/tree-sitter/
- **One-command install**: `codebase-memory-mcp install` auto-detects Claude Code, Codex CLI, Cursor, Windsurf, Gemini CLI, VS Code, and Zed, registers the MCP server, and installs task-specific skills
- **Self-update**: `codebase-memory-mcp update` downloads the latest release, verifies checksums, and atomically swaps the binary
- **Task-specific skills**: 4 skills (exploring, tracing, quality, reference) that prescribe exact tool sequences — Claude Code automatically uses graph tools instead of defaulting to grep
+- **Go: tree-sitter + LSP hybrid**: Go gets enhanced cross-file type resolution via a built-in LSP-style type resolver that runs alongside tree-sitter parsing. This produces higher-confidence call edges by resolving method calls through interface embeddings, struct field access, and cross-package type inference. **This hybrid approach is coming soon for additional languages.**
+- **`.gitignore` + `.cbmignore` support**: Respects your full `.gitignore` hierarchy (nested files + `.git/info/exclude`). Add a `.cbmignore` for additional indexer-specific exclusions using gitignore-style patterns. Symlinks are always skipped.
- **Fast**: Sub-millisecond graph queries, incremental reindex 4x faster than full scan, optimized SQLite with LIKE pre-filtering for regex searches
- **Call graph**: Resolves function calls across files and packages (import-aware, type-inferred)
- **Cross-service HTTP linking**: Discovers REST routes (FastAPI, Gin, Express) and matches them to HTTP call sites with confidence scoring
@@ -243,7 +245,7 @@ Add the MCP server to your project's `.mcp.json` (per-project, recommended) or `
}
```
-Restart Claude Code after adding the config. Verify with `/mcp` — you should see `codebase-memory-mcp` listed with 12 tools.
+Restart Claude Code after adding the config. Verify with `/mcp` — you should see `codebase-memory-mcp` listed with 14 tools.
</details>
@@ -609,23 +611,36 @@ The skill files are embedded in the binary. If you prefer to install them manual
</details>
-## Ignoring Files (`.cgrignore`)
+## Ignoring Files
-Place a `.cgrignore` file in your project root to exclude directories or files from indexing. The syntax is one glob pattern per line (comments with `#`):
+File ignoring is **layered** — each layer stacks on top of the previous one:
+
+### 1. Hardcoded patterns (always active)
+
+Directories like `.git`, `node_modules`, `dist`, `__pycache__`, `.venv`, `.cache`, `.idea`, `.vscode`, `vendor`, and ~50 other unambiguous build/cache directories are always skipped. Symlinked files and directories are also always skipped (prevents duplicate indexing).
+
+### 2. `.gitignore` (automatic for git repos)
+
+The indexer respects your full `.gitignore` hierarchy — including nested `.gitignore` files in subdirectories and `.git/info/exclude`. No configuration needed; if a file is gitignored, it won't be indexed.
+
+### 3. `.cbmignore` (project-specific exclusions)
+
+Place a `.cbmignore` file in your project root to exclude additional files from indexing that aren't in `.gitignore`. Uses full **gitignore-style pattern syntax** (globstar `**`, negation `!`, directory-only trailing `/`):
```
-# .cgrignore
-generated
-vendor
-__pycache__
+# .cbmignore — additional patterns for codebase-memory-mcp indexing
+generated/
*.pb.go
-testdata
-fixtures
+*_generated.*
+testdata/
+docs/api/
```
-Patterns are matched against both directory names and relative paths using Go's `filepath.Match` syntax. Directories matching a pattern are skipped entirely (including all contents).
+`.cbmignore` stacks on top of `.gitignore` — patterns in `.cbmignore` are additive exclusions. This is useful for files that should be in git but don't need to be in the code graph (e.g., generated code, large data fixtures, vendored docs).
+
+### 4. `.cgrignore` (legacy, backward-compatible)
-The following directories are **always ignored** regardless of `.cgrignore`: `.git`, `node_modules`, `vendor`, `__pycache__`, `.mypy_cache`, `.venv`, `dist`, `build`, `.cache`, `.idea`, `.vscode`, and others.
+The older `.cgrignore` format is still supported. It uses simpler `filepath.Match` glob patterns (one per line). If you have an existing `.cgrignore`, it will continue to work alongside `.cbmignore`.
## Persistence
@@ -683,14 +698,14 @@ cmd/codebase-memory-mcp/ Entry point (MCP stdio server + CLI mode + install/upd
internal/
store/ SQLite graph storage (nodes, edges, traversal, search, architecture, Louvain clustering)
lang/ Language specs (64 languages, tree-sitter node types)
- cbm/ Vendored tree-sitter C grammars (64 languages) and AST extraction engine
+ cbm/ Vendored tree-sitter C grammars (64 languages), AST extraction engine, and LSP-style type resolver (Go hybrid)
pipeline/ Multi-pass indexing (structure → definitions → calls → HTTP links → config links → communities → tests)
httplink/ Cross-service HTTP route/call-site matching
cypher/ Cypher query lexer, parser, planner, executor
selfupdate/ GitHub release checking, version comparison, asset download
- tools/ MCP tool handlers (12 tools) + CLI dispatch
+ tools/ MCP tool handlers (14 tools) + CLI dispatch
watcher/ Background auto-sync (mtime+size polling, adaptive intervals)
- discover/ File discovery with .cgrignore support
+ discover/ File discovery with .gitignore, .cbmignore, and symlink handling
fqn/ Qualified name computation
traces/ OpenTelemetry trace ingestion for HTTP_CALLS validation
```
diff --git a/cmd/codebase-memory-mcp/main.go b/cmd/codebase-memory-mcp/main.go
index 899ea5b56..51b40640c 100644
--- a/cmd/codebase-memory-mcp/main.go
+++ b/cmd/codebase-memory-mcp/main.go
@@ -7,8 +7,11 @@ import (
"log"
"os"
"path/filepath"
+ "runtime/debug"
+ "runtime/pprof"
"strings"
+ "github.com/DeusData/codebase-memory-mcp/internal/cbm"
"github.com/DeusData/codebase-memory-mcp/internal/store"
"github.com/DeusData/codebase-memory-mcp/internal/tools"
"github.com/modelcontextprotocol/go-sdk/mcp"
@@ -19,20 +22,37 @@ var version = "dev"
func main() {
tools.SetVersion(version)
- if len(os.Args) > 1 {
- switch os.Args[1] {
+ // Parse global flags before subcommand dispatch.
+ var pprofOnExit string
+ var remaining []string
+ for _, a := range os.Args[1:] {
+ switch {
+ case strings.HasPrefix(a, "--pprof-on-exit="):
+ pprofOnExit = strings.TrimPrefix(a, "--pprof-on-exit=")
+ default:
+ remaining = append(remaining, a)
+ }
+ }
+
+ if len(remaining) > 0 {
+ switch remaining[0] {
case "--version":
fmt.Println("codebase-memory-mcp", version)
os.Exit(0)
+ case "--help", "-h", "help":
+ printTopLevelHelp()
+ os.Exit(0)
case "install":
- os.Exit(runInstall(os.Args[2:]))
+ os.Exit(runInstall(remaining[1:]))
case "uninstall":
- os.Exit(runUninstall(os.Args[2:]))
+ os.Exit(runUninstall(remaining[1:]))
case "update":
- os.Exit(runUpdate(os.Args[2:]))
+ os.Exit(runUpdate(remaining[1:]))
+ case "config":
+ os.Exit(runConfig(remaining[1:]))
case "cli":
- if len(os.Args) >= 3 {
- os.Exit(runCLI(os.Args[2:]))
+ if len(remaining) >= 2 {
+ os.Exit(runCLI(remaining[1:]))
}
}
}
@@ -42,19 +62,255 @@ func main() {
log.Fatalf("store router err=%v", err)
}
- srv := tools.NewServer(router)
+ cfg, err := store.OpenConfig()
+ if err != nil {
+ log.Fatalf("config err=%v", err)
+ }
+
+ // Apply GOMEMLIMIT from config (e.g. "2G", "512M").
+ if memLimit := cfg.Get(store.ConfigMemLimit, ""); memLimit != "" {
+ if limit, parseErr := parseByteSize(memLimit); parseErr != nil {
+ log.Printf("config: invalid mem_limit %q: %v", memLimit, parseErr)
+ } else {
+ debug.SetMemoryLimit(limit)
+ }
+ }
+
+ srv := tools.NewServer(router, tools.WithConfig(cfg))
ctx, cancel := context.WithCancel(context.Background())
+ router.StartEvictor(ctx)
srv.StartWatcher(ctx)
runErr := srv.MCPServer().Run(ctx, &mcp.StdioTransport{})
cancel()
+
+ // Shutdown frees the calling thread's TLS tree-sitter parser pool.
+ // Main goroutine doesn't run extraction, so this frees 0 bytes at runtime,
+ // but signals clean shutdown for Valgrind/ASan runs.
+ cbm.Shutdown()
+
+ if pprofOnExit != "" {
+ writeHeapProfile(pprofOnExit)
+ }
+
+ cfg.Close()
router.CloseAll()
if runErr != nil {
log.Fatalf("server err=%v", runErr)
}
}
+// writeHeapProfile writes a heap profile to the given path.
+func writeHeapProfile(path string) {
+ f, err := os.Create(path) //nolint:gosec // path from trusted internal pprof flag
+ if err != nil {
+ log.Printf("pprof: create %s err=%v", path, err)
+ return
+ }
+ defer f.Close()
+ if err := pprof.WriteHeapProfile(f); err != nil {
+ log.Printf("pprof: write err=%v", err)
+ return
+ }
+ log.Printf("pprof: heap profile written to %s", path)
+}
+
+// parseByteSize parses human-readable byte sizes like "1G", "512M", "2048K".
+func parseByteSize(s string) (int64, error) {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return 0, fmt.Errorf("empty size")
+ }
+ multiplier := int64(1)
+ switch {
+ case strings.HasSuffix(s, "G") || strings.HasSuffix(s, "g"):
+ multiplier = 1 << 30
+ s = s[:len(s)-1]
+ case strings.HasSuffix(s, "M") || strings.HasSuffix(s, "m"):
+ multiplier = 1 << 20
+ s = s[:len(s)-1]
+ case strings.HasSuffix(s, "K") || strings.HasSuffix(s, "k"):
+ multiplier = 1 << 10
+ s = s[:len(s)-1]
+ }
+ var n int64
+ if _, err := fmt.Sscanf(s, "%d", &n); err != nil {
+ return 0, fmt.Errorf("parse %q: %w", s, err)
+ }
+ if n <= 0 {
+ return 0, fmt.Errorf("size must be positive")
+ }
+ return n * multiplier, nil
+}
+
+func printTopLevelHelp() {
+ fmt.Fprintf(os.Stderr, "codebase-memory-mcp %s — Code knowledge graph MCP server\n\n", version)
+ printHelpUsage()
+ printHelpTools()
+ printHelpIgnoring()
+ printHelpCLI()
+}
+
+func printHelpUsage() {
+ fmt.Fprint(os.Stderr, `Usage:
+ codebase-memory-mcp Start the MCP server (stdio transport)
+ codebase-memory-mcp cli <tool> [json_args] Invoke a tool directly from the shell
+ codebase-memory-mcp install [--dry-run] Auto-detect and configure MCP clients
+ codebase-memory-mcp uninstall Remove MCP registrations and skills
+ codebase-memory-mcp update Self-update to the latest release
+ codebase-memory-mcp config <command> Manage server configuration
+ codebase-memory-mcp --version Print version and exit
+ codebase-memory-mcp --help Show this help
+
+Supported MCP clients:
+ Claude Code, Codex CLI, Cursor, Windsurf, Gemini CLI, VS Code, Zed
+
+Language support (64 languages):
+ Tree-sitter AST parsing for: Python, Go, JavaScript, TypeScript, TSX, Rust,
+ Java, C++, C#, C, PHP, Lua, Scala, Kotlin, Ruby, Bash, Zig, Elixir, Haskell,
+ OCaml, Objective-C, Swift, Dart, Perl, Groovy, Erlang, R, Clojure, F#, Julia,
+ Vim Script, Nix, Common Lisp, Elm, Fortran, CUDA, COBOL, Verilog, Emacs Lisp,
+ MATLAB, Lean 4, FORM, Magma, Wolfram, HTML, CSS, SCSS, YAML, TOML, HCL, SQL,
+ Dockerfile, JSON, XML, Markdown, Makefile, CMake, Protobuf, GraphQL, Vue,
+ Svelte, Meson, GLSL, INI
+
+ Go uses a tree-sitter + LSP hybrid methodology for enhanced cross-file type
+ resolution and call graph accuracy. This hybrid approach is coming soon for
+ additional languages.
+
+`)
+}
+
+func printHelpTools() {
+ fmt.Fprint(os.Stderr, `MCP tools (14):
+
+ index_repository — Index a repo into the knowledge graph
+ {"repo_path": "/path/to/repo", "mode": "full|fast"}
+ repo_path: absolute path (optional — defaults to session project root)
+ mode: "full" (default) or "fast" (skips generated code, test fixtures, large files)
+
+ index_status — Check indexing status of a project
+ {"project": "my-project"}
+ Returns: status (not_indexed/indexing/ready), node/edge counts, timestamps
+
+ list_projects — List all indexed projects
+ {} (no parameters)
+ Returns: project names, node/edge counts, indexed_at timestamps
+
+ delete_project — Remove a project and all its graph data (irreversible)
+ {"project_name": "my-project"}
+
+ search_graph — Structural search with filters
+ {"label": "Function", "name_pattern": ".*Handler.*", "project": "my-api"}
+ label: Function, Class, Module, Method, Interface, Enum, Type, File, Route
+ name_pattern: regex on short name (case-insensitive by default)
+ qn_pattern: regex on qualified name (e.g. ".*services\\.order\\..*")
+ file_pattern: glob for file path (e.g. "*.py", "**/services/**")
+ relationship: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, IMPLEMENTS, etc.
+ direction: inbound, outbound, any (for degree filtering)
+ min_degree/max_degree: edge count filters (e.g. max_degree=0 for dead code)
+ exclude_entry_points: true to skip route handlers/main() in dead code search
+ limit (default 10), offset: pagination (response includes has_more, total)
+ case_sensitive: false (default) — set true for exact case matching
+
+ search_code — Grep-like text search within indexed files
+ {"pattern": "TODO|FIXME", "regex": true, "file_pattern": "*.go"}
+ pattern: search text (case-insensitive by default)
+ regex: true to enable regex (default false)
+ file_pattern: glob to filter files
+ max_results (default 10), offset: pagination
+
+ trace_call_path — BFS call chain traversal
+ {"function_name": "ProcessOrder", "direction": "both", "depth": 3}
+ function_name: exact name (use search_graph first to find it)
+ direction: outbound (what it calls), inbound (what calls it), both
+ depth: 1-5 (default 3)
+ risk_labels: true to add CRITICAL/HIGH/MEDIUM/LOW classification
+ min_confidence: 0.0-1.0 threshold for CALLS edges
+
+ detect_changes — Git diff → affected symbols + blast radius
+ {"scope": "unstaged", "depth": 3}
+ scope: unstaged (default), staged, all, branch
+ base_branch: for scope=branch (default "main")
+ depth: 1-5 (default 3) for blast radius tracing
+
+ query_graph — Execute Cypher-like graph queries (read-only)
+ {"query": "MATCH (f:Function)-[:CALLS]->(g) WHERE f.name = 'main' RETURN g.name LIMIT 20"}
+ Supports: MATCH, WHERE (=, <>, >, <, =~, CONTAINS, STARTS WITH), RETURN,
+ ORDER BY, LIMIT, COUNT, DISTINCT, variable-length paths (*1..3)
+ max_rows: default 200, max 10000
+
+ get_graph_schema — Node/edge counts and relationship patterns
+ {"project": "my-project"} (project optional)
+ Returns: node label counts, edge type counts, sample names
+
+ get_code_snippet — Read source code by qualified name
+ {"qualified_name": "myproject.cmd.server.main.HandleRequest"}
+ Accepts: full QN, partial suffix ("main.HandleRequest"), or short name
+ auto_resolve: true to auto-pick from <=2 ambiguous candidates
+ include_neighbors: true to get caller/callee name lists
+
+ get_architecture — Codebase overview
+ {"aspects": ["all"], "project": "my-project"}
+ aspects: languages, packages, entry_points, routes, hotspots, boundaries,
+ services, layers, clusters, file_tree, adr (or "all" for everything)
+
+ manage_adr — CRUD for Architecture Decision Records
+ {"mode": "store", "content": "## PURPOSE\n..."}
+ mode: get, store, update, delete
+ content: full ADR text (for store)
+ sections: {"PATTERNS": "..."} (for update — unmentioned sections preserved)
+ Fixed sections: PURPOSE, STACK, ARCHITECTURE, PATTERNS, TRADEOFFS, PHILOSOPHY
+
+ ingest_traces — Ingest OpenTelemetry JSON traces
+ {"traces": [...]} (OTLP format spans)
+ Validates HTTP_CALLS edges with runtime data, boosts confidence
+
+`)
+}
+
+func printHelpIgnoring() {
+ fmt.Fprint(os.Stderr, `File ignoring (layered):
+ 1. Hardcoded patterns Always-on: .git, node_modules, dist, __pycache__, etc.
+ 2. .gitignore Full gitignore hierarchy (nested files + .git/info/exclude)
+ 3. .cbmignore Repo-root file with gitignore-style patterns, stacks on top
+ 4. .cgrignore Legacy glob patterns (backward-compatible)
+
+ Symlinked files and directories are always skipped.
+
+`)
+}
+
+func printHelpCLI() {
+ fmt.Fprint(os.Stderr, `CLI invocation:
+ codebase-memory-mcp cli <tool_name> '<json_args>'
+ codebase-memory-mcp cli --raw <tool_name> '<json_args>' (full JSON output)
+
+ Tools are called with a single JSON object as the argument. All parameters
+ are passed as JSON keys. String values must be quoted. Arrays use JSON syntax.
+
+CLI examples:
+ 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_call_path '{"function_name": "main", "direction": "outbound"}'
+ codebase-memory-mcp cli search_code '{"pattern": "TODO", "file_pattern": "*.go"}'
+ codebase-memory-mcp cli get_architecture '{"aspects": ["languages", "packages"]}'
+ codebase-memory-mcp cli --raw list_projects | jq .
+ codebase-memory-mcp cli get_code_snippet '{"qualified_name": "HandleRequest"}'
+
+Configuration:
+ codebase-memory-mcp config list Show all settings
+ codebase-memory-mcp config set <key> <val> Set a config value
+ codebase-memory-mcp config get <key> Get a config value
+
+Data storage:
+ ~/.cache/codebase-memory-mcp/ SQLite databases (WAL mode, persists across restarts)
+
+For more information: https://github.com/DeusData/codebase-memory-mcp
+`)
+}
+
func runCLI(args []string) int {
// Parse flags
raw := false