Skip to main content
Glama
README.md
# codebase-memory-mcp

A Docker stdio-based MCP Server providing **code graph intelligence** and memory capabilities.  
Inspired by [DeusData/codebase-memory-mcp](https://github.com/DeusData/codebase-memory-mcp), optimized for token efficiency.

## šŸš€ Token Efficiency

| Feature | Traditional | This Project |
|---------|-------------|--------------|
| Find callers of a function | ~50K tokens (grep + read files) | **~500 tokens** (single `trace_calls`) |
| Project architecture overview | ~100K tokens | **~1K tokens** (`get_architecture`) |
| Dead code detection | Manual review | **Automated** (`find_dead_code`) |

**Estimated 20-50x token reduction** for structural queries.

---

## Features (19 Tools)

### šŸ“Š Graph Intelligence (NEW - 13 tools)

| Tool | Description |
|------|-------------|
| `index_project` | Index codebase into searchable graph (supports TypeScript, JavaScript, Python, Go, Rust, Java) |
| `sync_index` | Incrementally update index based on file changes |
| `list_projects` | List all indexed projects with statistics |
| `delete_project` | Remove a project index |
| `index_status` | Check indexing status and statistics |
| `search_symbols` | Search functions, classes, methods by name pattern |
| `trace_calls` | Find callers/callees of a function (call tree) |
| `get_symbol_info` | Detailed info about a symbol with relationships |
| `list_file_symbols` | List all symbols in a file |
| `find_dead_code` | Detect potentially unused functions |
| `get_architecture` | High-level project overview (modules, hotspots, entry points) |
| `get_code_snippet` | Read source code for a specific symbol |
| `query_graph` | Execute custom SQL queries on the graph |

### šŸ’¾ Memory (Original - 4 tools)

| Tool | Description |
|------|-------------|
| `store_memory` | Store or update memory entries (supports tags) |
| `retrieve_memory` | Search memories by keyword/tag |
| `list_memories` | List all stored memories |
| `delete_memory` | Delete a specific memory |

### šŸ” Codebase Search (Original - 2 tools)

| Tool | Description |
|------|-------------|
| `search_codebase` | Search code using ripgrep (supports regex) |
| `summarize_file` | Read file content for LLM summarization |

---

## Token-Optimization Roadmap

This roadmap focuses on generic mechanisms that reduce AI token usage by replacing repeated grep/read/reason loops with reusable structured evidence.

### Low Cost, High Return āœ… COMPLETED

| Item | Status | What was implemented |
|------|--------|---------------------|
| Tool routing policy | āœ… | `.github/copilot-instructions.md` with decision tree and best practices |
| Evidence-first responses | āœ… | `get_project_structure` returns purpose-grouped overview (~500 tokens vs ~50K) |
| File summary cache | āœ… | `file_summaries` table with purpose, exports, imports, symbols, dependencies, side effects |
| File summary tools | āœ… | `get_file_summary`, `list_file_summaries`, `search_file_summaries`, `get_project_structure` |

**Delivered in v2.1.0:**
- `file_summaries` schema keyed by `project + path + hash`
- Auto-generation during `index_project` / `sync_index`
- 4 new MCP tools for summary queries
- Token savings: 10-100x for common exploration tasks

### Mid Term

| Item | What to implement | Expected benefit |
|------|-------------------|------------------|
| Ownership relationships | Add `owner_symbol_id` or `parent_symbol_id` for methods, nested functions, and file/module ownership | Enables exact class/method and module/function queries with less fallback reading |
| Expand graph edge types | Add `IMPORTS`, `DEFINES`, `IMPLEMENTS`, `USES_CONFIG`, `READS_ENV` | Improves architecture and impact analysis from ~5x to ~20x+ on common questions |
| Incremental semantic summaries | Refresh only changed file and symbol summaries during `sync_index` | Reduces repeated recomputation and stale context reads in multi-turn sessions |
| Change-impact tool | Map git diff to affected symbols, direct callers, nearby files, and likely test targets | Reduces review and regression-analysis token cost by ~5-20x |
| Query templates | Provide first-class tools for recurring tasks like `list_entry_points`, `find_hotspots`, `list_module_dependencies` | Avoids ad hoc SQL or raw file reading for routine analysis |

**Concrete deliverables**
- Extend `symbols` schema to persist ownership relationships directly
- Add edge builders in the parser/indexer for imports and definitions
- Add a `detect_changes` MCP tool backed by git diff + graph traversal

### Long Term

| Item | What to implement | Expected benefit |
|------|-------------------|------------------|
| Hybrid retrieval | Combine structural graph search with semantic/vector candidate retrieval | Improves ambiguous or concept-level search by ~2-6x |
| Cross-file responsibility summaries | Build module-level summaries from grouped files and symbols | Lets AI answer design questions without opening many files |
| Precomputed risk and refactor candidates | Detect cycles, oversized modules, unstable hotspots, dead-code clusters | Makes maintenance guidance nearly zero-search for common cases |
| Test and route awareness | Model test ownership, API handlers, jobs, and config-driven execution paths | Greatly reduces token cost for impact and regression questions |
| Cross-repo artifact reuse | Persist compressed graph/summaries for team reuse or CI-produced bootstrap artifacts | Eliminates repeated cold-start indexing for shared codebases |

**Concrete deliverables**
- Add a vector index for file/symbol summaries and blend retrieval with graph constraints
- Introduce module and route nodes in the graph model
- Export reusable project graph artifacts to accelerate first-time sessions

### Prioritized Execution Order

1. ~~Add tool routing policy and evidence-first response shaping~~ āœ…
2. ~~Add file summary cache keyed by file hash~~ āœ…
3. Add `owner_symbol_id` / `parent_symbol_id` to support exact ownership queries
4. Add `IMPORTS` / `DEFINES` graph edges
5. Add `detect_changes` for git-aware impact analysis
6. Add hybrid semantic + structural retrieval

### Success Metrics

Track roadmap progress using these measurable outcomes:

| Metric | Current target | Long-term target |
|--------|----------------|------------------|
| Tokens per architecture question | 20-50x lower than grep/read flow | 50-100x lower |
| Tool calls per exploration task | 2-5 calls | 1-3 calls |
| Re-read rate for unchanged files | Reduced by file-hash summary cache | Near-zero in multi-turn sessions |
| Diff impact analysis time | Manual or multi-step | Single tool call |

---

## Quick Start

### Build Docker Image

```bash
cd /path/to/codebase-memory-mcp
podman build -t codebase-memory-mcp .
```

### With Persistent Data (Recommended)

```bash
# Create data directory for persistent indexes
mkdir -p ~/.codebase-memory-data

podman run -i --rm \
  -v "${PWD}:/app/workspace:ro" \
  -v "$HOME/.codebase-memory-data:/app/data" \
  codebase-memory-mcp
```

---

## VS Code Configuration

Create `.vscode/mcp.json` in your project root:

### Windows Host + WSL Container (Recommended)

For VS Code running on Windows, with Podman/Docker inside WSL:

```json
{
  "servers": {
    "codebase-memory": {
      "type": "stdio",
      "command": "wsl",
      "args": [
        "-d", "Ubuntu-22.04",
        "podman", "run", "-i", "--rm",
        "-v", "/mnt/c/Users/YourName/Projects/my-project:/app/workspace:ro",
        "-v", "/home/youruser/.codebase-memory-data:/app/data",
        "codebase-memory-mcp"
      ]
    }
  }
}
```

**Important for Windows + WSL:**
1. Replace `Ubuntu-22.04` with your WSL distro (run `wsl -l -v` to list)
2. Replace `/mnt/c/Users/YourName/Projects/my-project` with your Windows project path converted to WSL format:
   - `C:\Users\YourName\Projects` → `/mnt/c/Users/YourName/Projects`
   - `D:\code\myapp` → `/mnt/d/code/myapp`
3. Create persistent data directory in WSL:
   ```bash
   wsl -d Ubuntu-22.04 mkdir -p ~/.codebase-memory-data
   ```

### Windows Host + WSL (Dynamic Workspace Path)

For projects stored in Windows filesystem with dynamic path:

```json
{
  "servers": {
    "codebase-memory": {
      "type": "stdio",
      "command": "wsl",
      "args": [
        "-d", "Ubuntu-22.04",
        "bash", "-c",
        "podman run -i --rm -v \"$(wslpath '${workspaceFolder}'):/app/workspace:ro\" -v \"$HOME/.codebase-memory-data:/app/data\" codebase-memory-mcp"
      ]
    }
  }
}
```

> Note: `${workspaceFolder}` is a VS Code variable that expands to the Windows path. The `wslpath` command converts it to WSL format.

### Linux / macOS (Native)

### With Persistent Storage (Recommended)

```json
{
  "servers": {
    "codebase-memory": {
      "type": "stdio",
      "command": "podman",
      "args": [
        "run", "-i", "--rm",
        "-v", "${workspaceFolder}:/app/workspace:ro",
        "-v", "${env:HOME}/.codebase-memory-data:/app/data",
        "codebase-memory-mcp"
      ]
    }
  }
}
```

### Without Persistence (Ephemeral)

```json
{
  "servers": {
    "codebase-memory": {
      "type": "stdio",
      "command": "podman",
      "args": [
        "run", "-i", "--rm",
        "-v", "${workspaceFolder}:/app/workspace:ro",
        "codebase-memory-mcp"
      ]
    }
  }
}
```

---

## Usage Examples

### 1. Index Your Project (First Time)

```
You: "Index this project"
AI: [calls index_project]
→ āœ… Indexed 150 files in 2.3s
   šŸ“Š Total: 1,234 symbols, 567 edges
   šŸ“ Types: function=456, class=78, method=234, ...
```

### 2. Find Who Calls a Function

```
You: "Who calls the processOrder function?"
AI: [calls trace_calls(function_name="processOrder", direction="inbound")]
→ Callers of processOrder (depth=3)
   → OrderController.handleOrder (method) - src/controllers/order.ts:45
     → Router.post (function) - src/routes/index.ts:12
   → BatchProcessor.run (method) - src/jobs/batch.ts:89
```

### 3. Get Architecture Overview

```
You: "Give me an overview of this project's architecture"
AI: [calls get_architecture]
→ # šŸ—ļø Architecture Overview: default
   ## Statistics
   - Files: 45
   - Symbols: 1,234
   - Relationships: 567
   
   ## Hotspots (most called)
   1. validateInput - 23 callers
   2. formatResponse - 18 callers
   ...
```

### 4. Find Dead Code

```
You: "Find any potentially unused functions"
AI: [calls find_dead_code]
→ āš ļø Potentially Dead Code (12 functions with no callers)
   - legacyHandler - src/handlers/old.ts:45
   - deprecatedUtil - src/utils/deprecated.ts:12
   ...
```

### 5. Custom Graph Query

```
You: "Show me all classes and their method counts"
AI: [calls query_graph]
→ SELECT 
     (SELECT name FROM symbols WHERE id = s.id AND type = 'class') as class_name,
     COUNT(*) as method_count
   FROM symbols s
   WHERE type = 'method'
   GROUP BY parent
```

---

## Supported Languages

| Language | AST Parsing | Call Graph |
|----------|-------------|------------|
| TypeScript | āœ… Full (tree-sitter) | āœ… |
| JavaScript | āœ… Full (tree-sitter) | āœ… |
| Python | āœ… Full (tree-sitter) | āœ… |
| Go | ⚔ Regex fallback | ⚔ |
| Rust | ⚔ Regex fallback | ⚔ |
| Java | ⚔ Regex fallback | ⚔ |
| Others | ⚔ Regex fallback | ⚔ |

---

## Claude Desktop Configuration

Edit `%APPDATA%\Claude\claude_desktop_config.json` (Windows) or `~/.config/Claude/claude_desktop_config.json` (macOS/Linux):

```json
{
  "mcpServers": {
    "codebase-memory": {
      "command": "podman",
      "args": [
        "run", "-i", "--rm",
        "-v", "/path/to/your/project:/app/workspace:ro",
        "-v", "/path/to/.codebase-memory-data:/app/data",
        "codebase-memory-mcp"
      ]
    }
  }
}
```

---

## Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `DATA_PATH` | `/app/data` | SQLite database directory |
| `WORKSPACE_PATH` | `/app/workspace` | Mounted codebase root directory |
| `MEMORY_DB_PATH` | `$DATA_PATH/memory.db` | Full path to database file |

---

## Directory Structure

```
Inside container:
/app
ā”œā”€ā”€ dist/           # Compiled JS
ā”œā”€ā”€ node_modules/
ā”œā”€ā”€ data/           # SQLite DB (persist via volume mount!)
│   └── memory.db   # Contains: memories, symbols, edges, indexed_files
└── workspace/      # Project code (mounted via -v)
    └── ...
```

---

## Verify Installation

### Test MCP Server Startup

```bash
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}\n{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}\n' \
  | podman run -i --rm codebase-memory-mcp
```

### Confirm Tools Count

```bash
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}\n{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}\n' \
  | podman run -i --rm codebase-memory-mcp 2>/dev/null | tail -1 | jq '.result.tools | length'
```

Output: `19`

---

## Comparison with DeusData/codebase-memory-mcp

| Feature | DeusData | This Project |
|---------|----------|--------------|
| Language | C (native binary) | TypeScript (Node.js) |
| Token Reduction | 120x | 20-50x |
| Languages | 158 | 3 full + regex fallback |
| Deployment | Single binary | Docker container |
| Customization | Limited | Easy to extend |
| Memory | Releases after indexing | Persistent |

**Choose This Project If:**
- You want easy customization and extension
- You prefer Docker-based deployment
- Your codebase is primarily TypeScript/Python/Go
- You want to learn MCP development

**Choose DeusData If:**
- You need maximum token efficiency
- You have a large monorepo (millions of LOC)
- You need 158 language support
- You want zero-dependency deployment

---

## License

MIT

```bash
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}\n{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}\n' \
  | docker run -i --rm codebase-memory-mcp 2>/dev/null | tail -1 | jq '.result.tools[].name'
```

Output:
```
"store_memory"
"retrieve_memory"
"list_memories"
"delete_memory"
"search_codebase"
"summarize_file"
```

### Verify AI Can Use Tools

Once configured in VS Code or Claude Desktop, test with these prompts:

**Test 1: Store and retrieve memory**
```
Please store a memory with key "test" and content "Hello MCP", then list all memories.
```

Expected: AI calls `store_memory` then `list_memories`, showing the stored entry.

**Test 2: Search codebase**
```
Search for "function" in the codebase.
```

Expected: AI calls `search_codebase` and returns matching lines.

**Test 3: Summarize file**
```
Summarize the package.json file.
```

Expected: AI calls `summarize_file` and provides a summary of dependencies.

**Troubleshooting**
- If tools don't appear: Check MCP panel in VS Code (View → MCP Servers) or restart the editor
- If container fails: Run `docker run -i --rm codebase-memory-mcp` manually to see errors
- If path mount fails: Verify the workspace path exists and is accessible

---

## FAQ

### Q: When does memory disappear?
A: Memory is cleared each time the container exits (conversation ends or VS Code restarts). This is by design, allowing AI to re-understand the project each session.

### Q: How to auto-initialize memory?
A: Use `.github/copilot-instructions.md` to set instructions, or explicitly request memory initialization at conversation start. See "Auto-Initialize Memory on Each Session" section above.

### Q: What if I need persistent memory?
A: Add volume mount back:
```json
"args": [
  "run", "-i", "--rm",
  "-v", "codebase-memory-data:/app/data",
  "-v", "${workspaceFolder}:/app/workspace:ro",
  "codebase-memory-mcp"
]
```
Then run `podman volume create codebase-memory-data`.

### Q: Windows path conversion issues?
Docker Desktop automatically handles `C:\` → `/c/` conversion. For WSL Docker, store projects in WSL filesystem (e.g., `/home/user/projects`) to avoid path issues.