convez.ai
MCP Server
apresai

2ndbrain

apresai/2ndbrain

Ver no GitHub
InicialPluginScore · de 0 a 100

AI-native markdown knowledge base with semantic search, RAG, and MCP server

Instalação

$npx convez-ai apresai/2ndbrain

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
3
Forks
0
Acompanhando
0
Saúde
50%
Último commit
há 2 semanas
Versão
v0.23.4
Issues abertas
1
Contribuidores
1

README

A tradução para o português deste README ainda está na fila.

2ndbrain

License: MIT Release Homebrew

AI-native markdown knowledge base with semantic search. A Go CLI, MCP server, and native macOS editor that share a SQLite index — making your knowledge base searchable by both you and your AI coding assistant.

Install

brew install --cask apresai/tap/secondbrain

This installs both the 2nb CLI and the SecondBrain macOS editor. If you only need the CLI:

brew install apresai/tap/2nb

Or download binaries from GitHub Releases.

Note: The editor is ad-hoc signed (not notarized). On first launch, right-click the app and choose "Open" to bypass the macOS Gatekeeper warning.

Quick Start

# Create a vault (and set it active)
2nb vault create ~/vault

# Create documents
2nb create "Use JWT for Authentication" --type adr
2nb create "Debug Auth Failures" --type runbook
2nb create "My Notes on Go"

# Configure AI for semantic search & ask
2nb ai setup

# Index with AI embeddings (safe to run repeatedly)
2nb index

# Search (hybrid BM25 + semantic)
2nb search "authentication"
2nb search "how does auth work" --type adr

# Ask questions (RAG with source citations)
2nb ask "What authentication approach did we choose and why?"

# Check vault health any time
2nb vault

# One-time: enable shell tab-completion (zsh)
2nb completion install

The legacy 2nb init command still works (it prints a deprecation notice). Prefer 2nb vault create <path>.

Homebrew installs shell completions automatically. For manual installs, 2nb completion install detects your existing completion directory from .zshrc (falling back to ~/.zsh/completions/_2nb) and updates .zshrc with the required fpath and compinit block. The block is placed before early-return guards and before any existing compinit/fpath setup (e.g. from gcloud or Homebrew), so completions load correctly even when other tools initialize the completion system first. Re-running is safe — the block is replaced in-place, not duplicated. If multiple 2nb binaries are found on PATH, a warning is printed showing each binary's version and which is active.

Features

  • Hybrid search — BM25 keyword + vector semantic search with Reciprocal Rank Fusion
  • RAG Q&A — Ask questions, get answers with source citations
  • MCP server — 16 tools for Claude Code, Cursor, and any MCP client, with live status sidecar files and an observability panel
  • Suggest Links — AI finds semantically related documents in your vault and proposes wikilinks to insert
  • Polish — AI copy-editor fixes spelling, grammar, and awkward phrasing with a diff preview (Accept / Open in new tab / Reject)
  • Vault health dashboard — unified panel showing index state, embedding portability, stale docs, and provider reachability with one-click Rebuild Index and Re-embed All
  • AI connection testing — one-click probe of your configured embedding and generation models with live latency
  • Incremental re-embed on save — embeddings rebuild only for the document whose content hash changed
  • Git integration (read-only) — sidebar dots for uncommitted/untracked files, Recent Activity panel, Show Changes vs HEAD, MCP tools for AI clients
  • Merge conflict resolution — FSEvents-backed 3-way diff dialog when a tab's file changes externally while dirty
  • Skill files — One command to teach 8 AI coding agents about your vault
  • Three AI providers — AWS Bedrock, OpenRouter, Ollama (fully local)
  • Schema validation — Typed frontmatter, enum constraints, status state machines
  • Wikilinks — [[target#heading|alias]] with link resolution and graph traversal
  • Document templates — ADR, runbook, prd, prfaq, postmortem, note with enforced schemas
  • Native macOS editor — SwiftUI + AppKit with Source/Split/Preview modes, tabs, search, graph view, autosave, crash recovery
  • Local-first — All data on disk as plain markdown. Obsidian-compatible.

AI Providers

2ndbrain supports three AI providers for embeddings and generation. Bedrock uses the Converse API, so any Bedrock model works — Claude, Nova, Llama, Mistral, and more.

ProviderEmbeddingsGenerationSetup
AWS BedrockNova Embeddings v2Nova Micro, Claude, Llama, any modelUses existing AWS SSO — zero new keys
OpenRouterNemotron Embed (free)Gemma 4 31B (free), GPT-4o, Claude, etc.OPENROUTER_API_KEY env var
Ollamanomic-embed-textqwen2.5, gemma3, llama3brew install ollama — fully local

Quick Setup (Any Provider)

The setup wizard detects credentials and offers recommended defaults:

2nb ai setup
# → Pick provider (Bedrock / OpenRouter / Ollama)
# → Easy mode: recommended models, or Custom: pick from catalog
# → Tests connectivity, saves config, offers to index

Local AI with Ollama

Run everything locally with no cloud calls:

# Check readiness (models, disk, RAM)
2nb ai local

# Guided setup (installs models, configures vault)
2nb ai setup

# Or configure manually
2nb config set ai.provider ollama
ollama pull embeddinggemma
ollama pull qwen2.5:0.5b
2nb index

AWS Bedrock (Default)

Uses your existing AWS SSO credentials — no new API keys needed:

2nb ai status
2nb config set ai.bedrock.profile my-profile
2nb config set ai.bedrock.region us-west-2

OpenRouter

export OPENROUTER_API_KEY=sk-or-...
2nb config set ai.provider openrouter
2nb index

Model Catalog & Benchmarking

Browse verified models across all providers, test any model, and benchmark your favorites:

# See all verified models with pricing
2nb models list

# Discover vendor catalogs (Bedrock, OpenRouter, Ollama)
2nb models list --discover

# Check credentials and reachability
2nb models list --status

# Test if a model works before switching (--save adds it to your catalog)
2nb models test amazon.nova-micro-v1:0 --save
2nb models test google/gemma-4-31b-it:free

# Discover and auto-promote all passing models in one step
2nb models list --discover --promote

# Benchmark your favorites
2nb models bench fav amazon.nova-micro-v1:0
2nb models bench fav us.anthropic.claude-haiku-4-5-20251001-v1:0
2nb models bench                  # runs embed/generate/search/rag probes
2nb models bench compare          # side-by-side latency leaderboard
2nb models bench history          # view past runs

# End-to-end wizard: discover → pick → cost preview → test → save
2nb models wizard                 # TTY interactive flow
2nb models wizard --json          # JSON-event stream (GUI / automation)

# Estimate before you run
2nb models cost-preview us.anthropic.claude-opus-4-20250514-v1:0 --probe bench_rag

# Hide a model from selection dropdowns without removing it from the catalog
2nb models disable cohere.embed-multilingual-v3 --provider bedrock --scope vault
2nb models enable  cohere.embed-multilingual-v3 --provider bedrock --scope vault

Models are tiered as verified (tested with 2nb) or unverified (available from vendor, use models test to check). The benchmark suite stores results in .2ndbrain/bench.db for tracking performance over time.

Every catalog entry declares an invoke_strategy (e.g. bedrock_converse, bedrock_invoke_cohere_embed, openrouter_chat) so adding a new model variant doesn't require a code change — a catalog entry with the right strategy is enough. The macOS editor's AI → AI… opens the AI Hub — a single sheet with provider cards (enable / disable Bedrock, OpenRouter, Ollama), active model status, and the full catalog with inline Test / Set active / Enable / Disable / Discover actions. Catalog changes written by the CLI propagate to the running GUI via FSEvents without reopening the vault.

CLI Commands

Commands are organized into groups (2nb --help shows the full list).

Global flags: --json, --csv, --yaml, --format, --porcelain, --vault, --verbose (-v for debug logging to stderr and .2ndbrain/logs/cli.log)

Getting Started

CommandDescription
init --path <dir>Initialize a new vault
vaultShow or set the active vault

Documents

CommandDescription
create <title> [--type adr|runbook|prd|prfaq|postmortem|note]Create document from template
read <path> [--chunk <heading>]Read document or specific section
meta <path> [--set key=value]View or update frontmatter
delete <path> [--force]Delete document from vault and index
list [--type] [--status] [--tag] [--sort]List documents with filters

Search & AI

CommandDescription
search <query> [--type] [--status] [--tag] [--threshold]Hybrid BM25 + semantic search (shows rrf + raw cos scores)
ask <question> [--history <path|->]RAG Q&A with source citations; --history makes it multi-turn
chatInteractive multi-turn Q&A session (REPL over the same pipeline)
suggest-links <path> [--limit 10]Rank semantically related documents for wikilink insertion
polish <path> [--system <prompt>]AI copy-edit a document (JSON with original + polished body)
index [--doc <path>] [--force-reembed]Build search index + embeddings (full vault or a single document); --force-reembed invalidates every stored embedding for after an intentional provider switch
ai statusShow AI provider, models, embedding count, and vault portability state
ai setupMulti-provider setup wizard (easy mode or custom)
ai localCheck local AI readiness (Ollama, disk, RAM, models)
ai embed <text>Generate embedding vector (debug)
models list [--discover] [--status] [--provider] [--promote] [--enabled-only]Verified model catalog + user catalog + vendor discovery; --discover --promote tests unverified models concurrently and adds those that pass; --enabled-only filters out user-disabled models (dropdowns use this)
models test <model-id> [--save] [--scope global|vault]Smoke-test any model (embed or generate probe); --save adds the model to your catalog if it passes
models add <id> --provider --type [--scope global|vault] [--price-in --price-out --dimensions --context-length --name --notes]Add a model to your user catalog (per-vault by default, or global with --scope global)
models remove <id> --provider [--scope global|vault]Remove a model from your user catalog
models enable <id> --provider [--scope global|vault]Mark a model enabled so it appears in dropdowns
models disable <id> --provider [--scope global|vault]Hide a model from dropdowns; still listed by bare models list
models cost-preview [ids...] --probe <kind> [--provider] [--all]Estimate USD cost of running a probe (test / bench_embed / bench_gen / bench_rag / retrieval) across one or more models before committing
models wizard [--scope] [--provider] [--skip-discover] [--cost-cap] [--json]Interactive discover → pick → cost preview → test → save flow; --json emits an event stream for GUI / automation
models benchBenchmark favorites with persistent history
models bench fav <model-id>Add model to benchmark favorites
models bench compareSide-by-side latency leaderboard

Git (read-only)

CommandDescription
git activity [--since 7d]Recent commits that touched vault files
git show <hash>Full commit detail: metadata, stats, per-file diffs
git diff <path>Unified diff of a file against HEAD
git statusUncommitted/untracked files in the vault

Quality

CommandDescription
related <path> --depth <n>Find related docs via link graph
graph <path>Output link graph as JSON
lint [glob]Validate schemas, check broken wikilinks
stale --since <days>Find stale documents

Integration

CommandDescription
mcp-serverStart MCP server on stdio
mcp-setupShow MCP setup instructions for all AI tools
mcp status [--json]List live MCP server processes and their recent tool invocations
export-context --types <types>Generate CLAUDE.md context bundle
skills listList supported AI agents and install status
skills install <agent> [--all] [--user]Install skill file for an AI coding agent
skills uninstall <agent> [--all] [--user]Remove skill file for an AI coding agent
skills show <agent>Preview skill content for an agent

Import / Export

CommandDescription
import-obsidian <path>Import Obsidian vault
export-obsidian <path> [--strip-ids]Export to Obsidian format

Configuration

CommandDescription
config showShow full vault configuration (vault root + dir + name + all ai.* keys)
config get <key>Get a config value (e.g., ai.provider, ai.similarity_threshold)
config set <key> <value>Set a config value
config set-key <provider>Store API key in macOS Keychain

All commands support --json, --yaml, --csv for machine-readable output.

Defaults and search scoring

  • Parent-command defaults — running a command group without a subcommand invokes its most-useful read-only action: 2nb ai → ai status, 2nb models → models list, 2nb git → git status, 2nb mcp → mcp status, 2nb skills → skills list, 2nb config → config show. --help still works on every command.
  • Similarity threshold — hybrid search drops vector hits whose cosine similarity is below the active threshold so barely-related neighbors stop padding result lists. Resolution order: explicit vault config (2nb config set ai.similarity_threshold 0.65) > user calibration saved by 2nb models calibrate --save > per-model recommendation from the builtin catalog > global default 0.20. Builtin recommendations: Nova-2 0.65 (measured), Nemotron 0.60, nomic-embed-text/Titan-v2/Cohere-embed 0.50, mxbai/snowflake/bge-m3 0.55, all-minilm 0.35 (all estimated from each model's training objective — run 2nb models calibrate to tune for your vault). Override per-query with 2nb search "foo" --threshold 0.35. 2nb ai status shows the active value and which tier supplied it.
  • Calibration — 2nb models calibrate samples random chunk pairs from your vault, reports the noise-floor cosine distribution (p50/p90/p95/p99), and recommends a threshold. Add --save to persist it to the per-vault user catalog (or --save --scope global for all vaults).
  • Score display — 2nb search now shows (rrf=X.XXX, cos=Y.YYY) on each result. The rrf is the Reciprocal Rank Fusion score used for ranking; cos is the raw cosine similarity from the vector channel, which is what you actually want to look at when judging whether a result is relevant. If legitimate matches are being cut, lower the threshold; if noise is slipping through, raise it.

Portable vaults

A vault is self-describing. Paths in the index are relative, IDs are UUIDs, and embeddings live in the DB as raw float32 BLOBs — you can tar a vault and open it on another machine without any migration step.

If the receiver's current AI provider doesn't match what produced the embeddings, 2nb ai status tells you exactly what's wrong:

Vault Embedding State:
  As-embedded:    amazon.nova-2-multimodal-embeddings-v1:0 (1024d), 42 of 42 docs
  Current cfg:    ollama / nomic-embed-text (768d)
  Status:         DIMENSION BREAK
  Action:         Vault was embedded with 1024d vectors but current provider produces 768d.
                  Run `2nb index --force-reembed` or switch provider back.

2nb search and 2nb ask fail loudly (stderr + BM25 fallback) on dimension mismatch instead of silently returning worse results. The macOS app surfaces the same warnings as a yellow banner over search results and the Ask AI panel, and the status bar AI dot turns yellow.

Shipping a vault:

tar czf vault.tar.gz \
  --exclude='.2ndbrain/logs' \
  --exclude='.2ndbrain/recovery' \
  --exclude='.2ndbrain/mcp' \
  --exclude='.2ndbrain/bench.db' \
  my-vault/

Include .2ndbrain/config.yaml and .2ndbrain/index.db — the receiver gets the vault's as-embedded state and avoids re-embedding from scratch. For git-shared team vaults, 2nb vault create writes a .gitignore that excludes personal/local state (config, DBs, logs, recovery) and commits only schemas.yaml. Missing or corrupt config.yaml / index.db self-heal on next open with a one-line stderr warning — the vault never bricks.

Heads-up for scripters: 2nb search --json and 2nb ask --json now return envelopes ({mode, warnings, results} / {mode, warnings, answer, sources}; multi-turn asks via --history add rewritten_query). If you were parsing a raw array/object, extract .results / .answer.

MCP Server

The MCP server exposes 16 tools for AI coding assistants:

ToolDescription
kb_infoVault overview — doc types, schemas, counts, AI status
kb_searchHybrid BM25 + semantic search with filters
kb_askRAG Q&A — answer questions with source citations
kb_readRead full document or specific heading chunk
kb_listList documents with metadata filters
kb_createCreate document from template
kb_update_metaUpdate frontmatter with schema validation
kb_relatedGraph traversal to find connected documents
kb_structureGet document heading tree as JSON
kb_deleteDelete document from vault and index
kb_indexRebuild search index and generate embeddings
kb_suggest_linksSuggest semantically related documents to wikilink from a source doc
kb_polishAI copy-editor returns original + polished body for diff review
kb_git_activityRecent git commits that touched vault files (read-only)
kb_git_diffUnified diff of a file against HEAD
kb_git_statusUncommitted/untracked files in the vault

Each running 2nb mcp-server writes a sidecar status file to .2ndbrain/mcp/<pid>.json with PID, start time, parent PID, and the last 50 tool invocations. Run 2nb mcp status to list live servers, or use the Cmd+Shift+M status panel in the editor.

Claude Code

Add to ~/.claude.json:

{
  "mcpServers": {
    "2ndbrain": {
      "command": "2nb",
      "args": ["mcp-server"],
      "cwd": "/path/to/your/vault"
    }
  }
}

Cursor

Add to .cursor/mcp.json:

{
  "mcpServers": {
    "2ndbrain": {
      "command": "2nb",
      "args": ["mcp-server"],
      "cwd": "/path/to/your/vault"
    }
  }
}

Claude Desktop

Add to ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "2ndbrain": {
      "command": "/usr/local/bin/2nb",
      "args": ["mcp-server"],
      "cwd": "/path/to/your/vault"
    }
  }
}

Run 2nb mcp-setup for config snippets for additional tools (Gemini CLI, Amazon Q, Kiro).

Skill Files

Install a skill file to teach AI coding agents about your vault's CLI, MCP tools, and document format:

# See supported agents and status
2nb skills list

# Install for one agent
2nb skills install claude-code

# Install for all supported agents
2nb skills install --all

# Install globally (all projects, not just this vault)
2nb skills install claude-code --user

Supported agents: Claude Code, Cursor, Windsurf, GitHub Copilot, Kiro, Cline, Roo Code, JetBrains Junie.

macOS Editor

A native SwiftUI + AppKit editor with:

  • Markdown editing with Source / Split / Preview mode toggle (Preview is read-only — use Source or Split for editing)
  • Autosave toggle with 15s / 30s / 60s intervals in Preferences, low-disk warning, filename collision suffixing, pre-write crash snapshots
  • Merge conflict dialog — when a file changes externally while a tab is dirty, a 2-pane diff window shows On Disk vs Ancestor and Yours vs Ancestor
  • Configurable editor font family and size (Preferences via Cmd+,, zoom with Cmd+=/Cmd+-/Cmd+0)
  • Window toolbar (visible once a vault is open): New Note, Search, Quick Open
  • Editor toolbar (visible when a document is open): Save, Polish, Suggest Links, Share, Source/Split/Preview mode picker
  • Quick Open (Cmd+P), Command Palette (Cmd+Shift+P)
  • Search panel with semantic search toggle (Cmd+Shift+F)
  • Ask AI panel for RAG Q&A (Cmd+Shift+A)
  • Suggest Links (Cmd+Shift+L) — click-to-insert AI-suggested wikilinks to semantically related documents
  • Polish (Cmd+Option+P) — AI copy-edit the current document with an accept/reject diff preview
  • Vault Status — unified health panel (Vault menu) showing index state, embedding portability, stale docs, and provider reachability with Rebuild Index + Re-embed All buttons
  • AI Hub (AI menu > AI…, Cmd+Shift+,) — single merged surface for providers (enable/disable Bedrock / OpenRouter / Ollama), active embedding + generation models, and the full catalog grouped by vendor within each type (Embeddings first, Generation second; Anthropic / Amazon / Google / Meta / etc. as collapsible groups). Per-group bulk Enable all / Disable all, per-row Test · Set active · Enable · Disable, live search, and Discover. Replaces the previous three wizards (AI Setup, Test AI Connection, Model Wizard). Catalog changes made from a terminal propagate live via FSEvents
  • MCP Server Status (Cmd+Shift+M) — see which AI clients are connected and which tools they've invoked, plus a live status-bar indicator
  • Recent Activity (Cmd+Shift+G) — for vaults that are git repos, browse recent commits with 1/3/7/30-day window; click any commit for full detail with per-file diffs
  • Git diff viewer — right-click any file in the sidebar → Show Changes vs HEAD
  • Git sidebar indicators — orange dot for modified, blue dot for untracked
  • Interactive AI status popover with staleness indicator and index rebuild
  • Clickable vault name in status bar — opens Vault Status panel
  • Status bar shows document type, status, word count, chunk count, token estimate, AI dot, MCP dot
  • Index rebuild dialog with confirmation, progress bars, and stats summary
  • Tag drill-down navigation — click a tag to see filtered files, back button to return
  • Export as PDF, HTML, or Markdown (Notes > Export submenu, Cmd+Shift+X for PDF)
  • Menu taxonomy: Notes (file operations), Vault (vault operations + health), View (panels, search, zoom), AI (Ask AI, Suggest Links, Polish, Setup, Test, Skills, MCP)
  • Interactive link graph visualization
  • Wikilink autocomplete, backlinks panel, outline view
  • Tabs with dirty indicators, focus mode with hover-to-reveal toolbar
  • Sidebar context menu: Open, Duplicate, Find Similar, Show Changes vs HEAD, Delete
  • Drag .md files from Finder into the editor to open in new tabs
  • 6 document templates: Note, ADR, Runbook, Postmortem, PRD, PR/FAQ
  • Obsidian import/export
  • Spotlight indexing, crash recovery (parse-on-open corruption detection), file watching

Build and install:

make install    # Installs to ~/Applications

Document Types

TypeStatus StatesUse For
adrproposed -> accepted -> deprecated/supersededArchitecture decisions
runbookdraft -> active -> archivedOperational procedures
prddraft -> review -> approved -> shipped -> archivedProduct requirements
prfaqdraft -> review -> finalAmazon-style press release / FAQ
postmortemdraft -> reviewed -> publishedIncident analysis
notedraft -> completeGeneral knowledge

Documents are plain .md files with YAML frontmatter:

---
id: <UUID>
title: Use JWT for Authentication
type: adr
status: proposed
tags: [auth, security]
created: 2026-04-04T00:00:00Z
modified: 2026-04-04T00:00:00Z
---
# Use JWT for Authentication

Content with [[wikilinks]] to other documents.

Obsidian Compatible

Import an existing Obsidian vault:

2nb import-obsidian ~/my-obsidian-vault

This adds UUIDs, normalizes tags from inline #tag to frontmatter, and builds the search index. Your files stay as plain markdown.

Export back to Obsidian anytime:

2nb export-obsidian ~/export-dir --strip-ids

Development

make build          # CLI + macOS app
make install        # CLI to /usr/local/bin, app to ~/Applications
make test           # Go unit tests
make test-battery   # Golden-path E2E battery (vault, CRUD, index, MCP, skills)
make test-swift     # Swift unit tests (JSON decoding, parsing, wizard logic)
make test-gui       # GUI tests (AppleScript automation)
make test-all       # Go + battery + Swift + GUI

Requires Go 1.24+, CGO_ENABLED=1, macOS 14+ (for Swift app).

See CONTRIBUTING.md for details.

Releasing

Both the CLI and macOS editor are published to Homebrew via GitHub Actions.

# 1. Bump the version
make bump-build          # 0.1.8 → 0.1.9 (or bump-minor / bump-major)

# 2. Release — tags, pushes, and triggers CI
make release

make release updates CHANGELOG.md, commits, creates a git tag, and pushes it. GitHub Actions then:

  1. Builds CLI binaries (arm64 + x86_64) via GoReleaser
  2. Builds SecondBrain.app (arm64, swift build -c release)
  3. Creates a GitHub Release with all archives
  4. Pushes the Homebrew formula and cask to apresai/homebrew-tap

Users install with:

brew install apresai/tap/2nb                    # CLI
brew install --cask apresai/tap/secondbrain     # macOS editor (includes CLI)

To build a release locally (without GitHub Actions):

make release-local       # runs goreleaser locally (CLI only)
make package-app         # builds + zips SecondBrain.app locally

Note: The editor is ad-hoc signed, not notarized with Apple Developer ID. Users must right-click > Open on first launch to bypass Gatekeeper.

Architecture

cli/    Go CLI + MCP server (cobra, go-sqlite3, mcp-go, aws-sdk-go-v2)
app/    Swift macOS editor (SwiftUI, GRDB.swift, swift-markdown)
         |                    |
         +-------- shared ----+
              .2ndbrain/index.db (SQLite WAL)

The CLI and editor share the same SQLite database via WAL mode for concurrent access. All AI operations go through the provider interfaces in cli/internal/ai/.

License

MIT - Copyright (c) 2026 Apres AI

Ver o original no GitHub

Bom para

Relacionados