Skip to main content
Glama
obsidian-memory-mcp

obsidian-memory-mcp

by BoiDG
README.md
# obsidian-memory-mcp

A lightweight, **100% local Hybrid Memory & RAG MCP server** + `/handoff` & `/resume` skill workflow that turns an Obsidian vault into a structured, context-budgeted memory system for AI coding agents (**Cursor, Claude Code, Codex, OpenCode, T3 Code**).

Designed specifically for models with smaller context windows (e.g., **200k–256k**) where starting a fresh session before compaction beats degraded long chats — **without** burning 20–50k tokens re-reading massive living docs on every turn.

---

## Why This Exists

1. **Full-file loading eats small context windows fast:** Loading an 80–180 KB living KB + recent handoffs dumps **20k–55k tokens** into turn 1 — and every token gets re-sent on every subsequent turn.
2. **Vector-only RAG struggles with developer notes:** Dev handoffs are dense with exact symbols (`StripeWebhookSignatureValidator`, migration IDs, table names, GUIDs). Hybrid **SQLite FTS5 BM25 + offline ONNX embeddings (Reciprocal Rank Fusion)** handles both exact code identifiers and conceptual queries in **~10–25 ms** with zero cloud API keys and no Ollama daemon.
3. **Markdown-first, read-only MCP:** Obsidian remains your source of truth. The MCP never mutates your notes — it stores its SQLite + ONNX cache in your OS local-data directory (outside Nextcloud/iCloud/Dropbox sync).

---

## The 3-Tier Obsidian Memory Pattern

```text
your-vault/
├── acme-api/                          <-- becomes scope `acme-api`
│   ├── 00 Acme API Knowledge Base.md  <-- Tier 1: Living KB (current truth)
│   ├── billing-migration-task.md      <-- Tier 2: Multi-session task contract
│   └── 2026-03-10-1430-...-handoff.md <-- Tier 3: Frozen session snapshots
└── web-app/                           <-- becomes scope `web-app`
    ├── WEB-APP.md                     <-- Tier 1: Central index table
    └── 2026-03-12-0915-...-handoff.md <-- Tier 3: Frozen session snapshots
```

### Architecture

```mermaid
flowchart TD
    Agent["Fresh Agent Session (Cursor / Claude / Codex / T3 Code)"]
    Resume["/resume skill (boot ~2-4k tokens)"]
    Handoff["/handoff skill (save + sync index + reindex)"]

    subgraph MCP ["obsidian-memory-mcp (Python · MCP 2.x stdio · Thread-Safe)"]
        Tools["7 Lean Budgeted Tools"]
        Retriever["Hybrid RRF (SQLite FTS5 BM25 + ONNX Cosine + Authority + Recency)"]
        Indexer["Incremental Indexer (mtime + sha256 + chunk hash cache)"]
        Guard["Explicit Path Allowlist + Hard Private/ Denylist"]
    end

    DB[("Local SQLite + ONNX Model Cache\n(Outside Cloud Sync)")]
    Vault["Obsidian Vaults (Read-Only from MCP)"]

    Agent --> Resume --> Tools
    Agent --> Handoff --> Tools
    Tools --> Retriever --> DB
    Tools --> Indexer --> Guard --> Vault
    Indexer --> DB
```

---

## Quick Start (60 Seconds)

Requires Python 3.11–3.13 and [`uv`](https://docs.astral.sh/uv/).

```bash
git clone https://github.com/BoiDG/obsidian-memory-mcp.git
cd obsidian-memory-mcp
uv sync --extra dev
```

### Option A — Try the included demo vault first

```bash
uv run obsidian-memory --config config.example.toml index
uv run obsidian-memory --config config.example.toml scopes
uv run obsidian-memory --config config.example.toml brief --scope acme-api --task billing-migration-task
uv run obsidian-memory --config config.example.toml search "StripeWebhookSignatureValidator" --scope acme-api
uv run obsidian-memory --config config.example.toml audit
```

### Option B — Initialize for your own Obsidian vault

```bash
uv run obsidian-memory init \
  --vault "/path/to/Obsidian/DevNotes" \
  --install-skills
```

This command:
1. Writes a local `config.toml` (gitignored so personal paths never leak).
2. Copies the reusable `/handoff` and `/resume` skills to `~/.agents/skills/` (use `--skills-dir ~/.cursor/skills` if needed).
3. Prints the exact JSON block to paste into `~/.cursor/mcp.json` (or Claude Code / Codex MCP config).

Then warm up the local ONNX embedding model (`BAAI/bge-small-en-v1.5`, ~65 MB cached once offline) and build the index:

```bash
uv run obsidian-memory index
```

---

## Daily Workflow

### 1. Start a fresh session (before compaction hurts quality)
```text
/resume acme-api
```
or for a multi-session task:
```text
/resume acme-api billing-migration-task
```
Calls `get_session_brief` once (~2k tokens): loads only the latest handoff's Summary + Next actions + Decisions, active task contract, and an outline of the central KB (never the full 100 KB file).

### 2. Query past sessions & large KBs mid-session
```text
Use obsidian-memory (scope: acme-api) to check how StripeWebhookSignatureValidator and OutboxRetryWorker work.
```
```text
From "00 Acme API Knowledge Base", use obsidian-memory get_note_section with headings=["Webhook Idempotency", "Retry Policy"].
```

### 3. End a session before compaction
```text
/handoff acme-api
```
Writes a frozen `YYYY-MM-DD-HHMM-<topic>-handoff.md`, updates the parent central index/task doc so nothing drifts, calls `reindex`, and verifies immediate MCP retrieval.

### 4. Audit & backfill index drift anytime
```bash
uv run obsidian-memory audit
uv run obsidian-memory backfill --scope web-app          # Safe dry-run preview
uv run obsidian-memory backfill --scope web-app --apply  # Apply missing table rows
```

---

## MCP Tools (7 Lean, Strictly Budgeted Tools)

| Tool | Purpose | Default Budget |
|---|---|---|
| `get_session_brief(scope, task?, max_chars=8000)` | Primary `/resume` boot pack (latest handoff + task contract + KB outline). | ~2,000 tok |
| `search_memory(query, scope?, doc_type?, section?, limit=8, max_chars=6000)` | Hybrid FTS5 BM25 + ONNX cosine RRF search with authority (`kb > task > handoff > index`) & recency ranking. | ~1,500 tok |
| `get_note_section(note, heading?, headings?, include_links=true, max_chars=6000)` | Fetch a note's outline, one section, or **multiple batched sections** in a single call. | ~1,500 tok |
| `get_latest_handoff(scope?, project?, task?, sections?)` | Return the newest frozen handoff ordered by exact `YYYY-MM-DD-HHMM` timestamp. | ~1,500 tok |
| `get_linked_context(note, depth=1, max_chars=6000)` | Traverse outgoing `[[wikilinks]]` and incoming backlinks with 1-line summaries. | ~1,500 tok |
| `list_scopes_and_tasks()` | Compact table of all indexed scopes, central KBs/indexes, tasks, and latest handoff dates. | ~500 tok |
| `reindex(scope?, force=false)` | Incremental mtime/sha256 sync (reuses embeddings for unchanged chunks) + drift summary. | ~200 tok |

---

## Privacy & Trust Boundaries

- **Explicit Allowlist:** Only folders listed in `[[roots]]` in `config.toml` are ever walked.
- **Hard Denylist:** `Private/`, `.git/`, `.obsidian/`, and `.trash/` are unconditionally blocked at the path-guard level (even if removed from `config.toml`).
- **Read-Only Vault Access:** The MCP server never writes to your Markdown vault; SQLite WAL files live in your OS local-data directory (`%LOCALAPPDATA%` / `~/Library/Application Support` / `~/.local/share`).

---

## Benchmarks

### Live Cursor CLI A/B Test (Grok 4.6 High · Standard Mode · 256k Context)

Tested live on a real **86.7 KB (1,123-line)** combined approval-workflow knowledge base with a broad 5-part architecture prompt (exact resolver class, 5 module IDs, compact vs. 5-level template differences, role skip matrix, and fallback chain):

![Live Cursor CLI A/B Benchmark](docs/benchmark-live-ab.svg)

| Metric | Old Approach (Full File Path) | New Approach (`obsidian-memory` MCP) | Delta |
|---|---|---|---|
| **Ground-truth fact recall** | **14 / 14 (100%)** | **14 / 14 (100%)** | Tie (100% parity) |
| **Obsidian payload loaded** | 86,706 chars (~22,817 tok · 8.9% of 256k) | 38,781 chars (~10,206 tok · 4.0% of 256k) | **−55.3% (2.24× less)** |
| **Total tool payload injected** | 102,612 chars (~27,003 tok · 10.5% of 256k) | 42,070 chars (~11,071 tok · 4.3% of 256k) | **−59.0% (2.44× less)** |
| **Reasoning + final answer** | ~1,995 tok | ~1,865 tok | **−6.5%** |
| **Tool calls (errors)** | 3 calls (`0` errors) | 12 calls (`0` errors) | +9 calls |
| **Wall-clock latency** | **50.4 s** (2 LLM turns) | **80.0 s** (4 LLM turns) | +29.6 s\* |

**Honest takeaway:**
- On a broad multi-part question where you already know the single file path, direct full-file loading finishes faster on turn 1, while `obsidian-memory` cuts injected context by **55–59%** with identical **14/14** accuracy — keeping far more of a 256k context window free across the rest of the coding session (where turn-1 tokens get re-sent on every subsequent turn).
- On targeted lookups, session boots, and cross-note queries against larger vaults (**227 notes / ~180 KB living KBs**), offline retrieval benchmarks measured **74–97% context reduction (3.8×–38.4× smaller)** at **13.5 ms** average warm query latency.
- *\*The live run above was measured on v0.1.0 before v0.2.0 added batched `headings: list[str]` to `get_note_section`, which reduces multi-section lookups into fewer round-trips.*

---

## Benchmarking Your Own Vault

Two benchmark scripts are included under `scripts/`:

- **Offline payload & recall benchmark:**
  ```bash
  uv run python scripts/benchmark_retrieval.py --config config.example.toml
  ```
- **Live A/B CLI benchmark** (works with Cursor CLI `agent`, Codex CLI, Claude Code, or OpenCode):
  ```bash
  uv run python scripts/live_cli_benchmark.py \
    --cli cursor \
    --model "grok-4.6[effort=high,fast=false]" \
    --file "./examples/vault/acme-api/00 Acme API Knowledge Base.md" \
    --scope acme-api \
    --question "Explain the Stripe webhook idempotency contract and retry worker." \
    --facts "StripeWebhookSignatureValidator,BillingOutboxEvents,OutboxRetryWorker"
  ```

---

## Development & Tests

```bash
uv run pytest -v
```

MIT License — see [LICENSE](LICENSE).

TDQS

B3.3/5.0

Scored across 7 tools

Disambiguation4/5

Each tool targets a distinct retrieval shape: hybrid search, section reads, wikilink traversal, handoff lookup, scope listing, session boot, and reindexing. The only friction is between get_session_brief and get_latest_handoff, since the brief already embeds the latest handoff, so an agent may pick the narrower tool when the boot pack was intended; descriptions mostly resolve this.

Naming Consistency4/5

Six of seven tools follow a clean verb_noun convention (get_session_brief, search_memory, list_scopes_and_tasks). The lone exception is the bare verb 'reindex', a minor but visible deviation.

Tool Count5/5

Seven tools is squarely in the sweet spot for a focused memory/retrieval server, and each one covers a different access pattern rather than duplicating another. No bloat and no obviously missing sibling tool.

Completeness3/5

Read paths are thoroughly covered (boot pack, search, sections, links, handoffs, scopes), but the surface is entirely read-only: there is no way to write a note, freeze a new handoff, or create/update a task contract, so the 'memory' lifecycle dead-ends at consumption. An agent can work around this only if another tool or Obsidian itself handles writes, which the descriptions do not state.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues