Skip to main content
Glama

brain-v42

Memoria persistente para agentes de codificación, servida a través de MCP.

brain-v42 ofrece a Claude Code, Codex y cualquier otro cliente MCP un segundo cerebro duradero: decisiones, aprendizajes, fragmentos de código, runbooks, ADRs, tickets y hojas de ruta de proyectos — almacenados en PostgreSQL, recuperados mediante búsqueda de texto completo + semántica con reranking, y consolidados cada noche por un pipeline de agentes.

  • Conocimiento tipado, no un volcado de notas — una decisión registra su POR QUÉ y sus alternativas; un fragmento registra su intención; un runbook registra pasos ejecutables. Cada tipo tiene su propio ciclo de vida (cadenas de sustitución, aceptación de ADR, validación de aprendizajes).

  • Ciclo de vida de sesión explícito — el usuario controla cada límite de sesión. Las sesiones capturan los artefactos que produjeron, y el cierre es a prueba de fallos: una sesión termina con conocimiento capturado o con una razón explícita de «nada que capturar», nunca en silencio.

  • Búsqueda con ranking — búsqueda semántica con pgvector + FTS de PostgreSQL, fusionados y reordenados por un cross-encoder.

  • Consolidación nocturna («dream») — un pipeline de agentes limpia enlaces huérfanos, fusiona duplicados, sintetiza aprendizajes y propone promociones, tras killswitches por fase que se distribuyen todos cerrados.

  • Multiproyecto — enfoque por proyecto con revisiones compare-and-swap, hojas de ruta, tickets entre proyectos.

Arquitectura

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)

Transporte MCP: producción = bucle local HTTP http://127.0.0.1:8765/mcp; configuración predeterminada y dev/fallback = stdio.

PostgreSQL es la única fuente de verdad. Neo4j es una proyección desechable alimentada por un ledger relacional/outbox — siempre se puede reconstruir desde PostgreSQL, nunca al revés. La ruta canónica está activa en producción desde el 22 de julio de 2026; el diseño y la evidencia viven en docs/ARCHITECTURE.md y en el runbook del graph ledger.

Los embeddings son opcionales y conectables. El propio servidor es agnóstico al modelo: solo habla un contrato HTTP de tres rutas (POST /embed, POST /embed/query, POST /rerank) y degrada con elegancia cuando el endpoint no está disponible — brain_search cae en la búsqueda de texto completo, las escrituras persisten con un embedding NULL y se rellenan después. Cualquier servidor que implemente ese contrato funciona. La pila de referencia incluida (services/) sirve Qodo-Embed-1-1.5B como GGUF mediante llama.cpp en una GPU local. EMBEDDING_DIMENSION se elige en la instalación; cambiar de modelo más adelante implica volver a generar los embeddings del corpus (scripts/regen_embeddings.py).

Related MCP server: Cortex MCP Server

Inicio rápido

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

Conéctalo a Claude Code — el .mcp.json en la raíz del repositorio ya apunta al endpoint de bucle local HTTP de producción; para una configuración de desarrollo simple con stdio:

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

BRAIN_ALEMBIC_ALLOW_PROD solo se requiere cuando el nombre de la base de datos es exactamente brain; mantenlo como una opción de un solo comando, nunca exportado de forma persistente. Alembic rechaza los parámetros de consulta del DSN; usa la forma simple anterior con host, puerto, usuario y contraseña presentes.

Herramientas MCP

Dominio

Herramientas

Búsqueda y listado

brain_search, brain_list, brain_get, brain_update, brain_delete

Recorrido del grafo

brain_get_neighbors, brain_graph_path

Ciclo de vida de sesión

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

Contexto de proyecto

brain_set_project_context, brain_update_project_focus, brain_list_projects, brain_list_project_groups

Decisiones

brain_log_decision, brain_supersede_decision, brain_get_supersession_chain

Aprendizajes

brain_learn, brain_validate_learning

Fragmentos

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

Coordinación

brain_ticket_create, brain_ticket_reply, brain_ticket_transition, brain_ticket_list, brain_ticket_get

Dream / grafo

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 y decadencia

brain_get_roadmap, brain_feature_create, brain_feature_update, brain_decay_status

Guía de flujo de trabajo

brain_workflow_guide

Catálogo completo con firmas: docs/MCP_TOOLS.md.

El perfil de catálogo predeterminado es compact: las siete herramientas del ciclo de vida de sesión permanecen visibles, y cualquier otra herramienta se alcanza a través de dos puertas de enlace — brain_find_tool para descubrir, brain_call_tool para invocar. Establece BRAIN_MCP_PROFILE=native para exponer todas las herramientas directamente.

Sesiones

El usuario controla cada límite de sesión: start, resume, end y abandon son comandos explícitos, nunca inferidos por un hook, un agente o un cliente. Las sesiones capturan los artefactos duraderos que produjeron en un ledger exclusivo, y el cierre es a prueba de fallos: conocimiento capturado o una razón explícita de «nada que capturar», nunca silencio.

Después de 24 horas sin un heartbeat, una sesión abierta expone is_stale=true; el marcador se deriva, el estado persistente sigue siendo open, y solo la limpieza del servidor a los 7 días abandona una sesión sin un comando explícito del usuario.

El contrato completo del ciclo de vida (reglas de captura, semántica de enfoque, informe) vive en docs/MCP_TOOLS.md; el contrato es v4 y sigue evolucionando.

Configuración (.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

Nunca coloques MCP_HTTP_TOKEN ni MCP_HTTP_DREAM_TOKENS en el .env compartido: los tokens de portador viven en un archivo privado 0600 (~/.config/brain-v42/mcp-token.env), y la credencial del proyector de grafos en el suyo propio (~/.config/brain-v42/graph-projector.env). Referencia completa — cada variable, los archivos secretos privados, los preflights y los portones de despliegue: docs/OPERATIONS.md.

Modelo de confianza de red

El despliegue apunta a agentes personales en una LAN de confianza. MCP, PostgreSQL y Neo4j se vinculan a loopback; las métricas y la automatización usan loopback por defecto.

Topología de embeddings: producción/valor predeterminado = endpoint unificado local http://localhost:8003; deploy/dev-pc es una ruta de rollback/referencia superada.

El reranker comparte el endpoint unificado de embeddings :8003/rerank. Trata :8003 como expuesto a la LAN hasta que hayas comprobado el enlace real por ti mismo, y nunca lo expongas — ni el puerto MCP — a Internet. El código del repositorio por sí solo no demuestra un estado de firewall real.

Modo Dream

Pipeline de agente nocturno (scripts/dream.sh: scan → clean → connect → synth → promote → reorg) más trabajos del lado del servidor de extracción de tickets, curación de hojas de ruta y limpieza de sesiones. Cada fase mutante está tras un killswitch y todos los killswitches se distribuyen cerrados; el dry-run es el valor predeterminado distribuido. Cada fase se ejecuta con una lista de permitidos de herramientas MCP exacta. Detalles: docs/ARCHITECTURE.md y docs/OPERATIONS.md.

Estado de producción

El objetivo de migración del repositorio es la migración 045. Ninguna página de este repositorio demuestra una cabecera de esquema en vivo — mídela, no la leas aquí:

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

El build en ejecución se nombra a sí mismo: GET /health devuelve version (la distribución instalada) y alembic_head (la revisión incluida), ambos medidos, nunca escritos a mano.

Desarrollo

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 es obligatorio — rojo, verde, refactor; los tests nunca se editan para que el código pase.

  • Umbral de cobertura: 60% (CI bloquea por debajo).

  • La cadena de herramientas de desarrollo está fijada exactamente (pip install -e ".[dev]") para que el entorno local siempre coincida con CI.

Estructura del proyecto

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

El grafo de módulos de nivel superior se mantiene acíclico en CI (scripts/check_module_layering.py): cualquier módulo puede extraerse a un servicio independiente sin arrastrar un ciclo consigo.

CI/CD

Etapas: lint → test → security → build. Barreras de seguridad: pip-audit, bandit, gitleaks, comprobaciones de pines de imágenes de contenedor. Las imágenes Docker se construyen y se publican en main; no hay etapa de despliegue — el rollout a un host es siempre un paso manual y fuera de banda. Los lanzamientos están impulsados por etiquetas: el raíl de release construye la wheel + sdist, demuestra que la wheel incluye sus migraciones, y adjunta ambos al release de GitHub.

Versionado

  • La versión distribuida es 0.2.0, y se mantiene en 0.x a propósito: un 1.0.0 prometería una interfaz estable y un camino de retorno, y este proyecto no tiene ni lo uno ni lo otro todavía.

  • No se promete una degradación sin pérdida, en ninguna versión. Dos migraciones rechazan su propio downgrade: 037 lanza una EXCEPTION de SQL en cuanto se perdería una captura de sesión, y 039 lanza una excepción a menos que el operador pase un opt-in explícito -x.

  • Revertir un esquema es, por tanto, un procedimiento del operador con un runbook, nunca una garantía de versión — restaura desde una instantánea en su lugar.

Licencia

Código fuente: Apache-2.0.

Los pesos del modelo no están cubiertos por esa licencia, y esto no es una formalidad. El modelo de embedding de producción, Qodo/Qodo-Embed-1-1.5B, se publica bajo QodoAI-Open-RAIL-M — una licencia con restricciones basadas en el uso, no una permisiva. Ningún peso se almacena ni se distribuye mediante este repositorio: cada modelo se descarga de su host de origen en el momento de la compilación, por el operador, quien acepta los términos de cada modelo directamente de su editor. Consulta NOTICE antes de redistribuir cualquier cosa.

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
      -