second-brain-mcp

Selbstpflegendes Wissensarchiv: figure-level Suche, automatische Wikilinks und schlafbasierte Speicherkompression.

Dokumentation

second-brain MCP Server

A self-maintaining personal knowledge database โ€” powered by MCP, DuckDB, and biological memory models.

CI Python โ‰ฅ 3.11 DuckDB MCP License: MIT


For anyone who saves more papers, notes, and figures than they could ever re-read. second-brain turns everything you capture into a database that maintains itself โ€” auto-linking related notes, compressing what you stop reading, and keeping every figure searchable by its content. What you saved a year ago is still one query away, at a fraction of the token cost.

Why Does This Exist?

ProblemSolution
๐Ÿ“„ You save dozens of papers but can never find the right figuresearch_figures("UMAP melanocyte") โ€” returns the exact panel, across every paper you've saved
๐Ÿ“‘ arXiv gives you the abstract; you need the full paperAuto-upgrades /abs/ โ†’ /html/ โ€” fetches the complete paper with all sections, not just the abstract
๐Ÿ—‚ Notes pile up; older ones never get cleaned upVault Sleep: low-access notes compress automatically every Sunday while you sleep (60โ€“90% token reduction)
๐Ÿ”— New notes stay isolated; you forget what's connectedAuto-wikilinks: every saved note is automatically linked to semantically related notes already in your vault
๐Ÿ”Ž Semantic search needs a cloud API or Docker stackSelf-hosted nomic-embed-text via llama-server; BM25 fallback when offline
๐Ÿ”’ Every AI memory tool locks you into their formatPure Markdown vault โ€” sync with Google Drive, iCloud, or git; switch agents anytime
๐Ÿ–ผ Figure context is lost when you read a paperEvery figure is downloaded, OCR'd by Claude Vision, and stored in DuckDB โ€” searchable by gene name, p-value, axis label

The One-Command Demo

save_article("https://arxiv.org/abs/2405.01234")
  โ†“
โ€ข /abs/ auto-upgraded to /html/ โ€” full paper, not just abstract
โ€ข Full text converted to Markdown
โ€ข All figures downloaded + OCR'd by Claude Vision
โ€ข Semantic embeddings computed
โ€ข Auto-linked to related notes already in your vault   โ† auto-wikilinks
โ€ข Stored in 30-resources/ โ€” queryable immediately

search_figures("UMAP cluster batch correction")
  โ†“
โ€ข Returns the exact figure from the exact paper
โ€ข Works across your entire saved literature library

What Makes It Different

flowchart LR
    subgraph input["๐Ÿ“ฅ Any Content Source"]
        A1["arXiv / PubMed paper"]
        A2["Web article / blog"]
        A3["Local PDF / DOCX"]
        A4["Personal note"]
    end

    subgraph core["โš™๏ธ second-brain-mcp"]
        B1["Markdown note<br/>30-resources/"]
        B2["Figure OCR<br/>+ VLM description"]
        B3["Semantic embedding<br/>+ auto-wikilinks"]
        B4["Ebbinghaus score<br/>ranking"]
        B5["PNG snapshots<br/>60โ€“90% token reduction"]
    end

    subgraph query["๐Ÿ” Queryable Knowledge"]
        C1["search_figures<br/>'UMAP melanocyte'"]
        C2["search_notes<br/>'batch correction scRNA'"]
        C3["get_context<br/>top-20 relevant notes"]
    end

    input --> core
    B1 --> B2
    B1 --> B3
    B3 --> B4
    B4 --> B5
    B2 --> C1
    B3 --> C2
    B4 --> C3

Eight things most self-hosted memory tools can't do โ€” combined in one:

Most memory toolsโ€ฆsecond-brain
Save a link or PDF, then leave you to read and tag it๐Ÿ”ฌ One command builds the database โ€” save_article fetches any URL/PDF, converts to Markdown, downloads & OCRs every figure with Claude Vision, then semantic-indexes it
Store the arXiv abstract you pasted๐Ÿ“‘ Full text, not abstracts โ€” /abs/ URLs auto-upgrade to /html/ for the complete paper: methods, results, discussion
Leave new notes isolated until you tag them๐Ÿ”— The knowledge graph builds itself โ€” every note is auto-linked to semantically related notes already in your vault
Cost the same whether a note is read daily or never๐Ÿง  Memory that forgets like a brain โ€” Ebbinghaus score ranks by recency ร— frequency; stale notes compress while you sleep
Search documents, not what's inside the figures๐Ÿ–ผ Figure-level search across your whole library โ€” search_figures("p < 0.001") returns the exact panel from the exact paper
Forget your project decisions between sessions๐Ÿ“‹ The AI learns your rules โ€” hot notes auto-extract constraints into memory/rules.md, injected at every session start
Grow more expensive as the vault grows๐Ÿ“‰ Token cost shrinks with age โ€” PNG snapshots replace old text at 60โ€“90% compression; frequently-read papers stay full-fidelity
Lock you into their database format๐Ÿ”“ Zero lock-in โ€” pure Markdown, any MCP agent, sync via any cloud drive or git

Cross-Session Continuity โ€” Pick Up Where You Left Off

Every project you work on can be resumed in a new session with full context โ€” no re-explaining, no lost progress.

flowchart LR
    A["๐ŸŸข Session Start<br/>get_context()"] --> B["AI receives:<br/>โ€ข goals.md โ€” current priorities<br/>โ€ข Top-20 recent notes<br/>โ€ข Extracted rules"]
    B --> C["Work on project<br/>new_note / search / read"]
    C --> D["๐Ÿ”ด Before ending session<br/>update_goals(...)"]
    D --> E["New session<br/>get_context() again"]
    E --> B

How It Works in Practice

End of session โ€” tell the agent to save state:

Update goals: currently working on the scRNA batch correction pipeline.
Completed: harmony integration. Blocked on: choosing n_components for PCA.
Next session: start from the PCA parameter sweep in 20-areas/research/harmony-notes.md

The agent calls update_goals() and optionally new_note("project", ...) for detailed progress.

Start of next session โ€” just say:

Get context and continue where we left off.

The agent calls get_context() and immediately sees:

  • goals.md with the state you saved
  • The harmony-notes.md surfaced at the top (recently accessed, high Ebbinghaus score)
  • Rules auto-extracted from that note, e.g.:
RULE: use n_components=30 for this dataset โ€” tested 20/30/50, 30 minimises batch effect without losing resolution
RULE: exclude sample CRC_04 โ€” library size outlier confirmed by QC

These rules live in memory/rules.md and are injected at every get_context() call โ€” the AI carries your hard-won decisions forward automatically, without you having to repeat them.

What Gets Persisted

WhatWhereAlways in context?
Current priorities / blocked itemsmemory/goals.mdโœ… every session
Project progress notes10-projects/ or 20-areas/โœ… if recently accessed
Decisions and rationaledecisions/via get_decisions()
Extracted rules from notesmemory/rules.mdโœ… every session
Saved papers and figures30-resources/via search_notes/figures

This works across any project โ€” bioinformatics analysis, coding, writing, research. Save state with one sentence at the end of a session; resume instantly at the start of the next.


Consistent Filing โ€” The Operating Manual

Tools alone don't keep a vault tidy โ€” the agent has to know where each note belongs, how to name it, and what not to touch. second-brain ships a single operating manual (AGENTS.md) that encodes those decisions, so any agent files things the same way every time โ€” no re-explaining your conventions each session.

Agent receives a request
        โ”‚
        โ–ผ
get_agent_instructions()   โ† returns the full AGENTS.md operating manual
        โ”‚
        โ–ผ
Agent now knows, without being told:
  โ€ข Filing decision tree   โ€” paper (DOI/author) โ†’ 20-areas/research/
                             reference doc      โ†’ 30-resources/
                             stock analysis     โ†’ finance/  ยท unsure โ†’ 00-inbox/
  โ€ข Naming convention      โ€” papers: {YYYY}_{Author}_{ShortTitle}.md
  โ€ข Figure rules           โ€” figures/{slug}/fig-NN.png, embedded as ![[โ€ฆ]]
  โ€ข Editing discipline     โ€” local edits only, never reorder frontmatter,
                             new notes go through new_note (templated)

Why it matters for efficiency:

Without the manualWith AGENTS.md
You re-explain "papers go here, name them like this" every sessionThe agent reads it once per session and just does it
Notes drift into inconsistent folders/names; search degradesStable structure โ†’ semantic + figure search stays reliable
Each agent (local Claude Code, remote MCP, Gemini) behaves differentlyOne manual, one behaviour โ€” served locally via CLAUDE.md, remotely via get_agent_instructions()

Single source of truth: keep all conventions in the one AGENTS.md the server serves. Forks in a second copy silently diverge โ€” remote agents then act on stale rules. Edit the canonical file only.


Example Queries

# Resume a project from last session
get_context()  # โ†’ goals + recent notes + rules loaded automatically

# Find a specific figure panel across all saved papers
search_figures("p < 0.001 UMAP cluster")

# Semantic search across all notes
search_notes("single cell integration batch correction")

# Decision records for a specific project
get_decisions("MyProject")

Memory Architecture โ€” Biological Analogy

Biological BrainThis System
Hippocampal consolidation during sleepVault Sleep: weekly LLM-compression of old low-access notes
Ebbinghaus forgetting curveScore-based ranking: access_count / ln(age_days)
Visual long-term memoryPNG snapshots โ€” resolution degrades gracefully with age
Associative recallSemantic search + auto-generated [[wikilinks]]
Sleep-dependent consolidationlaunchd cron, runs Sunday 02:00 while you sleep

Token Efficiency

Memory that gets cheaper over time โ€” unlike flat-file systems where old notes cost the same forever.

Note age โ†’   fresh (0โ€“3 mo)   3โ€“6 months     6โ€“12 months    1 year+
             โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€     โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€    โ”€โ”€โ”€โ”€โ”€โ”€โ”€
token cost:  โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ         โ–ˆโ–ˆโ–ˆโ–ˆ           โ–ˆโ–ˆ
             ~1,000 tokens    ~400 tokens    ~256 tokens    ~100 tokens
                              โ–ผ 60%          โ–ผ 74%          โ–ผ 90%

Tier assigned by score ร— age (adaptive). Frequently-accessed notes stay full-text regardless of age.


Search Performance

Measured on Apple Silicon MacBook (20-rep average, BM25-only mode).

Vault    BM25-only p50          Hybrid BM25+semantic p50
โ”€โ”€โ”€โ”€โ”€โ”€   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€      โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
10 n     โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘   21 ms      โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ   37 ms
50 n     โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘   25 ms      โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ  39 ms
100 n    โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘   27 ms      โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ 45 ms
Vault SizeBM25 p50Hybrid p50Recall@1Recall@5MRR
10 notes21 ms37 ms30%60%0.42
50 notes25 ms39 ms70%90%0.78
100 notes27 ms45 ms70%80%0.73

Hybrid mode adds ~18 ms for embedding lookup. Both modes scale sub-linearly with vault size.

Recall figures at this scale (10โ€“100 notes) carry high sample variance โ€” a single ambiguous query shifts Recall@1 by 10%. Treat them as directional, not as benchmarks against large corpora; the takeaway is that hybrid consistently beats BM25-only on relevance for a fixed query set.


System Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    AI Agent Layer                    โ”‚
โ”‚         Claude Code ยท Gemini CLI ยท Any MCP           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                       โ”‚ MCP Protocol (27 tools)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚               Layer 2 โ€” MCP Server                   โ”‚
โ”‚              mcp_second_brain/server.py              โ”‚
โ”‚  get_context ยท search_notes ยท save_article ยท โ€ฆ (27)  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ”‚               โ”‚                โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  vault_sleepโ”‚ โ”‚  vault_db   โ”‚ โ”‚  figures    โ”‚
โ”‚  compress   โ”‚ โ”‚  DuckDB FTS โ”‚ โ”‚  PNG snap   โ”‚
โ”‚  Phase 3โ€“9  โ”‚ โ”‚  + semantic โ”‚ โ”‚  OCR ยท VLM  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ”‚               โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚               Layer 0 โ€” Markdown Vault               โ”‚
โ”‚   00-inbox ยท 10-projects ยท 20-areas ยท 30-resources   โ”‚
โ”‚   40-archive ยท decisions ยท memory ยท templates        โ”‚
โ”‚         (syncs via Google Drive / iCloud / git)      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Vault Sleep โ€” Auto-compression Flow

Every Sunday 02:00 (launchd, no interaction needed)
        โ”‚
        โ–ผ
 sync_index + embeddings
        โ”‚
        โ–ผ  age > 90d AND Ebbinghaus score โ‰ค 0.5
 โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
 โ”‚         Adaptive Tier Selection      โ”‚
 โ”‚  score > 1.5  โ†’  text  (keep full)  โ”‚  โ† frequently-read: never compressed
 โ”‚  score > 0.8  โ†’  large  ~400 tokens โ”‚
 โ”‚  score > 0.3  โ†’  base   ~256 tokens โ”‚
 โ”‚  otherwise    โ†’  small  ~100 tokens โ”‚
 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                  โ”‚
  Gemini CLI โ†’ Claude CLI โ†’ naive   (auto-fallback, no LLM required)
                  โ”‚
    compressed โ†’ vault  /  original โ†’ 40-archive/  /  snapshot โ†’ .png

MCP Tools (27 total)

ToolDescription
get_contextSession start: goals + top-20 Ebbinghaus-ranked notes + auto-rules
save_articleFetch URL/PDF โ†’ Markdown + auto-extract figures
search_notesHybrid BM25 + semantic search across all notes
search_figuresSearch figure OCR text / VLM descriptions
search_news_toolSearch cnews morning briefs and financial news by keyword
extract_figures_forManually trigger figure extraction for a saved article
read_noteRead note + record access (updates Ebbinghaus score)
read_note_as_imageReturn PNG snapshot for token-efficient reading
new_noteCreate note with correct template and folder by type
get_decisionsList ADR decision records, optionally filtered by project
update_goalsUpdate memory/goals.md
sync_indexRebuild DuckDB index from vault files
index_statsShow note counts by type
vault_sleepCompress old low-activity notes (dry_run=True by default)
sleep_statusShow compression candidates without acting
snapshot_note_toolRender note to PNG at chosen resolution tier
extract_rules_toolExtract L3 rules from frequently-accessed notes
consolidate_toolMerge semantically similar notes into one abstract note
update_links_toolRefresh auto-generated [[wikilinks]]
prune_archive_toolDelete archived originals that have a PNG snapshot
find_related_notesFind semantically related notes by cosine similarity (finance & knowledge management)
search_groupedHybrid search returning knowledge notes + cnyes morning briefs in one call
top_notesRank notes by Ebbinghaus score or recency โ€” find your most-engaged knowledge nodes
update_noteOverwrite an existing note with new content (auto-reindexes)
append_to_noteAppend content to end of an existing note โ€” safe, never loses existing text
init_vaultCreate or repair vault directory structure and templates
get_agent_instructionsReturn full AGENTS.md operating manual โ€” call at remote session start to learn vault SOP

Test Results

tests/test_figures.py      24 passed   (OCR, snapshots, VLM)
tests/test_server.py       30 passed   (MCP tools, path safety)
tests/test_vault_db.py     73 passed   (FTS, semantic search, embeddings)
tests/test_vault_sleep.py  46 passed   (compression, consolidation, rules, prune)
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
173 passed in 7.51s

Installation

โš ๏ธ Install from source for now. The source tree is packaged (v0.2.0, with a working python -m mcp_second_brain entry point), but the PyPI release is still catching up โ€” the published mcp-second-brain is 0.1.0, so pip install lands an outdated build. Until the fresh release ships, use the Development Install (clone) path. Self-hosting across your own machines from a synced source tree? See NEW_MACHINE_SETUP.md.

Prerequisites

DependencyRequiredNotes
Python 3.11+โœ…
Playwrightโœ…PNG snapshot rendering
uvDev onlyOnly needed for Development Install path
llama-server or OllamaOptionalEnables semantic search; BM25 fallback if absent
nomic-embed-text-v1.5.Q8_0.ggufOptional~300 MB โ€” needed for llama-server path only
ANTHROPIC_API_KEYOptionalBetter compression quality in vault_sleep; naive fallback if absent

Vault structure is auto-created on first server start โ€” no manual mkdir needed.


macOS / Linux โ€” Quick Start

Step 1 โ€” Install

pip install mcp-second-brain
playwright install chromium

Step 2 โ€” Register with your AI agent

Claude Code (CLI) โ€” global, works in any project:

claude mcp add --scope user second-brain \
  --env SECOND_BRAIN_PATH=~/second-brain \
  -- python -m mcp_second_brain

Claude Desktop โ€” add to ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "second-brain": {
      "command": "python",
      "args": ["-m", "mcp_second_brain"],
      "env": { "SECOND_BRAIN_PATH": "/Users/yourname/second-brain" }
    }
  }
}

Step 3 โ€” First run

Start your agent and say:

init_vault

The server auto-creates all directories and templates on startup. Call init_vault explicitly to verify or repair the structure.


Windows โ€” Quick Start

Step 1 โ€” Install Python and the package

# Install Python 3.11+ from python.org, or via winget:
winget install Python.Python.3.11

pip install mcp-second-brain
playwright install chromium

Step 2 โ€” Choose a vault location

# Local folder:
$vault = "C:\Users\$env:USERNAME\second-brain"

# Or a cloud-synced folder (Google Drive, OneDrive, etc.):
$vault = "G:\My Drive\second-brain"

The vault directories and templates are created automatically when the server first starts. No manual setup needed.

Step 3 โ€” Register with your AI agent

Claude Code (VSCode extension) โ€” create .mcp.json in your vault folder:

{
  "mcpServers": {
    "second-brain": {
      "command": "python",
      "args": ["-m", "mcp_second_brain"],
      "env": { "SECOND_BRAIN_PATH": "C:\\Users\\YourName\\second-brain" }
    }
  }
}

Claude Desktop โ€” add to %APPDATA%\Claude\claude_desktop_config.json:

{
  "mcpServers": {
    "second-brain": {
      "command": "python",
      "args": ["-m", "mcp_second_brain"],
      "env": { "SECOND_BRAIN_PATH": "C:\\Users\\YourName\\second-brain" }
    }
  }
}

Gemini CLI / other IDEs โ€” edit %USERPROFILE%\.gemini\mcp_config.json (or IDE-specific config):

{
  "mcpServers": {
    "second-brain": {
      "command": "C:\\Users\\YourName\\.venvs\\mcp-second-brain\\Scripts\\python.exe",
      "args": ["-m", "mcp_second_brain"],
      "env": { "SECOND_BRAIN_PATH": "C:\\Users\\YourName\\second-brain" }
    }
  }
}

Tip: Use a dedicated venv at C:\Users\YourName\.venvs\mcp-second-brain\ (local SSD) rather than a venv on a network drive. Python loads thousands of small files at startup โ€” on a cloud drive this causes 15โ€“30 s delays and context deadline exceeded errors.

Step 4 โ€” Semantic search (optional, Windows)

Ollama is the easiest path on Windows:

winget install Ollama.Ollama
ollama pull nomic-embed-text

Then add to the env block of your MCP config:

"EMBED_URL": "http://localhost:11434/v1/embeddings",
"EMBED_PORT": "11434"

Ollama starts automatically with Windows. No extra configuration needed.

Alternatively, build llama.cpp for Windows and register it as a scheduled task:

# Register llama-server as a login-triggered scheduled task:
$exe  = "C:\Users\$env:USERNAME\llama.cpp\build\bin\llama-server.exe"
$model = "C:\Users\$env:USERNAME\nomic-embed-text-v1.5.Q8_0.gguf"
$args = "-m `"$model`" --port 11435 --embedding --pooling mean -np 4 -c 2048 --log-disable"

$action   = New-ScheduledTaskAction -Execute $exe -Argument $args
$trigger  = New-ScheduledTaskTrigger -AtLogOn
$settings = New-ScheduledTaskSettingsSet -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 1)
Register-ScheduledTask -TaskName "llama-embed" -Action $action -Trigger $trigger `
  -Settings $settings -RunLevel Highest -Force

Step 5 โ€” Weekly vault maintenance (optional, Windows)

# Run vault_sleep every Sunday at 02:00
$pythonExe = "C:\Users\$env:USERNAME\.venvs\mcp-second-brain\Scripts\python.exe"
$serverPy  = "C:\path\to\second-brain-mcp\launchd\run_sleep.py"
$vaultPath = "C:\Users\$env:USERNAME\second-brain"

$action  = New-ScheduledTaskAction -Execute $pythonExe -Argument "`"$serverPy`"" `
  -WorkingDirectory (Split-Path $serverPy)
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 2am
$env_var = [System.Environment]::SetEnvironmentVariable(
  "SECOND_BRAIN_PATH", $vaultPath, "Machine")
Register-ScheduledTask -TaskName "vault-sleep" -Action $action -Trigger $trigger -Force

Development Install (clone)

git clone https://github.com/ddmanyes/second-brain-mcp
cd second-brain-mcp
uv sync
uv run playwright install chromium

Register with Claude Code:

# macOS / Linux
claude mcp add --scope user second-brain \
  --env SECOND_BRAIN_PATH=~/second-brain \
  -- uv run --project /path/to/second-brain-mcp python -m mcp_second_brain

# Windows (PowerShell)
claude mcp add --scope user second-brain `
  --env SECOND_BRAIN_PATH="C:\Users\$env:USERNAME\second-brain" `
  -- uv run --project C:\path\to\second-brain-mcp python -m mcp_second_brain

Environment Variables

VariableDefaultDescription
SECOND_BRAIN_PATH~/second-brainPath to your vault directory
EMBED_URLhttp://localhost:11435/v1/embeddingsEmbedding server endpoint
EMBED_MODELnomic-embed-textEmbedding model name
EMBED_PORT11435llama-server port (use 11434 for Ollama)

Auto-start (macOS, optional)

Weekly vault maintenance (Sunday 02:00) is wired up by the bundled installer โ€” it generates the launchd plists from templates and loads them, using your local venv:

SECOND_BRAIN_PATH=~/second-brain bash launchd/install.sh

For an always-on embedding server, adapt the reference plist:

cp examples/launchd/com.yourname.llama-embed.plist ~/Library/LaunchAgents/
# Edit paths inside the file, then:
launchctl load ~/Library/LaunchAgents/com.yourname.llama-embed.plist

Troubleshooting

SymptomLikely causeFix
new_note returns Error: template not foundTemplates missing from vaultRun init_vault โ€” the server copies bundled templates automatically
Semantic search silently falls back to BM25Embedding server not runningStart Ollama (ollama serve) or llama-server; check with curl localhost:11435/health (or port 11434 for Ollama)
read_note_as_image / snapshots failPlaywright chromium not installedpip install playwright && playwright install chromium
vault_sleep never compresses anythingNo ANTHROPIC_API_KEY โ†’ naive fallback, or no eligible notesExport ANTHROPIC_API_KEY; only notes >90 days old with Ebbinghaus score โ‰ค 0.5 are candidates โ€” run sleep_status to see them
Agent sees no notes / empty resultsIndex not builtRun sync_index once after install (and after bulk file changes)
Notes land in the wrong placeSECOND_BRAIN_PATH unset or wrongSet it in your MCP config env block; defaults to ~/second-brain
Tools unavailable when working in other project foldersInstalled as local config instead of user scopeRe-register with --scope user: claude mcp remove second-brain -s local && claude mcp add --scope user second-brain ...
Windows: MCP server times out on connect (context deadline exceeded)Python venv is on a network/cloud driveMove the venv to local SSD (e.g. C:\Users\Name\.venvs\) โ€” cloud drives cause 15โ€“30 s startup delay
Windows: Semantic search returns no results after sync_indexOllama not runningollama serve in a terminal, or install Ollama with auto-start via winget

Vault Structure

vault/
โ”œโ”€โ”€ 00-inbox/          # Unprocessed captures โ€” clear daily
โ”œโ”€โ”€ 10-projects/       # Active projects
โ”œโ”€โ”€ 20-areas/
โ”‚   โ”œโ”€โ”€ research/      # Ongoing research domains
โ”‚   โ”œโ”€โ”€ coding/        # Dev tools and workflows
โ”‚   โ””โ”€โ”€ consolidated/  # Auto-merged similar notes (Phase 8)
โ”œโ”€โ”€ 30-resources/      # โ† Papers and articles (save_article writes here)
โ”œโ”€โ”€ 40-archive/        # Compressed originals (auto-managed by vault_sleep)
โ”œโ”€โ”€ decisions/         # Architecture Decision Records (ADR format)
โ”œโ”€โ”€ memory/
โ”‚   โ”œโ”€โ”€ goals.md       # Current priorities โ€” injected at every session start
โ”‚   โ”œโ”€โ”€ index.md       # Vault map
โ”‚   โ””โ”€โ”€ rules.md       # Auto-extracted L3 rules โ€” injected at every session start
โ””โ”€โ”€ templates/         # Note templates (note, decision, project, research)

Running Tests

uv run pytest tests/ -v
uv run python benchmark.py --quick --markdown   # search latency + accuracy report

References & Acknowledgements

Papers That Directly Inspired This Project

PaperWhere Used
Do Language Models Need Sleep? Offline Recurrence for Improved Online Inference (2026)Phase 3 Vault Sleep โ€” hippocampal replay as batch memory consolidation
Experience Compression Spectrum: Unifying Memory, Skills, and Rules in LLM Agents (2026)Phase 9 adaptive tier โ€” score ร— age dual-axis; addresses the "missing diagonal" in existing systems
DeepSeek-OCR: Contexts Optical Compression (2025)Phase 4 PNG tiers โ€” image as compressed medium, 10ร— compression at 97% fidelity
MemOCR: Layout-Aware Visual Memory for Efficient Long-Horizon Reasoning (2026)Phase 4 vision API โ€” Playwright render โ†’ VLM reading pipeline
Active Context Compression: Autonomous Memory Management in LLM Agents (2026)Phase 3 design comparison โ€” session-level vs. nightly batch consolidation
SimpleMem: Efficient Lifelong Memory for LLM Agents (2026)Phase 8 consolidation โ€” 3-stage semantic compression, 30ร— token reduction
Memory for Autonomous LLM Agents: Mechanisms, Evaluation, and Emerging Frontiers (2026)Architecture positioning โ€” mechanisms, evaluation, and frontiers

Cognitive Science Foundations

Built With

MarkItDown ยท DuckDB ยท llama.cpp ยท nomic-embed-text ยท FastMCP ยท Playwright ยท Anthropic Claude API


Known Issues & Fixes

WAL corruption (Failure while replaying WAL file)

Cause: DuckDB write was interrupted mid-transaction (IDE restart, pkill -9, or machine sleep).
Symptom: MCP server crashes on startup; every DB operation fails.
Fix:

rm -f ~/.second-brain/vault.db ~/.second-brain/vault.db.wal

Restart the server โ€” it will rebuild a clean DB. Run sync_index to re-index your vault.

Note: If running inside a sandboxed IDE (e.g. Antigravity), the agent cannot delete ~/.second-brain/. Run the command in your local Terminal, or ask Claude Code (VSCode extension) which has full shell access.


vault.db created in the wrong directory

Cause: the server was launched with a non-home working directory; DuckDB created vault.db relative to cwd.
Symptom: ~/.second-brain/vault.db is tiny (< 1 MB) but a large vault.db exists elsewhere.
Fix:

# Find the real vault.db
find ~ -name "vault.db" -size +1M 2>/dev/null

# Move it to the correct location
cp /path/to/found/vault.db ~/.second-brain/vault.db

Running from a cloud-synced source tree (Google Drive / iCloud / OneDrive) across several of your own machines? Keep the venv on local disk (~/.venvs/), never inside the synced folder โ€” sync breaks venv symlinks. That self-hosting model is documented in NEW_MACHINE_SETUP.md.


Contributing

PRs and Issues welcome. Please open an issue first to discuss significant changes.


License

MIT License โ€” ยฉ 2026 Chan Chi Ru. See LICENSE.