Skip to main content
Glama

brain-v42

Dauerhaftes Gedächtnis für Coding-Agenten, über MCP bereitgestellt.

brain-v42 gibt Claude Code, Codex und jedem anderen MCP-Client ein dauerhaftes zweites Gehirn: Entscheidungen, Erkenntnisse, Code-Snippets, Runbooks, ADRs, Tickets und Projekt-Roadmaps – gespeichert in PostgreSQL, abgerufen per Volltext- + semantischer Suche mit Re-Ranking und jede Nacht durch eine Agent-Pipeline konsolidiert.

  • Typisiertes Wissen, kein Notizdump — eine Entscheidung erfasst ihr WARUM und Alternativen; ein Snippet erfasst seine Absicht; ein Runbook erfasst ausführbare Schritte. Jeder Typ hat seinen eigenen Lebenszyklus (Supersession-Ketten, ADR-Akzeptanz, Lernvalidierung).

  • Expliziter Session-Lebenszyklus — der Benutzer kontrolliert jede Session-Grenze. Sessions erfassen die Artefakte, die sie produziert haben, und das Schließen ist fail-closed: Eine Session endet mit entweder erfasstem Wissen oder einem expliziten Grund „nichts zu erfassen“, niemals mit Schweigen.

  • Suche mit Ranking — pgvector-semantische Suche + PostgreSQL FTS, fusioniert und neu gerankt durch einen Cross-Encoder.

  • Nächtliche Konsolidierung („dream“) — eine Agent-Pipeline bereinigt verwaiste Links, führt Duplikate zusammen, synthetisiert Erkenntnisse und schlägt Hochstufungen vor, hinter Phasen- Killswitches, die alle geschlossen ausgeliefert werden.

  • Multi-Projekt — projektbezogener Fokus mit Compare-and-Swap-Revisionen, Roadmaps, projektübergreifenden Tickets.

Architektur

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-Transport: Produktion = HTTP-Loopback http://127.0.0.1:8765/mcp; Konfigurationsstandard und Dev/Fallback = stdio.

PostgreSQL ist die einzige Quelle der Wahrheit. Neo4j ist eine wegwerfbare Projektion, die von einer relationalen Ledger/Outbox gespeist wird — sie kann jederzeit aus PostgreSQL neu aufgebaut werden, nie umgekehrt. Der kanonische Pfad ist seit dem 22. Juli 2026 in Produktion aktiv; Design und Nachweise befinden sich in docs/ARCHITECTURE.md und dem Graph-Ledger-Runbook.

Embeddings sind optional und austauschbar. Der Server selbst ist modellagnostisch: Er spricht nur einen Drei-Routen-HTTP-Vertrag (POST /embed, POST /embed/query, POST /rerank) und degradiert elegant, wenn der Endpoint nicht erreichbar ist — brain_search fällt auf Volltextsuche zurück, Schreibvorgänge werden mit einem NULL-Embedding persistiert und später nachgefüllt. Jeder Server, der diesen Vertrag implementiert, funktioniert. Der mitgelieferte Referenz- Stack (services/) bedient Qodo-Embed-1-1.5B als GGUF über llama.cpp auf einer lokalen GPU. EMBEDDING_DIMENSION wird bei der Installation gewählt; ein späterer Modellwechsel bedeutet Neu-Einbettung des Korpus (scripts/regen_embeddings.py).

Related MCP server: Cortex MCP Server

Schnellstart

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

Binde es in Claude Code ein — .mcp.json im Repository-Root zielt bereits auf den Produktions- HTTP-Loopback-Endpoint; für ein einfaches Stdio-Dev-Setup:

claude mcp add brain-v42 -- python -m brain_v42.mcp.server

BRAIN_ALEMBIC_ALLOW_PROD wird nur benötigt, wenn der Datenbankname exakt brain lautet; behalte es als Ein-Befehl-Opt-in bei und exportiere es niemals dauerhaft. Alembic lehnt DSN-Abfrageparameter ab; verwende die obige einfache Form mit Host, Port, Benutzername und Passwort.

MCP-Tools

Domäne

Werkzeuge

Suche & Liste

brain_search, brain_list, brain_get, brain_update, brain_delete

Graph-Traversierung

brain_get_neighbors, brain_graph_path

Session-Lebenszyklus

brain_session_start, brain_session_list, brain_session_resume, brain_session_capture, brain_session_heartbeat, brain_session_end, brain_session_abandon

Projektkontext

brain_set_project_context, brain_update_project_focus, brain_list_projects, brain_list_project_groups

Entscheidungen

brain_log_decision, brain_supersede_decision, brain_get_supersession_chain

Erkenntnisse

brain_learn, brain_validate_learning

Snippets

brain_save_snippet, brain_use_snippet

Runbooks

brain_create_runbook, brain_get_runbook, brain_execute_runbook

ADRs

brain_propose_adr, brain_accept_adr, brain_deprecate_adr, brain_list_adrs

Koordination

brain_ticket_create, brain_ticket_reply, brain_ticket_transition, brain_ticket_list, brain_ticket_get

Dream / Graph

brain_get_clusters, brain_backfill_links_batch, brain_consolidation_candidates, brain_merge_entities, brain_refresh_entity, brain_reindex_plans, brain_list_orphans_for_classification, brain_assign_domain, brain_list_curation_proposals

Roadmap & Verfall

brain_get_roadmap, brain_feature_create, brain_feature_update, brain_decay_status

Workflow-Anleitung

brain_workflow_guide

Vollständiger Katalog mit Signaturen: docs/MCP_TOOLS.md.

Das Standard-Katalogprofil ist compact: Die sieben Session-Lebenszyklus-Tools bleiben sichtbar, und jedes andere Tool wird über zwei Gateways erreicht — brain_find_tool zum Entdecken, brain_call_tool zum Aufrufen. Setze BRAIN_MCP_PROFILE=native, um jedes Tool direkt verfügbar zu machen.

Sitzungen

Der Benutzer kontrolliert jede Session-Grenze: start, resume, end und abandon sind explizite Befehle, die nie von einem Hook, einem Agenten oder einem Client abgeleitet werden. Sessions erfassen die dauerhaften Artefakte, die sie produziert haben, in einem exklusiven Ledger, und das Schließen ist fail-closed: erfasstes Wissen oder ein expliziter Grund „nichts zu erfassen“, niemals Stille.

Nach 24 Stunden ohne Heartbeat zeigt eine offene Session is_stale=true an; der Marker wird abgeleitet, der persistente Status bleibt open, und nur der serverseitige Sieben-Tage-Sweep bricht eine Session ohne expliziten Benutzerbefehl ab.

Der vollständige Lebenszyklus-Vertrag (Erfassungsregeln, Fokus-Semantik, Briefing) befindet sich in docs/MCP_TOOLS.md; der Vertrag ist v4 und befindet sich noch in der Entwicklung.

Konfiguration (.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

Platziere MCP_HTTP_TOKEN oder MCP_HTTP_DREAM_TOKENS niemals in der gemeinsamen .env: Bearer- Tokens leben in einer privaten 0600-Datei (~/.config/brain-v42/mcp-token.env), und die Graph-Projector-Anmeldedaten in einer eigenen (~/.config/brain-v42/graph-projector.env). Vollständige Referenz — jede Variable, die privaten Secret-Dateien, Preflights und Rollout- Gates: docs/OPERATIONS.md.

Netzwerk-Vertrauensmodell

Das Deployment zielt auf persönliche Agenten in einem vertrauenswürdigen LAN. MCP, PostgreSQL und Neo4j binden an Loopback; Metriken und Automatisierung verwenden standardmäßig Loopback.

Embedding-Topologie: Produktion/Standard = lokaler einheitlicher Endpoint http://localhost:8003; deploy/dev-pc ist ein überholter Rollback-/Referenzpfad.

Der Reranker teilt sich den einheitlichen Embedding-Endpoint :8003/rerank. Behandle :8003 als LAN-exponiert, bis du selbst das Live-Bind nachgewiesen hast, und setze es – oder den MCP-Port – niemals dem Internet aus. Der Repository-Code allein beweist keinen Live-Firewall-Zustand.

Dream-Modus

Nächtliche Agent-Pipeline (scripts/dream.sh: scan → clean → connect → synth → promote → reorg) plus serverseitige Ticket-Extraktions-, Roadmap-Kurations- und Session-Sweep-Jobs. Jede mutierende Phase sitzt hinter einem Killswitch, und jeder Killswitch wird geschlossen ausgeliefert; Dry-run ist die ausgelieferte Standardeinstellung. Jede Phase läuft unter einer exakten MCP-Tool-Allowlist. Details: docs/ARCHITECTURE.md und docs/OPERATIONS.md.

Produktionsstand

Das Migrationsziel des Repositories ist Migration 045. Keine Seite in diesem Repository beweist einen Live-Schema-Head — miss es, lies es hier nicht ab:

docker exec brain_v42_postgres psql -U brain -d brain -Atc "select version_num from alembic_version;"

Der laufende Build nennt sich selbst: GET /health liefert version (die installierte Distribution) und alembic_head (die damit ausgelieferte Revision), beide gemessen, niemals von Hand geschrieben.

Entwicklung

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/
  • Stack: Python 3.12+, FastMCP 3.x, SQLAlchemy 2.0 async + asyncpg, Alembic, Pydantic 2, structlog.

  • TDD ist Pflicht — Rot, Grün, Refactoring; Tests werden niemals geändert, um Code bestehen zu lassen.

  • Coverage-Untergrenze: 60 % (CI blockiert darunter).

  • Die Dev-Toolchain ist exakt gepinnt (pip install -e ".[dev]"), sodass lokal immer mit CI übereinstimmt.

Projektstruktur

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

Der Top-Level-Modulgraph wird in CI azyklisch erzwungen (scripts/check_module_layering.py): Jedes Modul kann weiterhin in einen eigenständigen Dienst extrahiert werden, ohne einen Zyklus mitzuziehen.

CI/CD

Stufen: lint → test → security → build. Security-Gates: pip-audit, bandit, gitleaks, Container-Image-Pin-Checks. Docker-Images werden auf main gebaut und gepusht; es gibt keine Deploy-Stufe — das Ausrollen auf einen Host ist immer ein manueller, Out-of-Band-Schritt. Releases sind Tag-getrieben: Die Release-Rail baut das Wheel + sdist, weist nach, dass das Wheel seine Migrationen mitliefert, und hängt beides an das GitHub-Release.

Versionierung

  • Die ausgelieferte Version ist 0.2.0, und sie bleibt bewusst 0.x: Ein 1.0.0 würde eine stabile Schnittstelle und einen Rückweg versprechen, und dieses Projekt hat beides noch nicht.

  • Es wird kein verlustfreies Downgrade versprochen, bei keiner Version. Zwei Migrationen verweigern ihr eigenes downgrade: 037 wirft eine SQL-EXCEPTION, sobald eine Session-Erfassung verloren ginge, und 039 wirft, sofern der Operator kein explizites -x-Opt-in angibt.

  • Ein Schema-Rollback ist daher ein Operator-Verfahren mit einem Runbook, niemals eine Versions- garantie — stattdessen aus einem Snapshot wiederherstellen.

Lizenz

Quellcode: Apache-2.0.

Die Modellgewichte sind nicht von dieser Lizenz abgedeckt, und das ist keine Formalität. Das Produktions-Embedding-Modell Qodo/Qodo-Embed-1-1.5B wird unter QodoAI-Open-RAIL-M veröffentlicht – einer Lizenz mit nutzungsbasierten Einschränkungen, nicht einer permissiven. In diesem Repository werden keine Gewichte gespeichert oder verteilt: Jedes Modell wird zur Build-Zeit von seinem Upstream-Host vom Betreiber heruntergeladen, der die Bedingungen jedes Modells direkt von dessen Herausgeber akzeptiert. Siehe NOTICE, bevor Sie etwas weiterverteilen.

Available Tools

11 tools
brain_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_abandonB
DestructiveIdempotent

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_bindA
Idempotent

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_captureA
Idempotent

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_endA
DestructiveIdempotent

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_listA
Read-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_relayA
DestructiveIdempotent

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_resumeB
Read-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_startA
Idempotent

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

    A3.6/5.0

    Scored across 11 tools

    Disambiguation3/5

    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.

    Naming Consistency4/5

    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.

    Tool Count4/5

    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.

    Completeness4/5

    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

    ActivityNo data
    ResponsivenessSyncing

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Provides 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.
      18
      34 npm
      1
      AGPL 3.0
    • A
      license
      Not graded
      quality
      B
      maintenance
      Provides persistent, searchable memory across coding projects and machines, letting agents record and retrieve projects, reusable assets, sessions, decisions, commits, and handoffs via MCP.
      3
      Apache 2.0
    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables 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
      -