MCP Hub
Back to servers

Cortex

C.O.R.T.E.X. — Cognitive profiling system for Claude Code

GitHub
Stars
12
Forks
1
Updated
Apr 5, 2026
Validated
Apr 7, 2026

Cortex

Persistent memory for Claude Code — built on neuroscience research, not guesswork

CI License: MIT Python 3.10+ Tests

Memory that learns, consolidates, forgets intelligently, and surfaces the right context at the right time. Works standalone or with a team of specialized agents.

Getting Started | How It Works | Neural Graph | Agent Integration | Benchmarks | Scientific Foundation


Getting Started

Prerequisites

  • Python 3.10+
  • PostgreSQL 15+ with pgvector and pg_trgm extensions
  • Claude Code CLI or desktop app

Option A — Claude Code Marketplace (recommended)

claude plugin marketplace add cdeust/Cortex
claude plugin install cortex

Restart your Claude Code session, then run:

/cortex-setup-project

This handles everything: PostgreSQL + pgvector installation, database creation, embedding model download, cognitive profile building from session history, codebase seeding, conversation import, and hook registration. Zero manual steps.

Using Claude Cowork? Install Cortex-cowork instead — uses SQLite, no PostgreSQL required.

claude plugin marketplace add cdeust/Cortex-cowork
claude plugin install cortex-cowork

Option B — Standalone MCP (no plugin)

claude mcp add cortex -- uvx --from "neuro-cortex-memory[postgresql]" neuro-cortex-memory

Adds Cortex as a standalone MCP server via uvx. No hooks, no skills — just the 33 MCP tools. Requires uv installed.

Option C — Clone + Setup Script

git clone https://github.com/cdeust/Cortex.git
cd Cortex
bash scripts/setup.sh        # macOS / Linux
python3 scripts/setup.py     # Windows / cross-platform

Installs PostgreSQL + pgvector (Homebrew on macOS, apt/dnf on Linux), creates the database, downloads the embedding model (~100 MB). On Windows, install PostgreSQL manually first, then run setup.py. Restart Claude Code after setup.

Option D — Docker

git clone https://github.com/cdeust/Cortex.git
cd Cortex

docker build -t cortex-runtime -f docker/Dockerfile .
docker run -it \
  -v $(pwd):/workspace \
  -v cortex-pgdata:/var/lib/postgresql/17/data \
  -v ~/.claude:/home/cortex/.claude-host:ro \
  -v ~/.claude.json:/home/cortex/.claude-host-json/.claude.json:ro \
  cortex-runtime

The container includes PostgreSQL 17, pgvector, the embedding model, and Claude Code. Data persists via the cortex-pgdata volume.

Option E — Manual Setup

Step-by-step instructions

1. Install PostgreSQL + pgvector

# macOS
brew install postgresql@17 pgvector
brew services start postgresql@17

# Ubuntu/Debian
sudo apt-get install postgresql postgresql-server-dev-all
sudo apt-get install postgresql-17-pgvector
sudo systemctl start postgresql

2. Create the database

createdb cortex
psql cortex -c "CREATE EXTENSION IF NOT EXISTS vector;"
psql cortex -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;"

3. Install Python dependencies

pip install -e ".[postgresql]"
pip install sentence-transformers flashrank

4. Initialize schema

export DATABASE_URL=postgresql://localhost:5432/cortex
python3 -c "
from mcp_server.infrastructure.pg_schema import get_all_ddl
from mcp_server.infrastructure.pg_store import PgStore
import asyncio
asyncio.run(PgStore(database_url='$DATABASE_URL').initialize())
"

5. Pre-cache the embedding model

python3 -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')"

6. Register MCP server

claude mcp add cortex -- uvx --from "neuro-cortex-memory[postgresql]" neuro-cortex-memory

Restart Claude Code to activate.

Verify Installation

After setup, open Claude Code in any project. The SessionStart hook should inject context automatically. You can also test manually:

python3 -m mcp_server  # Should start on stdio without errors

Configuration

Cortex reads DATABASE_URL from the environment (default: postgresql://localhost:5432/cortex). All tunable parameters use the CORTEX_MEMORY_ prefix:

VariableDefaultWhat It Controls
DATABASE_URLpostgresql://localhost:5432/cortexPostgreSQL connection string
CORTEX_RUNTIMEauto-detectedcli (strict) or cowork (SQLite fallback)
CORTEX_MEMORY_DECAY_FACTOR0.95Per-session heat decay rate
CORTEX_MEMORY_HOT_THRESHOLD0.7Heat level considered "hot"
CORTEX_MEMORY_WRRF_VECTOR_WEIGHT1.0Vector similarity weight in fusion
CORTEX_MEMORY_WRRF_FTS_WEIGHT0.5Full-text search weight in fusion
CORTEX_MEMORY_WRRF_HEAT_WEIGHT0.3Thermodynamic heat weight in fusion
CORTEX_MEMORY_DEFAULT_RECALL_LIMIT10Max memories returned per query

See mcp_server/infrastructure/memory_config.py for the full list (~40 parameters).


How It Works

Cortex runs as an MCP server alongside Claude Code. It captures what you work on, consolidates it while you're away, and resurfaces the right context when you need it.

Memory is Invisible

You don't manage memory. Cortex does.

Session start — hot memories, anchored decisions, and team context inject automatically. No manual recall needed.

During work — PostToolUse hooks capture significant actions (edits, commands, test results). Decisions are auto-detected and protected from forgetting. File edits prime related memories via spreading activation so they surface in subsequent recall.

Session end — a "dream" cycle runs automatically: decay old memories, compress verbose ones, and for long sessions, consolidate episodic memories into semantic knowledge (CLS).

Between sessions — memories cool naturally (Ebbinghaus forgetting curve). Important ones stay hot. Protected decisions never decay.

Retrieval Pipeline

Six signals fused server-side in PostgreSQL, then reranked client-side:

Retrieval pipeline: Intent → TMM fusion → FlashRank reranking

SignalSourcePaper
Vector similaritypgvector HNSW (384-dim)Bruch et al. 2023
Full-text searchtsvector + ts_rank_cdBruch et al. 2023
Trigram similaritypg_trgmBruch et al. 2023
Thermodynamic heatEbbinghaus decay modelEbbinghaus 1885
RecencyExponential time decay

Hooks

Seven hooks integrate with Claude Code's lifecycle (managed via plugin.json, no manual setup):

HookEventWhat It Does
SessionStartSession opensInjects anchors + hot memories + team decisions + checkpoint
UserPromptSubmitBefore responseAuto-recalls relevant memories based on user's prompt
PostToolUseAfter Edit/Write/BashAuto-captures significant actions as memories
PostToolUseAfter Edit/Write/ReadPrimes related memories via heat boost (spreading activation)
SessionEndSession closesRuns dream cycle (decay, compress, CLS based on activity)
CompactionContext compactsSaves checkpoint; restores context after compaction
SubagentStartAgent spawnedBriefs agent with prior work + team decisions

Neural Graph

Launch the interactive visualization with /cortex-visualize. Three views: Graph, Board, and Pipeline.

Graph View

Force-directed neural graph showing domain clusters, memories, entities, and discussions connected by typed edges.

Cortex Neural Graph — unified view with domain clusters, memories, entities, and discussions

Board View

Memories organized by biological consolidation stage. Each column shows decay rate, vulnerability, and plasticity. Memory cards display domain, heat, importance, and emotional tags.

Cortex Board View — kanban consolidation stages with biological metrics

Pipeline View

Horizontal flow from domains through the write gate into consolidation stages. Block height reflects importance, color indicates domain.

Cortex Pipeline View — Sankey flow through consolidation stages

Detail Panels

Click any node for full context. Discussion nodes show session timeline, tools used, keywords, and a full conversation viewer. Memory nodes show biological meters (encoding strength, interference, schema match) and git diffs.

Cortex — discussion detail with full conversation history Cortex — code diff viewer in memory detail panel

Filters

Domain, emotion, and consolidation stage dropdowns. Toggle buttons for methodology, memories, knowledge, emotional nodes, protected/hot/global memories, and discussions.


Agent Integration

Cortex is designed to work with a team of specialized agents. Each agent has scoped memory (agent_topic) while sharing critical decisions across the team.

Transactive Memory System

Based on Wegner 1987: teams store more knowledge than individuals because each member specializes, and a shared directory tells everyone who knows what.

Transactive Memory System — agent specialization, coordination, directory

Specialization — each agent writes to its own topic. Engineer's debugging notes don't clutter tester's recall.

Coordination — decisions auto-protect and propagate. When engineer decides "use Redis over Memcached," every agent sees it at next session start.

Directory — entity-based queries span all topics. "What do we know about the reranker?" returns results from engineer, tester, and researcher.

Agent Briefing

When the orchestrator spawns a specialist agent, the SubagentStart hook automatically:

  1. Extracts task keywords from the prompt
  2. Queries agent-scoped prior work (FTS, no embedding load needed)
  3. Fetches team decisions (protected + global memories from other agents)
  4. Injects as context prefix — agent starts with knowledge

Compatible Agent Team

Works with any custom Claude Code agents. See zetetic-team-subagents for a reference team of 18 specialists:

AgentSpecialtyMemory Topic
orchestratorParallel agent execution, coordination, mergeorchestrator
engineerClean Architecture, SOLID, any language/stackengineer
architectModule decomposition, layer boundaries, refactoringarchitect
code-reviewerClean Architecture enforcement, SOLID violationscode-reviewer
test-engineerTesting, CI verification, wiring checkstest-engineer
dbaSchema design, query optimization, migrationsdba
research-scientistBenchmark improvement, neuroscience/IR papersresearch-scientist
frontend-engineerReact/TypeScript, component design, accessibilityfrontend-engineer
security-auditorThreat modeling, OWASP, defense-in-depthsecurity-auditor
devops-engineerCI/CD, Docker, PostgreSQL provisioningdevops-engineer
ux-designerUsability, accessibility, design systemsux-designer
data-scientistEDA, feature engineering, data quality, bias auditingdata-scientist
experiment-runnerAblation studies, hyperparameter search, statistical rigorexperiment-runner
mlopsTraining pipelines, model serving, GPU optimizationmlops
paper-writerResearch paper structure, narrative flow, venue conventionspaper-writer
reviewer-academicPeer review simulation (NeurIPS/CVPR/ICML style)reviewer-academic
professorConcept explanation, mental models, adaptive teachingprofessor
latex-engineerLaTeX templates, figures, TikZ, bibliographieslatex-engineer

Skills

Cortex ships as a Claude Code plugin with 14 skills:

SkillCommandWhat It Does
cortex-remember/cortex-rememberStore a memory with full write gate
cortex-recall/cortex-recallSearch memories with intent-adaptive retrieval
cortex-consolidate/cortex-consolidateRun maintenance (decay, compress, CLS)
cortex-explore-memory/cortex-explore-memoryNavigate memory by entity/domain
cortex-navigate-knowledge/cortex-navigate-knowledgeTraverse knowledge graph
cortex-debug-memory/cortex-debug-memoryDiagnose memory system health
cortex-visualize/cortex-visualizeLaunch 3D neural graph in browser
cortex-profile/cortex-profileView cognitive methodology profile
cortex-setup-project/cortex-setup-projectBootstrap a new project
cortex-develop/cortex-developMemory-assisted development workflow
cortex-automate/cortex-automateCreate prospective triggers

Benchmarks

All scores are retrieval-only — no LLM reader in the evaluation loop. We measure whether retrieval places correct evidence in the top results.

BenchmarkMetricCortexBest in PaperPaper
LongMemEvalR@1098.0%78.4%Wang et al., ICLR 2025
LongMemEvalMRR0.880
LoCoMoR@1097.7%Maharana et al., ACL 2024
LoCoMoMRR0.840
BEAMOverall MRR0.6270.329 (LIGHT)Tavakoli et al., ICLR 2026
Per-category breakdowns

BEAM (10 abilities, 400 questions)

AbilityMRRR@10
contradiction_resolution0.879100.0%
knowledge_update0.86797.5%
temporal_reasoning0.85797.5%
multi_session_reasoning0.73892.5%
information_extraction0.54272.5%
summarization0.35969.4%
preference_following0.35662.5%
event_ordering0.35362.5%
instruction_following0.24252.5%
abstention0.12512.5%

LongMemEval (6 categories, 500 questions)

CategoryMRRR@10
Single-session (assistant)0.970100.0%
Multi-session reasoning0.917100.0%
Temporal reasoning0.88797.7%
Knowledge updates0.884100.0%
Single-session (user)0.79391.4%
Single-session (preference)0.70696.7%

LoCoMo (5 categories, 1986 questions)

CategoryMRRR@10
adversarial0.80989.0%
open_domain0.81791.1%
multi_hop0.73684.1%
single_hop0.71491.8%
temporal0.53876.1%

Architecture

Clean Architecture with strict dependency rules. Inner layers never import outer layers.

Clean Architecture layers

LayerModulesRule
core/118Pure business logic. Zero I/O. Imports only shared/.
infrastructure/33All I/O: PostgreSQL, embeddings, file system.
handlers/62 toolsComposition roots wiring core + infrastructure.
hooks/7Lifecycle automation (SessionStart/End, PostToolUse, etc.)
shared/12Pure utilities. Python stdlib only.

Storage: PostgreSQL 15+ with pgvector (HNSW) and pg_trgm. All retrieval in PL/pgSQL stored procedures.


Scientific Foundation

The Zetetic Standard

Every algorithm, constant, and threshold traces to a published paper, a measured ablation, or documented engineering source. Nothing is guessed. Where engineering defaults exist, they are labeled as such.

Paper Index (41 citations)

Information Retrieval
PaperYearVenueModule
Bruch et al. "Fusion Functions for Hybrid Retrieval"2023ACM TOISpg_schema.py
Nogueira & Cho "Passage Re-ranking with BERT"2019arXivreranker.py
Joren et al. "Sufficient Context"2025ICLRreranker.py
Collins & Loftus "Spreading-activation theory"1975Psych. Reviewspreading_activation.py
Neuroscience — Encoding (5 papers)
PaperYearModule
Friston "A theory of cortical responses"2005hierarchical_predictive_coding.py
Bastos et al. "Canonical microcircuits for predictive coding"2012hierarchical_predictive_coding.py
Wang & Bhatt "Emotional modulation of memory"2024emotional_tagging.py
Doya "Metalearning and neuromodulation"2002coupled_neuromodulation.py
Schultz "Prediction and reward"1997coupled_neuromodulation.py
Neuroscience — Consolidation (6 papers)
PaperYearModule
Kandel "Molecular biology of memory storage"2001cascade.py
McClelland et al. "Complementary learning systems"1995dual_store_cls.py
Frey & Morris "Synaptic tagging"1997synaptic_tagging.py
Josselyn & Tonegawa "Memory engrams"2020engram.py
Dudai "The restless engram"2012reconsolidation.py
Borbely "Two-process model of sleep"1982session_lifecycle.py
Neuroscience — Retrieval & Navigation (4 papers)
PaperYearModule
Behrouz et al. "Titans: Learning to Memorize at Test Time"2025titans_memory.py
Stachenfeld et al. "Hippocampus as predictive map"2017cognitive_map.py
Ramsauer et al. "Hopfield Networks is All You Need"2021hopfield.py
Kanerva "Hyperdimensional computing"2009hdc_encoder.py
Neuroscience — Plasticity & Maintenance (14 papers)
PaperYearModule
Hasselmo "Hippocampal theta rhythm"2005oscillatory_clock.py
Buzsaki "Hippocampal sharp wave-ripple"2015oscillatory_clock.py
Leutgeb et al. "Pattern separation in dentate gyrus"2007pattern_separation.py
Yassa & Stark "Pattern separation in hippocampus"2011pattern_separation.py
Turrigiano "The self-tuning neuron"2008homeostatic_plasticity.py
Abraham & Bear "Metaplasticity"1996homeostatic_plasticity.py
Tse et al. "Schemas and memory consolidation"2007schema_engine.py
Gilboa & Marlatte "Neurobiology of schemas"2017schema_engine.py
Hebb The Organization of Behavior1949synaptic_plasticity.py
Bi & Poo "Synaptic modifications"1998synaptic_plasticity.py
Perea et al. "Tripartite synapses"2009tripartite_synapse.py
Kastellakis et al. "Synaptic clustering"2015dendritic_clusters.py
Wang et al. "Microglia-mediated synapse elimination"2020microglial_pruning.py
Ebbinghaus Memory1885thermodynamics.py
Team Memory & Preemptive Retrieval (6 papers)
PaperYearModule
Wegner "Transactive memory"1987memory_ingest.py, session_start.py
Zhang et al. "Collaboration Mechanisms for LLM Agents"2024memory_ingest.py
McGaugh "Amygdala modulates consolidation"2004memory_ingest.py
Adcock et al. "Reward-motivated learning"2006memory_ingest.py
Bar "The proactive brain"2007preemptive_context.py
Smith & Vela "Context-dependent memory"2001agent_briefing.py

Ablation Data

All ablation results committed to benchmarks/beam/ablation_results.json.

ParameterTested ValuesOptimalSource
rerank_alpha0.30, 0.50, 0.55, 0.700.70BEAM 100K ablation
FTS weight0.0, 0.3, 0.5, 0.7, 1.00.0 (BEAM), 0.5 (balanced)Cross-benchmark
Heat weight0.0, 0.1, 0.3, 0.5, 0.70.7 (BEAM), 0.3 (balanced)Cross-benchmark
Adaptive alphaCE spread QPPRejectedRegressed LoCoMo -5.1pp R@10

Engineering Defaults

Values without paper backing, explicitly documented:

ConstantValueLocationStatus
FTS weight0.5pg_recall.pyBalanced across benchmarks
Heat weight0.3pg_recall.pyBalanced across benchmarks
CE gate threshold0.15reranker.pyEngineering default
Titans eta/theta0.9/0.01titans_memory.pyPaper uses learned params

Security

Cortex runs locally (MCP over stdio, PostgreSQL on localhost, visualization on 127.0.0.1). No data leaves your machine unless you explicitly configure an external database.

Audit Score: 91/100

CategoryScoreNotes
Data Flow90No external data exfiltration. Embeddings computed locally.
SQL Injection95All queries parameterized (psycopg %s). Dynamic columns use sql.Identifier().
Auth & Access Control85Docker PG uses scram-sha-256 on localhost. MCP over stdio (no network auth needed).
Dependency Health80Floor-pinned deps. Background install version-bounded.
Network Behavior92Model download on first run only. Viz servers bind 127.0.0.1.
Code Quality90Pydantic validation on all tools. Input length limits on remember/recall. Path traversal protected.
Prompt Injection88Memory content escaped in HTML rendering. Session injection uses data delimiters.
Secrets Management90.env/credentials in .gitignore. No hardcoded secrets. Docker credentials via env vars.
Hardening measures
  • SQL parameterization across all 7 pg_store modules (psycopg %s placeholders)
  • sql.Identifier() for dynamic column names (no f-string SQL)
  • ILIKE patterns escape %, _, \ from user input
  • CORS allows * (localhost-only servers, no external exposure)
  • Docker PostgreSQL uses scram-sha-256 auth on 127.0.0.1/32
  • trust_remote_code removed from embedding model loading
  • Input length validation: remember content capped at 50KB, queries at 10KB
  • Path traversal protection via .resolve() in sync_instructions
  • HTML escaping (esc()) on all user-generated content in visualization
  • Background pip install version-bounded (>=2.2.0,<4.0.0)
  • Secrets patterns (.env, *.credentials.json, *.pem, *.key) in .gitignore

Development

pytest                    # 2080 tests
ruff check .              # Lint
ruff format --check .     # Format

License

MIT

Citation

@software{cortex2026,
  title={Cortex: Persistent Memory for Claude Code},
  author={Deust, Clement},
  year={2026},
  url={https://github.com/cdeust/Cortex}
}

Reviews

No reviews yet

Sign in to write a review