brain-v42
brain-v42
MCP上で提供される、コーディングエージェント向けの永続メモリ。
brain-v42は、Claude Code、Codex、その他のMCPクライアントに永続的なセカンドブレインを提供します:決定、学び、コードスニペット、ランブック、ADR、チケット、プロジェクトロードマップをPostgreSQLに保存し、全文検索+セマンティック検索とリランキングで取得し、毎晩エージェントパイプラインによって統合されます。
型付けされた知識であり、単なるメモの寄せ集めではない — 決定はそのWHYと代替案を記録し、スニペットはその意図を記録し、ランブックは実行可能なステップを記録します。各型は独自のライフサイクルを持ちます(置き換えチェーン、ADRの受理、ラーニングの検証)。
明示的なセッションライフサイクル — すべてのセッション境界はユーザーが所有します。セッションは生成した成果物を記録し、クローズはフェイルクローズです:セッションは、記録された知識または明示的な「nothing to capture」という理由のいずれかで終了し、決して沈黙はしません。
ランキングを行う検索 — pgvectorによるセマンティック検索 + PostgreSQL FTSを、クロスエンコーダーで融合して再ランキングします。
夜間の統合(「dream」) — エージェントパイプラインが、孤立リンクの掃除、重複のマージ、ラーニングの統合、プロモーションの提案を行います。すべてのフェーズは初期状態で無効化されたキルスイッチの背後で実行されます。
マルチプロジェクト — プロジェクトごとのフォーカスに、比較と交換によるリビジョン、ロードマップ、プロジェクト横断のチケット。
アーキテクチャ
Claude Code / Codex (MCP client)
│ HTTP loopback :8765/mcp (production) · stdio (dev/fallback)
brain-v42 (FastMCP)
├── SQLAlchemy async ─▶ PostgreSQL 16 + pgvector (source of truth)
├── HTTP ─────────────▶ embedding endpoint :8003 (optional, pluggable)
├── HTTP ─────────────▶ :8003/rerank (optional reranker)
└── bolt ─────────────▶ Neo4j 5 Community (relationship index, optional)MCPトランスポート:本番 = HTTPループバック http://127.0.0.1:8765/mcp; 設定デフォルトおよび開発/フォールバック = stdio。
PostgreSQLが唯一の真実源です。Neo4jはリレーショナルな台帳/アウトボックスから供給される使い捨て可能なプロジェクションであり、常にPostgreSQLから再構築できますが、その逆はありません。この正規パスは2026年7月22日から本番で稼働しています。設計と根拠はdocs/ARCHITECTURE.mdとgraph ledger runbookにあります。
埋め込みはオプションかつプラグイン可能です。サーバー自体はモデル非依存です。POST /embed、POST /embed/query、POST /rerank の3ルートからなるHTTP契約のみを話し、エンドポイントが利用できない場合はグレースフルに劣化します。brain_searchは全文検索にフォールバックし、書き込みはNULL埋め込みで永続化され、後でバックフィルされます。この契約を実装するサーバーならどれでも動作します。バンドルされているリファレンススタック(services/)は、ローカルGPU上のllama.cppを介してQodo-Embed-1-1.5BをGGUFとして提供します。EMBEDDING_DIMENSIONはインストール時に選択され、後でモデルを切り替える場合はコーパスの再埋め込み(scripts/regen_embeddings.py)が必要です。
Related MCP server: Cortex MCP Server
クイックスタート
git clone https://github.com/hawkixs/brain-v42 && cd brain-v42
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
# 1. Local Neo4j secret (skip if you run without the graph)
install -d -m 0700 .secrets
read -rsp "Neo4j password (same value as NEO4J_PASSWORD in .env): " PW
(umask 0022; printf 'neo4j/%s\n' "$PW" > .secrets/neo4j-auth); unset PW
# 2. Databases (PostgreSQL 16 + pgvector, Neo4j)
docker compose up -d
# 3. Migrations
export POSTGRES_URL="postgresql+asyncpg://brain:REPLACE_WITH_PASSWORD@localhost:5433/brain"
BRAIN_ALEMBIC_ALLOW_PROD=1 alembic upgrade head
# 4. Run the MCP server (stdio)
python -m brain_v42.mcp.serverClaude Codeに配線するには、リポジトリルートの.mcp.jsonがすでに本番HTTPループバックエンドポイントを対象にしています。プレーンなstdio開発セットアップの場合は:
claude mcp add brain-v42 -- python -m brain_v42.mcp.serverBRAIN_ALEMBIC_ALLOW_PRODは、データベース名が正確にbrainの場合にのみ必要です。これを1コマンドのオプトインに留め、永続的にエクスポートしないでください。AlembicはDSNクエリパラメータを拒否します。上記のプレーンな形式で、ホスト、ポート、ユーザー名、パスワードをすべて指定してください。
MCPツール
ドメイン | ツール |
検索と一覧 |
|
グラフ探索 |
|
セッションライフサイクル |
|
プロジェクトコンテキスト |
|
決定 |
|
ラーニング |
|
スニペット |
|
ランブック |
|
ADR |
|
調整 |
|
dream / グラフ |
|
ロードマップと減衰 |
|
ワークフローガイダンス |
|
シグネチャ付きの完全なカタログ:docs/MCP_TOOLS.md。
デフォルトのカタログプロファイルはcompactです。7つのセッションライフサイクルツールは表示されたままになり、その他のすべてのツールは2つのゲートウェイ、つまり発見のためのbrain_find_toolと呼び出しのためのbrain_call_toolを介してアクセスされます。BRAIN_MCP_PROFILE=nativeを設定すると、すべてのツールを直接公開できます。
セッション
ユーザーはすべてのセッション境界を制御します。start、resume、end、abandonは明示的なコマンドであり、フック、エージェント、クライアントによって推測されることはありません。セッションは生成した永続的な成果物を排他的な台帳に記録し、クローズはフェイルクローズです。記録された知識、または明示的な「nothing to capture」という理由のいずれかであり、沈黙はありません。
ハートビートが24時間ない場合、オープン中のセッションはis_stale=trueを公開します。このマーカーは導出されるものであり、永続的なステータスはopenのままです。明示的なユーザーコマンドなしにセッションを放棄するのは、7日間のサーバーサイドスイープだけです。
完全なライフサイクル契約(キャプチャルール、フォーカスセマンティクス、ブリーフィング)はdocs/MCP_TOOLS.mdにあります。契約はv4であり、まだ進化中です。
設定 (.env)
# Required
POSTGRES_URL=postgresql+asyncpg://brain:REPLACE_WITH_PASSWORD@localhost:5433/brain
# Optional — semantic search and reranking
EMBEDDING_SERVICE_URL=http://localhost:8003
EMBEDDING_DIMENSION=1536
RERANKER_URL=http://localhost:8003
# Optional — relationship graph (safe defaults for a fresh environment)
GRAPH_ENABLED=false
GRAPH_LEDGER_WRITE_ENABLED=false
# Tool catalog profile
BRAIN_MCP_PROFILE=compact # compact (default) or native
LOG_LEVEL=INFOMCP_HTTP_TOKENやMCP_HTTP_DREAM_TOKENSを共有の.envに置かないでください。ベアラートークンはプライベートな0600ファイル(~/.config/brain-v42/mcp-token.env)に置き、グラフプロジェクターの認証情報は専用のファイル(~/.config/brain-v42/graph-projector.env)に置きます。完全なリファレンス — すべての変数、プライベートな秘密ファイル、事前チェック、ロールアウトゲート: docs/OPERATIONS.md。
ネットワーク信頼モデル
このデプロイは、信頼できるLAN上の個人エージェントを対象としています。MCP、PostgreSQL、Neo4jはループバックにバインドされ、メトリクスと自動化もデフォルトでループバックです。
埋め込みトポロジー:本番/デフォルト = ローカル統合エンドポイント http://localhost:8003; deploy/dev-pcは置き換えられたロールバック/リファレンスパスです。
リランカーは統合埋め込みエンドポイント:8003/rerankを共有します。自分で実際のバインドを確認するまで:8003はLANに公開されているものとして扱い、インターネットには決して公開しないでください(MCPポートも同様です)。リポジトリのコードだけでは、実際のファイアウォールの状態を証明できません。
Dreamモード
夜間のエージェントパイプライン(scripts/dream.sh:スキャン → クリーン → 接続 → 統合 → プロモート → 再編成)に加え、サーバーサイドのチケット抽出、ロードマップキュレーション、セッションスイープジョブがあります。変更を伴うすべてのフェーズはキルスイッチの背後にあり、すべてのキルスイッチは初期状態で無効化されています。ドライランが標準のデフォルトです。各フェーズは正確なMCPツール許可リストの下で実行されます。詳細: docs/ARCHITECTURE.md と docs/OPERATIONS.md。
本番状態
リポジトリのマイグレーションターゲットはマイグレーション045です。このリポジトリのどのページも、実際のスキーマヘッドを証明するものではありません — ここで読むのではなく、測定してください:
docker exec brain_v42_postgres psql -U brain -d brain -Atc "select version_num from alembic_version;"実行中のビルドはそれ自体を名乗ります。GET /healthはversion(インストールされたディストリビューション)とalembic_head(それに同梱されるリビジョン)を返します。どちらも測定された値であり、手書きされることはありません。
開発
pytest tests/unit -v # no PostgreSQL required
pytest --cov=brain_v42 --cov-report=term-missing
ruff check src/ tests/ && ruff format --check src/ tests/
mypy src/スタック: Python 3.12+、FastMCP 3.x、SQLAlchemy 2.0 async + asyncpg、Alembic、Pydantic 2、structlog。
TDDは必須 — レッド、グリーン、リファクタリング。コードを通過させるためにテストを編集することは決してありません。
カバレッジ下限: 60%(CIがそれ未満をブロックします)。
開発ツールチェーンは正確に固定されています(
pip install -e ".[dev]")。これにより、ローカルは常にCIと一致します。
プロジェクト構成
brain-v42/
├── src/brain_v42/
│ ├── config.py # pydantic-settings — single config surface
│ ├── db/ # SQLAlchemy engine + tables
│ ├── models/ # Pydantic models
│ ├── repositories/ # CRUD + FTS + pgvector + graph adapters
│ ├── services/ # business logic, embedding, reranker, dream, dedup
│ ├── metrics/ # sidecar + collector + cockpit endpoint
│ ├── automation/ # independent webhook/dedup runtime (:9201)
│ └── mcp/ # FastMCP server + brain_*/dream_* tool handlers
├── tests/{unit,integration}
├── alembic/versions/ # migrations (shipped inside the wheel)
├── scripts/ # operational CLIs (dream.sh, canaries, repair)
├── services/ # GPU embedding service + shim + supervisor
├── deploy/ # systemd units, per-host compose, install.sh
└── docs/ # ARCHITECTURE, SCHEMA, MCP_TOOLS, OPERATIONS, runbooksCIではトップレベルのモジュールグラフが非巡回であることが強制されます(scripts/check_module_layering.py)。これにより、どのモジュールもサイクルを引きずらずにスタンドアロンサービスとして抽出できます。
CI/CD
ステージ:lint → test → security → build。セキュリティゲート:pip-audit、bandit、gitleaks、コンテナイメージのピン留めチェック。Dockerイメージはmain上でビルドされプッシュされます。デプロイステージはありません。ホストへのロールアウトは常に手動の帯域外ステップです。リリースはタグ駆動です。リリースレールはwheel + sdistをビルドし、wheelがマイグレーションを同梱していることを証明し、両方をGitHubリリースに添付します。
バージョニング
出荷バージョンは0.2.0であり、意図的に
0.xのままです。1.0.0は安定したインターフェースと後戻りの道を約束することになりますが、このプロジェクトにはそのどちらもまだありません。どのバージョンでも、ロスレスなダウングレードは保証されません。 2つのマイグレーションは自身の
downgradeを拒否します。037はセッションキャプチャが失われるとすぐにSQLEXCEPTIONを発生させ、039はオペレーターが明示的な-xオプトインを渡さない限り発生させます。したがって、スキーマのロールバックはランブックを伴うオペレーター手順であり、バージョン保証ではありません。代わりにスナップショットから復元してください。
ライセンス
ソースコード: Apache-2.0。
モデルの重みはそのライセンスの対象ではありません。これは形式的なものではありません。本番用埋め込みモデル Qodo/Qodo-Embed-1-1.5B は、QodoAI-Open-RAIL-M の下で公開されています — これは、使用に基づく制限を伴うライセンスであり、寛容なライセンスではありません。このリポジトリには重みは保存も配布もされていません:すべてのモデルは、ビルド時にオペレーターがアップストリームのホストからダウンロードし、各モデルの規約をその発行元から直接受け入れます。再配布する前に NOTICE を参照してください。
Available Tools
11 toolsbrain_call_toolA
Call a tool by name with the given arguments.
Use this to execute tools discovered via search_tools.
Inputs: name (required), arguments.
brain_find_toolA
Search for tools using natural language.
Returns up to 5 matching tools ranked by relevance, each as a summary: name, one-line description, required parameters with types, optional parameter names. Pass an exact tool name to get that tool's full input schema.
Inputs: query (required). Returns: result
brain_session_abandonBDestructiveIdempotent
Abandon a session only from an explicit user command.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: reason (required), session_id (required), expected_client_key (required).
brain_session_bindAIdempotent
Bind an open operator session to one focus slot, from an explicit user command.
Once per session; binding the same slot again is a replay. From then on the
session's end writes that slot only, never the project base:
expected_focus_revision is the slot revision returned here. Refusals:
session_not_open, session_is_agent_trace, session_already_bound,
slot_not_found, slot_closed, slot_project_mismatch, slot_busy.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: slot_id (required), session_id (required), expected_client_key (required). Returns: `brain_session_bind`: the slot revision an end or relay must send next.
brain_session_captureAIdempotent
Attach durable artifacts from an explicit user command — to repair or refine.
No longer a compulsory ritual. With derived capture armed, artifacts
created during the session are attributed without this call, and end
no longer demands a receipt. What this tool is for now: attaching
something the derivation could not see — created outside the window,
on another connection, or in another project — and saying so on the
record.
It never steals: an artifact already attributed stays where it is.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: session_id (required), knowledge_ids (required), expected_client_key (required).
brain_session_endADestructiveIdempotent
End a session from an explicit user command, on judgement alone.
nothing_to_capture_reason is now OPTIONAL. The old rule — a non-empty
ledger XOR a written reason — measured whether the client had DECLARED
its work. Derived capture feeds that signal from the server, and a check
is hollow the moment the thing it checks can influence its own signal;
worse, it made a session whose ledger the server had filled impossible
to close. Give a reason if you have one to give; a blank one is still
refused, because saying nothing and saying " " are not the same act.
What end still requires is what the server cannot produce for you:
a summary and a next focus. It REPORTS unattributed_in_window —
artifacts of this project created during the session that belong to no
ledger — as a measure, never a gate. It cannot refuse a close, and a
session cannot improve it by doing nothing.
For a bound session, expected_focus_revision is the SLOT revision (from
bind, resume, or relay's slot.revision), never started_focus_revision.
For an UNBOUND session, next_focus REPLACES the project's whole base focus
under a compare-and-swap on expected_focus_revision. SHRINK GUARD: a
next_focus under 70% of the current base focus is refused before any write
(base_focus_shrink, current, proposed and floor in the message) and the
session stays open, so carry the durable content over and call again. A bound
end REPLACES the whole slot body and meets the same 70% guard
(slot_focus_shrink). allow_focus_shrink = true requires an active
/brain-admin elevation for this credential and MCP connection; otherwise
focus_shrink_override_refused is raised before any mutation. Shared-token
and stdio callers cannot override; an operator relay can. A stale revision is still
recorded as a conflict and closes the session, since nothing is written.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: summary (required), next_focus (required), session_id (required), expected_client_key (required), +3 more. Returns: Outcome of ending a session and conditionally updating shared focus.
brain_session_heartbeatA
Refresh an open session from an explicit user command.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: session_id (required), expected_client_key (required).
brain_session_listARead-onlyIdempotent
List sessions only in response to an explicit user command.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: limit, offset, status, project_key.
brain_session_relayADestructiveIdempotent
Relay an open session onto its slot, or its project base: capture, end, restart.
One transaction: the named knowledge_ids are captured into the old session,
the handover is written under a compare-and-swap, the old session ends, and
a successor opens under new_client_key; its briefing follows. Two forms,
and exactly one revision per call.
briefing defaults to full detail; compact returns counts and IDs in at
most 4,000 characters. Focus text appears only in session.started_focus.
Bound session: send expected_slot_revision; the handover (at most 4,000
characters) REPLACES the whole slot body and the successor stays on the slot. A
closed slot or a stale revision changes nothing and leaves the session open.
Unbound session: send expected_focus_revision, the BASE revision; the
handover becomes the project's whole base focus and the successor is
unbound. A stale revision (focus_revision_conflict) changes nothing and
leaves the session open, unlike end, which closes anyway. SHRINK GUARD: a
handover under 70% of the current base focus is refused (base_focus_shrink,
both lengths in the message), because it REPLACES the whole base: carry the
durable content over. An operator relay may pass allow_focus_shrink = true
only with an active /brain-admin elevation for this credential and MCP
connection; a guard mod never can.
The same 70% guard applies to a bound slot body (slot_focus_shrink).
The override is enforced before mutation: only initiator='operator' can
pass it, and only with an active /brain-admin elevation for this credential
and MCP connection. A guard_mod relay is refused even if elevated.
An equal replay returns the same successor with replayed = true; any other
payload on an ended session is terminal_conflict. The successor's next end
or relay sends result.slot.revision (bound: the SLOT revision, from bind,
resume, or relay) or result.focus_revision (unbound: the new BASE revision),
never started_focus_revision for a bound one.
A guard mod the operator explicitly enabled may make this call as a standing
user command, and only this one (Amendment — slot relay (ADR #34)); with
initiator = 'guard_mod' it is refused while
BRAIN_SESSION_RELAY_GUARD_MOD_ENABLED is false.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: summary (required), handover (required), initiator (required), session_id (required), +8 more. Returns: `brain_session_relay`: the ended session, its successor, what the CAS wrote. A…
brain_session_resumeBRead-onlyIdempotent
Resume an open session from an explicit user command.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: session_id (required), expected_client_key (required). Returns: Current context returned when attaching to an open session.
brain_session_startAIdempotent
Start or replay a concurrent session from an explicit user command.
briefing defaults to full detail; compact returns counts and IDs in at
most 4,000 characters. Focus text appears only in session.started_focus.
An agent tracer is the only session the server opens or closes on its own; no hook and no auto-close may invoke this lifecycle boundary.
Inputs: client_key (required), project_key (required), briefing. Returns: Outcome of an idempotent session start.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 11 tools
The nine brain_session_* tools each nominally target a distinct lifecycle action, and the verbose descriptions clarify nuances, but several boundaries overlap heavily — relay internally performs capture+end+start, making it confusable with end/start, and start vs resume vs bind blur together. An agent could plausibly pick the wrong lifecycle tool for a given situation.
All names are snake_case with a consistent brain_ prefix, so the set is readable. There is a minor structural deviation: session tools use brain_<noun>_<verb> (brain_session_start) while the meta tools use brain_<verb>_<noun> (brain_call_tool, brain_find_tool), but the pattern is still predictable.
11 tools is within the well-scoped 3-15 range. The session lifecycle legitimately needs many operations, though nine session tools plus two meta tools is on the heavier side for what is essentially one domain.
The session lifecycle is thoroughly covered — start, heartbeat, capture, resume, bind, relay, end, abandon, list — plus meta tools for discovery and invocation. The only notable gap is that slots/focus are referenced extensively in relay/end but no tool here creates or manages slots, leaving a potential dead end for that sub-resource.
Maintenance
Related MCP Connectors
Persistent memory, knowledge graph, task management and more for AI agents via MCP.
Team memory for AI coding agents and code reviews, reviewed by humans and served over MCP.
Persistent memory and cross-session learning for AI coding assistants (hosted remote MCP).
Hosted MCP memory for coding agents: persistent across sessions, editable markdown, team sharing.
Related MCP Servers
- AlicenseAqualityDmaintenanceProvides persistent memory for AI coding agents via MCP, enabling teams to share and recall facts across sessions. Automatically captures, classifies, and curates knowledge from supported transcript sources.1834 npm1AGPL 3.0
- AlicenseNot gradedqualityCmaintenanceProvides persistent memory and task management for coding agents via MCP tools, enabling mid-session recall and capture of durable knowledge.12MIT
- AlicenseNot gradedqualityBmaintenanceProvides persistent, searchable memory across coding projects and machines, letting agents record and retrieve projects, reusable assets, sessions, decisions, commits, and handoffs via MCP.3Apache 2.0
- FlicenseNot gradedqualityCmaintenanceEnables AI coding agents and IDEs to capture conversations, extract structured knowledge into a queryable graph database, and recall past decisions, patterns, files, and errors across all projects and workspaces. Provides persistent memory tools for saving, searching, and cleaning up knowledge via MCP.2-