brain-v42
brain-v42
为编码代理提供的持久记忆,通过 MCP 提供服务。
brain-v42 为 Claude Code、Codex 以及任何其他 MCP 客户端提供一个持久的第二大脑: 决策、经验、代码片段、runbook、ADR、工单和项目路线图—— 存储在 PostgreSQL 中,通过全文 + 语义搜索(带重排序)检索,并由代理管道每晚整合。
类型化知识,而非笔记堆砌 —— 决策记录其 WHY 和备选方案; 代码片段记录其意图;runbook 记录可执行的步骤。每种类型都有自己的生命周期(取代链、ADR 接受、经验验证)。
明确的会话生命周期 —— 每个会话边界都由用户掌控。会话捕获其产生的制品,关闭是 fail-closed 的:会话要么以已捕获知识结束,要么以明确的“无可捕获内容”原因结束,绝不沉默。
带排序的搜索 —— pgvector 语义搜索 + PostgreSQL FTS,通过 cross-encoder 融合并重新排序。
夜间整合(“dream”) —— 代理管道清理孤立链接、合并重复项、综合经验并提出提升建议,每个阶段都位于默认关闭的 killswitch 之后。
多项目 —— 按项目聚焦,支持 compare-and-swap 修订、路线图和跨项目工单。
架构
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 是一个可丢弃的投影,由关系型 ledger/outbox 提供数据——它随时可以从 PostgreSQL 重建,绝无反向。自 2026 年 7 月 22 日起,这条规范路径已在生产环境启用;设计与证据位于 docs/ARCHITECTURE.md 和 graph ledger runbook 中。
Embedding 是可选的、可插拔的。服务器本身与模型无关:它只通过一个三路由 HTTP 契约进行通信(POST /embed、POST /embed/query、POST /rerank),当端点不可用时优雅降级——brain_search 回退到全文搜索,写入以 NULL embedding 持久化,稍后回填。任何实现该契约的服务器都可以工作。捆绑的参考栈(services/)以 GGUF 格式,通过本地 GPU 上的 llama.cpp 提供 Qodo-Embed-1-1.5B。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.server将其接入 Claude Code — 仓库根目录下的 .mcp.json 已经指向生产 HTTP 环回端点;如需简单的 stdio 开发设置:
claude mcp add brain-v42 -- python -m brain_v42.mcp.serverBRAIN_ALEMBIC_ALLOW_PROD 仅在数据库名称恰好为 brain 时需要;请保持其为一次性命令的选择加入,切勿持久导出。Alembic 拒绝 DSN 查询参数;请使用上述带有主机、端口、用户名和密码的普通形式。
MCP 工具
领域 | 工具 |
搜索与列表 |
|
图遍历 |
|
会话生命周期 |
|
项目上下文 |
|
决策 |
|
经验 |
|
代码片段 |
|
Runbook |
|
ADR |
|
协同 |
|
Dream / 图 |
|
路线图与衰减 |
|
工作流指导 |
|
完整目录(含签名):docs/MCP_TOOLS.md。
默认目录配置为 compact:七个会话生命周期工具保持可见,所有其他工具通过两个网关访问——brain_find_tool 用于发现,brain_call_tool 用于调用。设置 BRAIN_MCP_PROFILE=native 可直接暴露所有工具。
会话
用户掌控每个会话边界:start、resume、end 和 abandon 都是显式命令,绝不由 hook、代理或客户端推断。会话将其产生的持久制品捕获到专属账本中,关闭是 fail-closed 的:要么是已捕获的知识,要么是明确的“无可捕获内容”原因,绝不沉默。
超过 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=INFO切勿将 MCP_HTTP_TOKEN 或 MCP_HTTP_DREAM_TOKENS 放入共享的 .env 中:bearer 令牌存放在私有 0600 文件(~/.config/brain-v42/mcp-token.env)中,graph projector 凭据则存放在其专属文件(~/.config/brain-v42/graph-projector.env)中。完整参考——每个变量、私有机密文件、预检和发布门禁:docs/OPERATIONS.md。
网络信任模型
该部署面向可信 LAN 上的个人代理。MCP、PostgreSQL 和 Neo4j 绑定到环回地址;指标和自动化默认使用环回地址。
Embedding 拓扑:生产/默认 = 本地统一端点 http://localhost:8003;deploy/dev-pc 是一条已被取代的回滚/参考路径。
重排序器共享统一 embedding 端点 :8003/rerank。在你自己证实实际绑定之前,请将 :8003 视为暴露在 LAN 上,切勿将其——或 MCP 端口——暴露到互联网。仅凭仓库代码无法证明实时防火墙状态。
Dream 模式
夜间代理管道(scripts/dream.sh:scan → clean → connect → synth → promote → reorg),外加服务器端的工单提取、路线图整理和会话清理任务。每个变更阶段都位于 killswitch 之后,且每个 killswitch 默认关闭;dry-run 是发布默认。每个阶段在精确的 MCP 工具允许列表下运行。详情:docs/ARCHITECTURE.md 和 docs/OPERATIONS.md。
生产状态
仓库的迁移目标是迁移 045。本仓库中没有页面能证明实际的 schema head——请实测,不要在此处阅读:
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, runbooks顶层模块图在 CI 中强制无环(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将承诺稳定的接口和回退途径,而这个项目两者都还没有。在任何版本下都不承诺无损降级。 有两个迁移拒绝自身的
downgrade:037 在会话捕获即将丢失时立即抛出 SQLEXCEPTION;039 除非操作员传入显式的-x选择加入,否则抛出异常。因此,回滚 schema 是带有 runbook 的操作员流程,而非版本保证——请改为从快照恢复。
许可证
源代码: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-