Skip to main content
Glama
SecondBrain MCP
by vladilenm

SecondBrain MCP

Safe MCP-сервер для Obsidian vault. Даёт AI-ассистентам (Claude, ChatGPT и др.) семантический доступ к заметкам, проектам, решениям и задачам, а также безопасные операции создания и подтверждённого редактирования.

Что умеет

Вместо сырого доступа к файлам предоставляет структурированные инструменты:

Tool

Описание

healthcheck

Статус vault и статистика

search_knowledge

Полнотекстовый поиск + фильтры по frontmatter

get_note

Чтение заметки по пути или имени

list_notes

Список заметок с метаданными, mtime, size, hash, фильтрами и пагинацией

read_notes_batch

Batch-чтение нескольких заметок для сборки LLM-контекста

get_note_metadata

Метаданные заметки: frontmatter, hash, links, backlinks, tags, line count

validate_vault_path

Проверка безопасности пути для чтения или записи

create_note

Создание новой markdown-заметки с YAML-frontmatter

propose_note_update

Подготовка diff без записи файла

apply_note_update

Применение подтверждённой правки с expected_hash

append_to_note

Добавление блока в заметку или секцию

read_agent_memory

Чтение памяти агента из 00_Meta/AI-System

add_agent_memory

Добавление правила, ошибки, примера, проекта, роли или стиля в память агента

list_projects

Список проектов с фильтром по статусу

get_project_context

Полный контекст проекта: содержимое + связи + задачи + решения

find_related

Связанные заметки через wikilinks, backlinks, общие теги

extract_tasks

Открытые/завершённые задачи из vault или папки

extract_decisions

Записи из журнала решений

Related MCP server: knowledgebased

Safe-write контракт

MCP v0.3 поддерживает запись, но не даёт агенту тихо перезаписывать vault.

  1. Клиент получает hash через list_notes или get_note_metadata.

  2. Клиент вызывает propose_note_update и показывает пользователю diff.

  3. Пользователь подтверждает изменение в UI.

  4. Клиент вызывает apply_note_update с confirmed: true и тем же expected_hash.

  5. Если файл изменился между шагами, MCP вернёт ошибку hash mismatch.

Все операции записи проходят validate_vault_path. Запрещены абсолютные пути, выход за пределы vault, запись не-.md файлов и доступ к исключённым папкам.

Память агента хранится в:

00_Meta/AI-System/
  role.md
  rules.md
  style.md
  projects.md
  mistakes.md
  examples.md

Для second-brain-vault действует соглашение: новые заметки должны иметь YAML-frontmatter, поля type, status, created, updated, tags, aliases, related, а related должен ссылаться хотя бы на один MOC.

Поиск v0.3

search_knowledge теперь использует ранжирование по нескольким полям:

  • title и имя файла;

  • aliases;

  • tags;

  • related;

  • markdown content.

Запрос нормализуется по пробелам, дефисам, /, _ и wikilink-синтаксису, поэтому AI Sprint может находить AI-Sprint, ai/sprint и [[AI Sprint]]. В ответе есть score, matches и snippet, чтобы UI мог показать, почему заметка попала в выдачу.

Рекомендуемый flow для приложения:

search_knowledge
→ read_notes_batch top-K
→ find_related / get_note_metadata при необходимости
→ LLM context builder

Установка

git clone <repo-url> && cd sb-mcp
npm install
npm run build
npm test

Запуск

Stdio (локально, один клиент)

OBSIDIAN_VAULT_PATH=/path/to/vault node dist/index.js

HTTP (удалённо, несколько клиентов)

OBSIDIAN_VAULT_PATH=/path/to/vault \
MCP_AUTH_TOKEN=your-secret-token \
MCP_PORT=3100 \
node dist/index.js --http

Аутентификация

В HTTP-режиме задайте переменную MCP_AUTH_TOKEN для защиты доступа. Токен можно передать двумя способами:

1. Заголовок Authorization — для клиентов с поддержкой кастомных заголовков (Claude Code, API-клиенты):

Authorization: Bearer your-secret-token

2. Query-параметр — для клиентов без поддержки заголовков (Claude.ai, ChatGPT):

https://your-server/mcp?token=your-secret-token

Если MCP_AUTH_TOKEN не задан, сервер работает без аутентификации (не рекомендуется для публичных сетей).

Сгенерировать токен:

openssl rand -hex 32

Переменные окружения

Переменная

По умолчанию

Описание

OBSIDIAN_VAULT_PATH

текущая директория

Путь к Obsidian vault

MCP_TRANSPORT

stdio

Режим транспорта: stdio или http

MCP_PORT

3100

Порт HTTP-сервера

MCP_AUTH_TOKEN

—

Токен для аутентификации в HTTP-режиме

Настройка клиентов

Claude Code (.mcp.json)

Stdio (локально):

{
  "mcpServers": {
    "secondbrain": {
      "command": "node",
      "args": ["/path/to/sb-mcp/dist/index.js"],
      "env": {
        "OBSIDIAN_VAULT_PATH": "/path/to/vault"
      }
    }
  }
}

HTTP (удалённо):

{
  "mcpServers": {
    "secondbrain": {
      "type": "url",
      "url": "https://your-server/mcp",
      "headers": {
        "Authorization": "Bearer your-secret-token"
      }
    }
  }
}

Claude.ai / ChatGPT

Используйте URL с токеном в query-параметре:

https://your-server/mcp?token=your-secret-token

systemd (деплой на сервер)

# /etc/systemd/system/secondbrain-mcp.service
[Unit]
Description=SecondBrain MCP Server
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/node /path/to/sb-mcp/dist/index.js --http
Environment=OBSIDIAN_VAULT_PATH=/path/to/vault
Environment=MCP_AUTH_TOKEN=your-secret-token
Environment=MCP_PORT=3100
Restart=on-failure

[Install]
WantedBy=multi-user.target

Контракт данных

  • Исключённые папки: .git, .obsidian, node_modules, 99_Private, _attachments, mcp

  • Типы заметок: project, area, resource, person, daily, moc, decision, inbox, about

  • Статусы: active, paused, done, someday

  • Frontmatter: YAML с полями type, status, created, updated, tags, aliases, related

  • Связи: [[wikilinks]] + related: в frontmatter + backlinks + общие теги

  • Оптимистическая блокировка: write-операции используют hash, чтобы UI применял только просмотренную пользователем версию файла

Available Tools

18 tools
add_agent_memoryB

Append a rule, mistake, example, project, style, or role memory entry under 00_Meta/AI-System.

Inputs: type (required), content (required), tags, source_path.

append_to_noteA

Append markdown to a note or section. Useful for Inbox, logs, and incremental memory entries.

Inputs: path (required), content (required), section, expected_hash, +1 more.

apply_note_updateA

Apply a confirmed note update. Requires confirmed=true and expected_hash to prevent accidental overwrites.

Inputs: path (required), confirmed (required), new_content (required), expected_hash (required), +1 more.

create_noteA

Create a new markdown note safely. Requires frontmatter with type/status/related and refuses to modify existing files.

Inputs: path (required), content (required), frontmatter (required), dry_run, +1 more.

extract_decisionsA

Extract decisions from decision log folders (02_Areas/*/Decisions/). Optionally filter by area name. Sorted newest first.

Inputs: area.

extract_tasksA

Extract checkbox tasks (- [ ] / - [x]) from vault notes. Optionally scope to a folder. By default returns only open tasks.

Inputs: folder, include_completed.

get_noteA

Read a single note by path or name. Returns full content with parsed YAML frontmatter.

Inputs: identifier (required).

get_note_metadataA

Get one note metadata: frontmatter, tags, mtime, hash, wikilinks, backlinks, line count.

Inputs: identifier (required).

get_project_contextA

Full context for a project: README content + related notes (via wikilinks) + open tasks + linked decisions. The key tool for understanding what a project is about.

Inputs: project (required).

healthcheckA

Check vault accessibility and return statistics: note counts by type/status, active projects, areas, decisions

Inputs: no named parameters.

list_notesA

List notes with metadata for browsing UI: path, title, frontmatter, mtime, size, hash. Supports folder/type/status/tag filters and pagination.

Inputs: tags, type, limit, folder, +4 more.

list_projectsA

List all projects with status, deadline, and tags. Optionally filter by status (active/paused/done/someday).

Inputs: status.

propose_note_updateA

Prepare a note update without writing. Returns old/new hashes and a line diff for user confirmation.

Inputs: path (required), new_content (required), expected_hash, update_reason.

read_agent_memoryB

Read agent memory files from 00_Meta/AI-System.

Inputs: files.

read_notes_batchA

Read multiple notes in one call for context building. Returns missing paths separately.

Inputs: paths (required), include_content, max_chars_per_note, include_frontmatter.

search_knowledgeA

Ranked lexical search across vault: title/name/aliases/tags/related/content matching. Filter by type, status, tags. Returns score, matches, and snippets.

Inputs: query (required), tags, type, limit, +1 more.

validate_vault_pathA

Validate whether a relative vault path is safe for read or write. Rejects traversal and excluded folders such as 99_Private.

Inputs: path (required), operation (required).

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 18 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: note CRUD separated from search, tasks, decisions, project context, and memory read/add. No overlapping functions.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern in snake_case (e.g., list_notes, create_note, search_knowledge). Only healthcheck is a single word but still clear.

    Tool Count5/5

    18 tools cover the breadth of a second brain system: notes, tasks, decisions, projects, memory, search, and validation. The count feels complete without bloat.

    Completeness4/5

    Core CRUD operations are present with safety mechanisms. Missing explicit delete/move tools, but the design prioritizes safety and append-only patterns. Minor gaps but overall solid.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables read-only access to Obsidian vaults with semantic search, tag filtering, and metadata queries. Provides secure, intelligent note retrieval and summarization for LLMs without modifying your vault.
      14 npm
      13
      ISC
    • A
      license
      A
      quality
      D
      maintenance
      Provides semantic search and a tag-based knowledge graph for any project, auto-discovering local markdown knowledge bases with YAML frontmatter.
      10
      16 npm
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides semantic search and keyword search over Obsidian notes, along with direct note retrieval, allowing external AI agents to query and access the vault.
      19
      BSD Zero Clause
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables read-only, filesystem-based access to Obsidian vault Markdown notes, including full-text search, title/path search, and frontmatter or tag metadata lookup, all without running Obsidian or using a plugin/REST API.
      13 npm
      MIT