cortex-memory
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@cortex-memory What did we learn about the memory leak in the worker service?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
CortexMemory
Bi-Temporal, 4-Tier Hybrid Cognitive Memory Engine for Autonomous Coding Agents
CortexMemory provides external cognitive memory for AI coding assistants via the Model Context Protocol (MCP). By decoupling active working context from long-term memory, it maintains a lean, stationary context window ($O(1)$) that cuts token consumption by ~82%, eliminates compaction amnesia, and prevents repetitive debugging loops.
The engine runs 100% locally on your machine using Docker (PostgreSQL 16 + Neo4j 5.26) and local vector embeddings.
Architecture Overview

CortexMemory separates memory into 4 distinct tiers coordinated across two asynchronous pathways:
The Dual Pathways
The Hot Path (Sub-Second Interaction):
Every tool call, error, and diff is logged non-blockingly to PostgreSQL (Tier 2) in < 5ms.
When the agent queries memory, the Cognitive Memory Router blends active scratchpad state (Tier 1), dense vector retrieval (Tier 3), and bi-temporal graph traversals (Tier 4) via Reciprocal Rank Fusion (RRF): $$RRF(d) = \sum_{m \in {\text{vector}, \text{graph}, \text{episodic}}} \frac{w_m}{k + \text{rank}_m(d)}$$
A Token Budgeter packs the top ranked facts into a lean Markdown injection capped at 2,500 tokens.
The Sleep-Cycle Consolidation Path (Background Reflection):
An
AFTER INSERTtrigger on PostgreSQL firespg_notify('new_episode_channel').The background daemon wakes reactively (no polling) and claims unconsolidated batches using
SELECT ... FOR UPDATE SKIP LOCKED.It distills raw events through a lightweight reflection model (Claude 3.5 Haiku, Gemini Flash, or local Ollama) into 4 atomic operations:
ADD: Inserts a new entity or dependency edge (valid_from = now(), valid_to = null).UPDATE: Refreshes properties or bumps confidence scores.DELETE: Setsvalid_to = now()on superseded relationships (soft invalidation).NOOP: Discards transient noise (e.g.ls, exploratory file reads).
Updates are committed to Neo4j, and episodes are marked
consolidated = true.
Related MCP server: Agent Memory Bridge
š§ The Memory Hierarchy & Engine Philosophy
Why Flat Context & Naive Vector RAG Fail
Approach | How It Operates | Core Failure Mode |
Flat Context Accumulation | Piles raw turns and tool outputs into a single prompt window. | Linear context growth ($O(N)$) triggers lossy compaction at ~160k tokens, causing compaction amnesia and repetitive error spirals. |
Naive Vector RAG | Indexes code snippets into a flat vector database (Pinecone, Chroma). | Temporal Blindness: Outdated code often matches queries with high similarity, causing hallucinations. Cannot resolve multi-hop graph dependencies or detect error loops. |
The 4-Tier Memory Hierarchy (Computer Architecture Analogy)
CortexMemory maps cognitive memory to computer storage tiers (Registers $\rightarrow$ SSD WAL $\rightarrow$ Inverted Index $\rightarrow$ Relational Topology):
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Tier 1: Working Memory (RAM / L1 Cache) ā
ā - Engine: In-Memory / Python dictionary (Strict 4,000 token ceiling) ā
ā - Role: Active goal, current debugging hypothesis, transient scratchpad ā
ā - Benefit: Sub-millisecond prompt focus; prevents task drift ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā (Async Log & Action Stream)
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Tier 2: Episodic Store (Write-Ahead Log / SSD) ā
ā - Engine: PostgreSQL 16 (JSONB, GIN Indexing, SHA-256 Hashes) ā
ā - Role: Append-only audit trail of every tool execution, diff, and output ā
ā - Benefit: Lossless auditability; instant repetitive error detection via ā
ā SHA-256 hash match; zero-polling pg_notify triggers ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā (Background Sleep-Cycle Consolidation)
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Tier 3: Semantic Store (Fast Inverted Search Index) ā
ā - Engine: Neo4j Native Lucene Vector Index (1536-dim Cosine Similarity) ā
ā - Role: Dense vector embeddings of entities, patterns, and decisions ā
ā - Benefit: Conceptual discovery when exact symbol names are unknown ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā (Unified in Neo4j)
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Tier 4: Knowledge Graph (Bi-Temporal Relational Topology) ā
ā - Engine: Neo4j Bi-Temporal Property Graph ā
ā - Role: Code entities and edges with [valid_from, valid_to] intervals ā
ā - Benefit: Multi-hop dependency traversal; deterministic temporal ā
ā disambiguation (valid_to IS NULL = active, non-null = obsolete) ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāQuantitative Benchmark: Flat Context vs. CortexMemory
Measured over a 50-turn refactoring task:
Metric | Flat Context (Native Agent) | CortexMemory Engine | Difference / Advantage |
Cumulative Tokens | ~3,380,000 tokens | ~600,000 tokens | -82.2% token reduction |
Prompt Latency (p95) | 3.8s ā 7.2s (huge KV-cache) | 0.8s ā 1.4s (lean 10k prompt) | ~75% faster responses |
Amnesia Events | Multiple auto-compactions | 0 amnesia events | 100% deterministic recall |
Temporal Accuracy | None (confuses old & new code) | Strict ( | Zero temporal hallucinations |
Error Loop Recovery | Prone to repeating failed fixes | Instant SHA-256 hash alert | Loops halted after 1 repeat |
Dependency Resolution | Heuristic regex/grep searching | Exact Cypher graph traversal | True structural awareness |
Key Use Cases
1. Halting Repetitive Debugging Loops
Scenario: An agent encounters an environment or test error, attempts a fix that fails, and later repeats the exact same attempt because previous command outputs rolled off context.
Cortex Action: Every error is indexed with a canonical SHA-256 hash in Tier 2. When the same failure repeats, Cortex flags
repetitive_loop_detected: truewith the occurrence count, instructing the agent to change approach immediately.
2. Temporal Disambiguation During Refactors
Scenario: A project migrates from REST to tRPC. An agent reading older commits or documentation attempts to generate obsolete REST endpoints.
Cortex Action: Consolidation marks obsolete relationships with
valid_to = datetime(). Cypher queries filterWHERE valid_to IS NULL, ensuring only currently active architecture conventions are supplied to the prompt.
Quickstart & Setup
1. Launch Infrastructure
Starts PostgreSQL 16 and Neo4j 5.26 with pre-configured schemas and APOC plugins:
docker compose -f docker/docker-compose.yml up -dPostgreSQL:
localhost:5432(user: cortex,db: cortex_memory)Neo4j Browser: http://localhost:7474 (
user: neo4j,pass: cortex_secure_password)
2. Install & Verify
uv sync
uv run pytest(Runs the 42 unit and integration tests across storage tiers, hashing, RRF, and FastMCP tools).
Agent Integration (FastMCP)
CortexMemory implements the Model Context Protocol (MCP), connecting directly to Claude Code, Cursor, Windsurf, and Antigravity.
Client Configuration (~/.claude.json or cursor.json)
{
"mcpServers": {
"cortex-memory": {
"command": "uv",
"args": [
"--directory",
"/Users/supreme/Dev/cortex-memory",
"run",
"python",
"-m",
"cortex.mcp.server"
]
}
}
}Available MCP Tools
Tool Name | Description | Key Parameters |
| Ingests a tool run, prompt, git commit, or error into Tier 2. |
|
| Hybrid RRF retrieval returning synthesized, token-budgeted context. |
|
| Checks if a stack trace or error has occurred previously. |
|
| Sets active goal and hypothesis in Tier 1 Working Memory. |
|
| Traverses active dependencies for a file or function in Neo4j. |
|
| Triggers background sleep-cycle distillation on demand. |
|
Example Usage
1. Ingesting Events & Detecting Loops
# Agent logs a test failure
response = await cortex_record_event(
session_id="session_01",
turn_index=12,
event_type="test_failure",
payload={"stderr": "AssertionError: 401 != 200 at auth.test.ts:45"},
outcome_status="FAILED",
target_entity="src/auth/jwt.ts"
)
# Output:
# {
# "event_id": "c71a39...",
# "content_hash": "8ea6c75...",
# "repetitive_loop_detected": true,
# "occurrence_count": 2
# }2. Querying Memory for Synthesized Context
# Agent queries relevant architectural facts before editing
context = await cortex_query_memory(
query="How is authentication validated in API routes?",
target_entity="src/api/routes.ts",
max_tokens=1500
)
# Injected Context:
# ### Active Working Scratchpad
# **Active Goal:** Migrate from REST to tRPC
#
# ### Graph Dependencies
# - src/auth/session.ts (depth 1) [USES_PROTOCOL: tRPC]
# - src/models/user.ts (depth 2)License
Apache 2.0
Available Tools
6 toolscortex_check_error_loopC
Checks if identical error stack trace has occurred previously.
Inputs: session_id (required), error_output (required). Returns: result
cortex_force_consolidationC
Manually forces background sleep-cycle consolidation.
Inputs: limit. Returns: result
cortex_inspect_graphB
Queries bi-temporal knowledge graph dependencies for a code entity.
Inputs: entity_id (required). Returns: result
cortex_query_memoryC
Hybrid 4-tier retrieval returning synthesized, lean context.
Inputs: query (required), max_tokens, session_id, target_entity. Returns: result
cortex_record_eventB
Hot-path non-blocking episodic event logging.
Inputs: payload (required), event_type (required), session_id (required), turn_index (required), +2 more. Returns: result
cortex_update_scratchpadC
Updates Tier 1 transient working memory scratchpad.
Inputs: session_id (required), notes, active_goal, current_hypothesis. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogā¦
TDQS
Scored across 6 tools
Each tool targets a distinct memory operation: error-loop checking, scratchpad updates, hybrid retrieval, graph inspection, consolidation, and event recording. There is minimal overlap between querying, inspecting, and recording.
All tools share the cortex_ prefix and follow a consistent snake_case verb_noun pattern. The naming clearly communicates action and target.
Six tools is a well-scoped set for a memory server, covering retrieval, recording, updates, inspection, and maintenance without redundancy.
Core memory workflows are covered, but there is no explicit delete/forget or scratchpad reset operation, which could be a minor gap depending on expected memory lifecycle management.
Maintenance
Related MCP Connectors
Persistent memory for AI agents to retain, retrieve, and recall conversation context through MCP.
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.
Hosted MCP memory for coding agents: persistent across sessions, editable markdown, team sharing.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents to maintain persistent, cross-session memory of codebase architecture, naming conventions, and decisions through MCP tools. Eliminates repetitive project re-explanation by automatically injecting stored context into every session with local-first SQLite storage and optional team sharing capabilities.4MIT
- AlicenseAqualityBmaintenanceMCP-native, local-first memory for coding agents that turns real sessions into reusable decisions, gotchas, and domain knowledge.17136 PyPI7MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI coding agents to retrieve and manage code context with hybrid search, project memory, and observability via MCP tools.30MIT
- AlicenseNot gradedqualityBmaintenanceProvides coding agents with governed semantic memory and code-graph context via MCP, enabling code-linked recall, blast-radius impact analysis, and lifecycle-aware memory management.799 PyPI3Apache 2.0