Skip to main content
Glama

second-brain MCP Server

A self-maintaining personal knowledge base for AI agents — a plain-Markdown vault, powered by MCP.

CI Python 3.11–3.13 License: MIT

📖 English · 繁體中文


A local knowledge base your AI agent can read, write, and maintain on its own. Save a paper or note with one command — second-brain converts it to Markdown, OCRs every figure, embeds it for semantic search, and auto-links it to related notes. Notes you stop reading compress themselves over time, so recall stays cheap as the vault grows.

Everything is plain Markdown — sync via Google Drive / iCloud / git, switch agents anytime, zero lock-in.

Highlights

  • One command saves anything — save_article(url_or_pdf) fetches, converts to Markdown, OCRs figures (Claude Vision), embeds, and auto-links.

  • Figure-level search — search_figures("UMAP melanocyte") returns the exact panel across your whole library.

  • Self-organizing — new notes auto-link to related ones; frequently-read notes extract reusable rules.

  • Memory that forgets like a brain — Ebbinghaus ranking; stale notes auto-compress (60–90% fewer tokens).

  • Read-only housekeeping audit — inspect article metadata, links, exact duplicate candidates, inbox age, and source freshness without changing the vault.

  • Session continuity — get_context() reloads goals + top notes + rules at the start of every session.

  • Pluggable backend — DuckDB (default, offline) or Postgres + pgvector (central, multi-machine). Self-hosted embeddings optional; BM25 fallback when offline.

Related MCP server: mybrain

Quick Start (Claude Code)

pip install mcp-second-brain
playwright install chromium

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

The vault directory and templates are created on first run. Then tell your agent init_vault to verify.

⚠️ PyPI currently lags the source tree. For the newest build — plus Claude Desktop, Windows, and multi-machine / central-server setups — see NEW_MACHINE_SETUP.md.

Core Tools

Tool

What it does

auth_context

Read the authenticated caller's canonical UUID, role, and RBAC state

get_context

Session start — goals + top-ranked notes + auto-rules

save_article

URL / PDF → Markdown + figures + embeddings

search_notes / search_figures

Hybrid BM25 + semantic search (note text / figure content)

search_articles

Structured author, ORCID, DOI/PMID/PMCID and year search for papers

audit_article_records

Bounded, read-only article housekeeping and social-source freshness report

new_note / update_note / append_to_note

Create & edit notes (auto-filed, auto-indexed, auto-linked)

vault_sleep

Compress old, low-activity notes

get_agent_instructions

Serve the full filing SOP (AGENTS.md) to remote agents

Full tool reference (46 tools) lives in AGENTS.md.

Use search_notes when you need content, health_check when the server or index may be unhealthy, and audit_article_records when you need a housekeeping report. Audit results never merge, archive, or delete notes automatically.

How It Works

Any source (paper · PDF · web · note)
        │   save_article · new_note
        ▼
Markdown vault  ──►  index  (DuckDB, or Postgres + pgvector)
  00-inbox/            • BM25 + semantic search
  10-projects/         • figure OCR + vision descriptions
  20-areas/            • auto-wikilinks between related notes
  30-resources/        • Ebbinghaus ranking → weekly auto-compression
  decisions/ memory/
        │
        ▼
Your AI agent queries it — search_notes · search_figures · get_context

The vault is the source of truth; the index is rebuildable anytime (sync_index). Filing conventions live in one operating manual — AGENTS.md — served to any agent via get_agent_instructions(), so every agent files things the same way without being re-taught.

Vault Structure

vault/
├── 00-inbox/       Unprocessed captures
├── 10-projects/    Active projects
├── 20-areas/       Ongoing research / coding domains
├── 30-resources/   Papers & articles (save_article writes here)
├── 40-archive/     Auto-compressed originals
├── decisions/      Architecture Decision Records
├── memory/         goals.md · rules.md  (injected every session)
└── templates/      Note templates

Legacy author metadata

search_articles reads structured frontmatter, so older article notes without authors are not guessed from body text or references. A bounded two-phase CLI can prepare those notes safely: first create and review a manifest, then apply it separately.

python -m mcp_second_brain.author_backfill \
  --vault "<vault>" --limit 20 --out /tmp/author-backfill.json
python -m mcp_second_brain.author_backfill \
  --vault "<vault>" --apply --manifest /tmp/author-backfill.json

Apply on the central writer host only. Each entry requires an exact DOI/PMID/PMCID or title match and unchanged content/body hashes; successful writes are reindexed.

Documentation

  • AGENTS.md — filing SOP, naming conventions, full tool reference (single source of truth)

  • NEW_MACHINE_SETUP.md — source install, self-hosting, multi-machine central server, API keys

  • CONTEXT.md — domain model / ubiquitous language

Design Notes

Inspired by biological memory: the Ebbinghaus forgetting curve (access_count / ln(age_days)) for ranking, and sleep-dependent consolidation (weekly LLM compression of low-access notes). Built with MarkItDown · DuckDB · pgvector · FastMCP · Playwright · Claude API.

License

MIT © 2026 Chan Chi Ru. See LICENSE.

Available Tools

46 tools
annotate_figureA

Save a read-time insight about a figure as an atomic vault note.

Use AFTER you have loaded a figure (read_figure) and reasoned out something worth keeping — e.g. a specific value, trend, or conclusion. The insight is stored as a short standalone note (fully within the search index window) that backlinks the paper, so next time the question can be answered from text alone without re-loading the image. Insights for the same figure are appended.

Store STRUCTURED facts ('panel C: IC50 = 2.3 µM') over prose — they cache better.

Args: note_path: Vault-relative path of the source paper note fig_index: 0-based figure index (as shown by search_figures / read_figure) insight: The fact/observation to remember about this figure

Inputs: insight (required), fig_index (required), note_path (required). Returns: result

append_to_noteA

Append content to the end of an existing note.

Safer than update_note — existing text is never lost. Use for adding progress updates, new findings, or extra sections.

Args: path: Relative path from vault root, e.g. '10-projects/my-project.md' content: Text to append (added after a blank line at end of file)

Inputs: path (required), content (required). Returns: result

audit_article_recordsB
Read-onlyIdempotent

Audit article records and social-source state without changing the vault.

Args: scope: Audit article notes, social-source state, or both. limit: Maximum results returned per issue category (1..500). stale_after_days: Age at which source state is considered stale (1..90).

Inputs: limit, scope, stale_after_days. Returns: scope, vault, counts, issues, +7 more

auth_contextA
Read-onlyIdempotent

Return the authenticated caller's canonical EP UUID and current role.

Inputs: no named parameters. Returns: role, user_id, rbac_enforced

backfill_figure_textA

Fill empty OCR/description fields using only the configured local VLM.

The call is resumable and bounded to at most 20 notes and 20 images. Each successful image is committed separately; model failures remain queued. SB_VISION_BACKEND=local-only is mandatory, so paid fallback is impossible.

Args: note_paths: Explicit vault-relative article paths; at most 20. dry_run: List the next bounded image batch without model calls or writes. note_limit: Maximum supplied notes to inspect; 1 through 20. image_limit: Maximum images to analyse in this call; 1 through 20.

Inputs: note_paths (required), dry_run, note_limit, image_limit. Returns: result

consolidate_toolA

Find and consolidate clusters of semantically similar notes.

Groups notes with cosine similarity >= threshold, then uses Gemini CLI to synthesise each cluster into one abstract note in 20-areas/consolidated/. Source notes are marked status='consolidated' and deprioritised in context.

Default dry_run=True — inspect clusters before committing.

Args: threshold: Cosine similarity threshold for clustering (default 0.85) dry_run: If True, show clusters without consolidating (default True)

Inputs: dry_run, threshold. Returns: result

enrich_neighbor_keywords_toolA

Enrich notes with neighbor_keywords and cluster_topic derived from embedding similarity.

Computes cosine similarity between all notes' embeddings, finds top-5 neighbors per note, and writes high-frequency words from neighbors back into each note's frontmatter. No API or model calls — pure local computation from vault.db embeddings.

Args: note_path: Relative path to a single note (e.g. "10-projects/foo.md"). Empty string = process all notes without neighbor_keywords. force: If True, overwrite existing neighbor_keywords. Default: skip existing. Returns: JSON-like string with {"enriched": N, "skipped": M, "no_neighbors": K}.

Inputs: force, note_path. Returns: result

expand_semantic_keywords_toolA

Batch-extract or refresh semantic_keywords for notes via llm_cli (local Gemma4 → Claude CLI → Gemini CLI, in that priority order — see llm_cli.py's module docstring).

Writes extracted keywords into each note's frontmatter and rebuilds FTS index. Skips notes that already have semantic_keywords unless force=True.

Args: note_path: Specific vault-relative path to process (e.g. 'decisions/my-note.md'). Leave empty to process all indexed notes missing keywords. force: If True, overwrite existing semantic_keywords (default False).

Returns: Summary dict: {"processed": N, "skipped": M, "failed": K}

Inputs: force, note_path. Returns: result

extract_figures_forB

Manually trigger figure extraction for a saved article.

Args: note_path: Relative path within vault, e.g. '30-resources/my-article.md'

Inputs: note_path (required). Returns: result

extract_rules_toolA

Extract L3 declarative rules from high-access notes into memory/rules.md.

Rules are auto-injected at the top of every get_context() call so Claude always has the most important project constraints in view.

Args: note_path: Specific note to extract from (e.g. 'decisions/my-note.md'). Leave empty to run batch extraction on all eligible notes (access_count >= 5, not extracted in last 90 days).

Inputs: note_path. Returns: result

get_agent_instructionsA

Return the full AGENTS.md operating manual for AI agents.

Call this at the start of a remote session (when AGENTS.md cannot be read from the filesystem) to learn vault structure, tool SOP, and hard constraints.

Returns: str: Full contents of AGENTS.md

Inputs: no named parameters. Returns: result

get_contextA

Load session context: current goals + top-20 most recently active notes. Call this at the start of every session to orient yourself.

Inputs: no named parameters. Returns: result

get_decisionsB

Get decision records from the vault.

Args: project: Filter by project name (optional). If empty, returns all decisions.

Inputs: project. Returns: result

health_checkA

Diagnose second-brain system health.

Checks: DB connectivity, note count vs vault files, WAL file size, duplicate server processes, embedding server, and vault accessibility. Returns a plain-text report with OK / WARN / ERROR per item.

Inputs: no named parameters. Returns: result

index_statsA

Show vault index statistics: total notes, breakdown by type, DB location.

Inputs: no named parameters. Returns: result

init_vaultA

Initialize or repair vault directory structure and default templates.

Safe to re-run: only creates missing items, never overwrites existing files. Call this after cloning the repo or setting up on a new machine.

Inputs: no named parameters. Returns: result

litnet_answerA

Answer a literature question as a fixed-format, CITED synthesis note (retrieve → synthesize).

Retrieves grounded material via query_graph (LitNet 正本 edges + full-text net), then Claude writes a cited summary. GENERATED prose (not raw literature): every claim is anchored to a source note in the retrieval; tagged type: synthesis; a synthesis is NEVER re-extracted into the 正本 (saved outside 20-areas/research/).

Args: entity: comma-separated entities to look up; if empty, extracted from the question (auto-extraction caps at _LA_MAX_AUTO_ENTITIES=3 entities — pass entity explicitly to query more than that in one call; see AGENTS.md's SOP note on this). fmt: middle-section shape — auto | mechanism | compare | list | methods (auto = model picks). save: if true, write the note into VAULT/20-areas/syntheses/ (else just return it). model: Claude synthesis model.

Each entity is queried via query_graph(e, "both") — top_k intentionally omitted so it always tracks query_graph's own default (currently 12) instead of a second hardcoded number that can silently drift from it.

Inputs: question (required), fmt, save, model, +1 more. Returns: result

manage_api_keyA

Manage API keys for multi-user access (admin only).

action: "register" | "revoke" | "list" raw_key: the plaintext API key (register/revoke). Never stored; only its SHA-256 hash is persisted. user_id: human-readable owner label (register/list filter). role: "reader" | "member" | "writer" | "admin" (register only, default "reader"). 'member' (lab-open plan) requires user_uuid — it is how the key's private 90-personal// area is derived (see visibility.py). user_uuid: canonical UUID from EP lab-access (register only). Required for role='member'; optional for other roles. expires_days: if > 0, the key expires that many days from now (register only). 0 (default) means no expiry, same as every key before this.

Returns a plain-text summary of the operation.

Inputs: action (required), role, raw_key, user_id, +2 more. Returns: result

mark_note_statusA

Update the frontmatter status field of a note and sync to DB.

Use this to track note lifecycle without rewriting the whole file — including a decision note's proposed → accepted → superseded progression.

Args: path: Relative path from vault root, e.g. '30-resources/my-note.md' status: active | completed | archived (general / project notes), proposed | accepted | superseded (decision / ADR), or consolidated | archive_backup (normally written by consolidate_tool / vault_sleep, accepted here for repairs).

Inputs: path (required), status (required). Returns: result

new_noteA

Create a new note in the vault using the correct folder and template.

If the title or tags contain a known project slug (from PROJECT_REGISTRY.md), the note is automatically routed into that project's subfolder: coding → {project}/phases/, research/paper/finding → {project}/research/, resource/reference/tool → {project}/docs/ decision/adr always go to decisions/; project always goes to 10-projects/. A coding-type note whose title slug starts with "fix-" routes to {project}/fixes/ instead of phases/ — a postmortem isn't an in-flight phase plan.

Args: note_type: Type of note — decision, project, research, coding, resource, or inbox title: Human-readable title (will be converted to kebab-case filename) content: Optional initial content to append after the template tags: Comma-separated tags, e.g. 'evo-prism,architecture'. Added to frontmatter.

Inputs: title (required), note_type (required), tags, content. Returns: result

prune_archive_toolA

Delete archived originals older than min_age_days that have a snapshot.

Safe to run: only deletes when a PNG snapshot exists as long-term memory. Default dry_run=True — set to False to actually delete.

Args: min_age_days: Minimum age of archived file to consider (default 365) dry_run: If True, only report what would be deleted (default True)

Inputs: dry_run, min_age_days. Returns: result

query_audit_logA

Query the write-action audit log (admin only).

user_id: filter by actor (optional). tool_name: filter by tool (optional). limit: max rows to return (default 50).

Inputs: limit, user_id, tool_name. Returns: result

query_graphA

Dual-path knowledge-graph query for an entity (gene / factor / phenotype / …).

Path 1 — structured typed edges (ACTIVATES / INHIBITS / PROMOTES / CAUSES / PREVENTS / ASSOCIATED_WITH) mentioning the entity, aggregated ACROSS papers with verbatim evidence + source note. Cross-paper agreement = stronger (shown as ×N). Path 2 — full-text verbatim snippet recall net (same engine as search_snippets), so a relation the edge extractor missed is still surfaced (goal: 無遺漏).

Args: entity: e.g. 'TXNDC5', 'TGF-beta', 'pulmonary fibrosis'. mode: 'edges' | 'snippets' | 'both' (default 'both'). top_k: snippet notes to pull for the recall net (default 12).

Inputs: entity (required), mode, top_k. Returns: result

read_figureA

Load ONE extracted figure as a down-scaled image (the cheap rung of the recall ladder — between text search and rendering a whole page).

Use this only when search_figures' text proxy (caption + OCR + description) can't answer the question. Returns a thumbnail (long edge ~768px, ~256-400 tokens) rather than the full-resolution image or the whole page.

Args: note_path: Vault-relative path of the source note, e.g. '20-areas/research/paper.md' fig_index: 0-based figure index as shown by search_figures

Inputs: fig_index (required), note_path (required).

read_noteA

Read a specific note by its relative path within the vault.

Args: path: Relative path from vault root, e.g. 'decisions/my-decision.md'

Inputs: path (required). Returns: result

read_note_as_imageA

Read a note as a PNG snapshot (direct image for VLM agents) or text fallback.

Returns the PNG image directly so the calling agent (Claude, Gemini, etc.) reads it with its own vision model — cheaper and faster than routing through an intermediary. Args: path: Relative path from vault root

Inputs: path (required).

reconcile_figuresA

Reconcile figure files and index rows without Vision-model calls.

Only deterministic evidence is applied: a unique canonical local file, a unique same-stem replacement for a missing path, or a guarded public image URL with an existing text proxy. Ambiguous cases remain in the manual queue. Research Markdown is never modified.

Args: note_paths: Explicit vault-relative Markdown paths; at most 20. dry_run: Report actions without downloading files or updating rows. limit: Maximum notes to inspect from the supplied list; 1 through 20.

Inputs: note_paths (required), limit, dry_run. Returns: result

restore_missing_pdf_imagesA

Restore missing legacy embedded-image files from their original PDFs.

Restoration is fail-closed: the reconstructed PDF sequence must match every database row and every surviving file byte-for-byte before any file is written. The call never changes research Markdown or figure database rows.

Args: note_paths: Explicit vault-relative article paths; at most 20. dry_run: Validate and list the next bounded restore batch without writes. note_limit: Maximum supplied notes to inspect; 1 through 20. image_limit: Maximum missing image files to restore; 1 through 20. source_pdfs: Optional local PDF paths aligned with note_paths, for an explicitly verified copy when the recorded File Provider path is unavailable.

Inputs: note_paths (required), dry_run, note_limit, image_limit, +1 more. Returns: result

save_articleA

Convert a web article or PDF into a markdown note and save it to the vault.

Args: source: URL of a web article, or absolute path to a local PDF/DOCX file. title: Optional title override. If empty, inferred from the source filename or URL. tags: Comma-separated tags to add to frontmatter, e.g. 'bioinformatics,clustering'. dest_folder: Vault-relative folder to save into. Defaults to '30-resources'. Use '20-areas/research' for academic papers with DOI/journal. filename: Filename stem (without .md). If empty, auto-generated from title as kebab-slug. Use 'YYYY_Author_ShortTitle' format for research papers, e.g. '2024_Bakr_ARID1A'. metadata: Optional structured bibliographic fields. Only authors, author_ids, DOI/PMID/PMCID, journal, publication_year and canonical_url are written.

Inputs: source (required), tags, title, filename, +2 more. Returns: result

search_articlesA
Read-onlyIdempotent

Search article-only structured bibliography fields.

Use this instead of search_notes when asking for papers by an author. Author matching is based only on article frontmatter, never body text or references. Full names, surname-first initials and ORCID are supported. A surname-only result is marked ambiguous and must not be treated as identity resolution.

Inputs: doi, pmid, year, limit, +3 more. Returns: count, filters, message, results

search_figuresA

Search figures by OCR text or semantic description across all saved articles.

Args: query: Search term, e.g. 'UMAP', 'TYRP1', 'cluster', 'p < 0.001'

Inputs: query (required). Returns: result

search_groupedA

Hybrid search that returns results split into two groups in one call:

  • knowledge: permanent notes, project notes, literature (excludes cnyes_archive)

  • news: cnyes morning briefs from the last 7 days

Useful for finance research (get stock report + morning brief context together) and general knowledge work (see both deep notes and recent news at once).

Args: query: Search terms, e.g. "NVDA" or "transformer architecture" limit: Max results per group (default 10)

Returns: Markdown with two sections: Knowledge and News.

Inputs: query (required), limit. Returns: result

search_news_toolA

Search recent cnyes daily news archives.

Only searches cnyes_archive notes within the last N days. Use search_notes for knowledge base search.

Args: query: Stock ticker, keyword, or company name (e.g. '2317', 'TSMC', 'AI') days: How many days back to search (default 7)

Inputs: query (required), days. Returns: result

search_notesA

Hybrid semantic + full-text search across knowledge notes (excludes daily news archives).

Uses BM25 + cosine similarity (bge-m3, 1024d) when embedding server is available, falls back to BM25-only, then file scan. To search news specifically, use search_news_tool.

Args: query: Search term — supports natural language and keywords

Inputs: query (required). Returns: result

search_snippetsA

Precise localization: return the VERBATIM source sentence from each of the most relevant notes, with its citation. The sentence is quoted exactly from the paper, never rewritten — ideal for 'what does the literature say about X' or 'a factor's role': jumps to the passage.

Args: query: keyword or phrase, e.g. 'TGF-beta fibrosis', 'hair follicle stem cell niche'. top_k: how many notes to pull snippets from (default 8).

Inputs: query (required), top_k. Returns: result

sleep_statusA

Check current sleep triggers and list candidates without compressing.

Inputs: no named parameters. Returns: result

snapshot_note_toolB

Render a markdown note to PNG snapshot for token-efficient storage.

Args: note_path: Relative path within vault, e.g. 'decisions/my-note.md' tier: Resolution tier — 'large' (400 tokens), 'base' (256), 'small' (100)

Inputs: note_path (required), tier. Returns: result

sync_chunks_toolA

Backfill note_chunks for notes whose chunks are missing or stale — the dedicated tool for draining a large backlog (sync_index()'s own chunk backfill is capped small so it stays fast; see its docstring).

limit: max notes to process this call (default 200). Call repeatedly (the response says how many remain) until "remaining" reaches 0 — each call is its own bounded unit of work rather than one unbounded one, so a big backlog never turns a single call into an hours-long block (see PostgresStore.sync_chunks's docstring for the architecture debt this replaced, fixed 2026-09-04).

Inputs: limit. Returns: result

sync_indexA

Rebuild the DuckDB index by scanning all vault markdown files. Run this after adding notes manually, or when setting up on a new machine.

Also backfills note_chunks for up to _SYNC_INDEX_CHUNK_LIMIT notes that predate chunking or whose chunks failed previously. If more than that are outstanding, run sync_chunks_tool() separately to drain the rest — this tool intentionally does not attempt the whole backlog in one call.

Inputs: no named parameters. Returns: result

sync_notesC

Reindex only the explicitly requested vault notes.

Inputs: note_paths (required). Returns: result

top_notesA

Return your most important notes ranked by engagement.

Two ranking modes:

  • score (default): Ebbinghaus decay score = access_count / time_decay. High score = frequently accessed AND recently accessed. Best for finding your core knowledge nodes and most-researched stocks.

  • recency: Last accessed time. Best for resuming recent work.

Use cases:

  • Finance: find your most-researched tickers (= notes with highest score)

  • Knowledge: find Evergreen note candidates (high score = worth refining)

  • Weekly review: top 20 notes you've engaged with most this week

Args: by: "score" or "recency" (default "score") limit: Number of notes to return (default 20)

Returns: Ranked Markdown table of notes.

Inputs: by, limit. Returns: result

update_goalsB

Replace the contents of memory/goals.md with new content.

Args: new_content: Full new content for goals.md (markdown format)

Inputs: new_content (required). Returns: result

update_noteA

Overwrite an existing note with new content.

Use when rewriting or restructuring a note. For adding content without losing existing text, use append_to_note instead.

Args: path: Relative path from vault root, e.g. 'decisions/my-decision.md' content: Full new content to write (replaces the entire file)

Inputs: path (required), content (required). Returns: result

vault_sleepA

Compress old low-activity notes to slim down the vault.

Thresholds are read from vault/.sleep-config.json (per-folder):

  • cnyes_archive: 7 days

  • finance: 30 days

  • everything else: 90 days Notes with Ebbinghaus score > 0.5 are skipped.

Args: dry_run: If True, show candidates without making changes.

Inputs: dry_run. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 46 tools

    Disambiguation3/5

    Several search/retrieval tools overlap in purpose (search_notes, search_articles, search_snippets, search_news_tool, search_grouped, query_graph), and sync tools (sync_index, sync_notes, sync_chunks_tool) or write tools (update_note, append_to_note, new_note) can be confused without careful reading. The descriptions do clarify target and method, so boundaries exist but require effort.

    Naming Consistency3/5

    Mostly snake_case, but patterns vary: verb_noun (search_notes), noun-first (auth_context, index_stats, vault_sleep, sleep_status, health_check), and an inconsistent _tool suffix on about nine tools. The naming is readable but not uniform.

    Tool Count2/5

    46 tools is well above the typical 3–15 range and feels heavy even for a broad vault-management domain. Many tools could be consolidated or grouped without losing capability.

    Completeness4/5

    The surface covers note CRUD, search, indexing, article ingestion, figure management, graph queries, synthesis, admin, and health checks. Minor gaps exist (e.g., no explicit delete/rename/move note tool), but archival/pruning tools mitigate some of that.

    Maintenance

    ActivityStale
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers