brain-v42
brain-v42
코딩 에이전트를 위한 영구 메모리, MCP로 제공됩니다.
brain-v42는 Claude Code, Codex 및 기타 모든 MCP 클라이언트에 지속적인 두 번째 두뇌를 제공합니다: 결정, 학습, 코드 스니펫, 런북, ADR, 티켓 및 프로젝트 로드맵 — PostgreSQL에 저장되고, 전문(full-text) + 의미론적 검색과 재랭킹으로 검색되며, 매일 밤 에이전트 파이프라인에 의해 통합됩니다.
유형화된 지식, 메모 덤프가 아님 — 결정은 그 이유(WHY)와 대안을 기록하고, 스니펫은 의도를 기록하며, 런북은 실행 가능한 단계를 기록합니다. 각 유형은 고유한 수명 주기를 가집니다(supersession 체인, 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이 단일 진실 공급원(single source of truth)입니다. Neo4j는 관계형 원장/아웃박스(ledger/outbox)에서 공급되는 일회용 프로젝션입니다. 항상 PostgreSQL에서 재구축할 수 있으며, 결코 그 반대는 아닙니다. 표준 경로는 2026년 7월 22일부터 프로덕션에서 활성화되었습니다. 설계와 증거는 docs/ARCHITECTURE.md 및 그래프 원장 런북에 있습니다.
임베딩은 선택 사항이며 플러그인 방식입니다. 서버 자체는 모델에 구애받지 않습니다. 세 개의 라우트로 구성된 HTTP 계약(POST /embed, POST /embed/query, POST /rerank)만 사용하며, 엔드포인트가 없으면 우아하게 성능이 저하됩니다. 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인 경우에만 필요합니다. 일회성 명령 옵트인으로 유지하고, 영구적으로 내보내지 마십시오. Alembic은 DSN 쿼리 매개변수를 거부합니다. 위의 일반 형식을 host, port, username, password를 모두 포함하여 사용하십시오.
MCP 도구
도메인 | 도구 |
검색 및 목록 |
|
그래프 탐색 |
|
세션 수명 주기 |
|
프로젝트 컨텍스트 |
|
결정 |
|
학습 |
|
스니펫 |
|
런북 |
|
ADRs |
|
조정 |
|
Dream / 그래프 |
|
로드맵 및 감쇠 |
|
워크플로 안내 |
|
전체 카탈로그 및 시그니처: docs/MCP_TOOLS.md.
기본 카탈로그 프로필은 compact입니다. 일곱 개의 세션 수명 주기 도구는 계속 표시되며, 다른 모든 도구는 두 개의 게이트웨이를 통해 접근합니다 — 탐색을 위한 brain_find_tool, 호출을 위한 brain_call_tool입니다. BRAIN_MCP_PROFILE=native로 설정하면 모든 도구가 직접 노출됩니다.
세션
사용자는 모든 세션 경계를 제어합니다: start, resume, end, abandon은 후크, 에이전트 또는 클라이언트가 추론하지 않는 명시적 명령입니다. 세션은 생성한 지속 가능한 산출물을 전용 원장에 캡처하며, 종료는 실패 시 잠금 방식입니다. 캡처된 지식 또는 명시적인 “캡처할 것이 없음” 사유, 결코 침묵이 아닙니다.
하트비트 없이 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: scan → clean → connect → synth → promote → reorg) 및 서버 측 티켓 추출, 로드맵 큐레이션, 세션 스윕 작업. 모든 변경 단계는 킬 스위치 뒤에 있으며 모든 킬 스위치는 기본적으로 닫혀 있고, 드라이런이 기본 배포입니다. 각 단계는 정확한 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, 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옵트인을 전달하지 않으면 발생합니다.따라서 스키마 롤백은 버전 보장이 아닌 런북을 통한 운영자 절차입니다. 대신 스냅샷에서 복원하십시오.
라이선스
소스 코드: Apache-2.0.
모델 가중치는 해당 라이선스의 적용을 받지 않습니다, 그리고 이는 형식적인 문제가 아닙니다. 프로덕션 임베딩 모델인 Qodo/Qodo-Embed-1-1.5B는 QodoAI-Open-RAIL-M에 따라 게시됩니다 — 즉, 허용적(permissive) 라이선스가 아니라 사용 기반 제한이 있는 라이선스입니다. 이 저장소에는 어떤 가중치도 저장되거나 배포되지 않습니다: 모든 모델은 빌드 시 운영자가 업스트림 호스트에서 다운로드하며, 운영자는 각 모델의 이용 약관을 게시자로부터 직접 수락합니다. 무엇이든 재배포하기 전에 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-