Skip to main content
Glama

Cortex - AI Memory & Context Management Server

Powered by Enlighter and Hyperskill.

Cortex MCP server

What it's for

Cortex is an MCP server that helps build and maintain a project Memory Bank so AI assistants always have up-to-date context, plans, and rules. It follows the Memory Bank pattern and keeps your .cortex/ files (roadmap, activeContext, progress, rules) in sync so agents can reliably run a plan → do → commit loop instead of ad-hoc edits. Use Cortex when you want reproducible, high-quality AI-driven development that survives restarts, editor changes, and long-running projects.

Related MCP server: memory-bank-mcp

How to use it

  1. Install prerequisites: Python 3.13+ and the Rust-based rumdl Markdown linter (installed via the Python dev environment; see Prerequisites).

  2. Run the server: Add the config snippet from Running the Server to your mcp.json (most users pick uvx).

  3. Start with the plan → do → commit loop (see below). In your IDE/assistant, ask the agent to orchestrate these commands:

    • Start a session (get an orientation brief)

    • Load task-specific context

    • Follow the plan → do → commit loop

For new projects, use the initialize prompt to create the Memory Bank and .cortex/ structure.

Plan → do → commit

This is the daily workflow:

Step

What happens

Plan

Create or refine plans in .cortex/plans/ and register them in roadmap.md.

Do

Apply the next PENDING roadmap step with tests and quality checks.

Commit

Run the full pre-commit pipeline and push only healthy commits.

See docs/prompts for setup/migration prompt details.

If Cortex MCP cannot be reached in your environment, you can still do a read-only audit of the repo under the boundaries in AGENTS.md (MCP unavailable: read-only audit fallback) and the runbook MCP unavailable: read-only audits.

Features

  • Memory Bank — structured project context that persists across sessions

  • Session & Context — orientation briefs, token-budgeted context loading, end-of-session compaction

  • Validation & Quality — schema validation, lint/format/type auto-fix, pre-commit checks

  • Plans & Roadmap — plan lifecycle management tied to a roadmap

  • DRY Linking — transclusion engine to embed content without duplication

  • Shared Rules (Synapse) — cross-project rule and prompt sharing via Git submodule

  • Refactoring — pattern analysis, suggestions, safe execution with rollback

  • Token Optimization — context summarization and relevance scoring

Recent changes

2026-10-05

  • Reviews, analyses, and queries now use canonical directories directly under .cortex/, shared by filing, search, and recent/deep context retrieval. Architectural findings retain their memory-bank destination.

  • Added preview-first, digest-approved manage_file(operation="migrate_artifacts") relocation with reference/index preservation, recoverable byte preimages, immutable historical provenance, and unchanged wiki-mirror allocation rules. See the migration guide.

Prerequisites

  • Python 3.13+

  • rumdl — Markdown linter/formatter installed into the Python environment (for example via uv sync --extra dev, which adds the rumdl CLI to .venv/bin/rumdl)

Running the Server

{
  "mcpServers": {
    "cortex": {
      "command": "uvx",
      "args": [
        "--from",
        "git+https://github.com/igrechuhin/Cortex.git",
        "cortex"
      ]
    }
  }
}

First run / IDE timeouts: uvx --from git+… must resolve GitHub HEAD, download dependencies, and build the package into uv’s cache. That can take minutes on a cold machine or right after uv cache clean. Some MCP clients time out during the first Initialize if the server is not ready yet. Pre-warm once in a terminal (same command you use in mcp.json), then start or reload the MCP client:

uvx --from git+https://github.com/igrechuhin/Cortex.git cortex --help

Details: Getting started — Stable MCP setup, Troubleshooting — uvx cold start.

Project-level vs global config: Place the snippet in your project's .mcp.json rather than in the global client config. Project-level config lets Cortex resolve the correct workspace root immediately. A global config makes your client launch Cortex with CWD set to the home directory; Cortex falls back to a heuristic root-finder that can pick up stale .cortex/ state left in ~/ and show spurious setup prompts.

With Smithery

{
  "mcpServers": {
    "cortex": {
      "command": "npx",
      "args": [
        "-y",
        "@smithery/cli@latest",
        "run",
        "@igrechuhin/cortex",
        "--key",
        "your_smithery_key"
      ]
    }
  }
}

With Docker

{
  "mcpServers": {
    "cortex": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "19283744/cortex:latest"
      ]
    }
  }
}

Manually

Clone the repository, then:

bash scripts/bootstrap.sh

Optionally initialize the Synapse submodule for shared rules:

git submodule update --init --recursive

Add to your mcp.json:

{
  "mcpServers": {
    "cortex": {
      "command": "uv",
      "args": ["run", "cortex"]
    }
  }
}

Developer commands

For local development, use these Make targets (after running bash scripts/bootstrap.sh once to create the virtualenv and install dependencies):

  • Dependency setup / connectivity triage: If uv sync or installs fail (proxy, SSL, or registry access), use Dependency and network verification to separate environment setup failures from actual test failures.

  • make preflight: Probe PyPI or UV_INDEX_URL before uv sync when triaging connectivity; see Dependency and network verification.

  • make bootstrap: Run scripts/bootstrap.sh to create or update the .venv and install all dependencies.

  • make check: Non-mutating local gate: verify Black on src/ and tests/, Ruff lint, Pyright, then the fast test suite. Does not rewrite files; use make fix when checks fail for formatting or auto-fixable lint.

  • make fix: Apply Black, Ruff import sorting (I), and Ruff --fix on src/ and tests/ (mutating).

  • make check-ci-parity: Run a broader subset of the GitHub Actions Code Quality workflow via uv run (synapse format/lint scripts, type checks, file/function limits, rumdl, pytest with coverage). Requires uv on your PATH. Still not identical to CI: spell check (cspell), the eval suite, Codecov, and health-check upload steps run only in Actions—see Troubleshooting — Local make check vs CI.

  • make test: Run the default suite in parallel (-n auto), skip @pytest.mark.slow, no coverage (timeouts). Use make check-ci-parity for the full pytest+coverage command that matches CI.

  • make test-full: Run the full test suite (including slower tests) with a longer timeout.

  • make commit-check: Run the same checks as make check before using /cortex/commit for the full commit pipeline. With Cortex MCP connected, Phase A / Step 12 use the zero-arg tools documented in docs/api/tools.md.

For Swift Package Manager projects, the native quality gate runs the complete suite with swift test --enable-code-coverage --no-parallel. Test cases are scheduled serially; concurrent tasks and task groups inside each test remain concurrent. This native adapter invokes Swift directly, not the Synapse test script, and records the same arguments in its test transcript.

Key Tools

Cortex exposes 14 MCP tools, 6 static cortex:// resources, and up to 4 setup prompts (one always-on plus up to three configuration-dependent). Machine-readable inventory: docs/_generated/tool-inventory.json (must match cortex.discovery.published_inventory; CI enforces parity).

Published tools (canonical TOOL_CATEGORIES order — see docs/api/tools.md):

Tool

Purpose

manage_file()

Memory bank read/write (zero-arg reads activeContext.md)

plan()

Plan create/list/get/complete/register/archive_completed

update_memory_bank()

Roadmap/progress/activeContext mutations

session()

Session start, orientation, compact

run_quality_gate()

Phase A quality checks and Step 12 final gate (zero-arg)

autofix()

Auto-fix lint/format/types/markdown (zero-arg)

think()

Reasoning scratchpad

ingest()

Stage raw external sources under memory-bank for /cortex/ingest

run_docs_gate()

Phase B docs validation (zero-arg)

pipeline_handoff()

Inter-phase state exchange (init/write/read/clear)

write_artifact()

Allowlisted skill JSON and Synapse rule artifact writes

compress_memory_bank()

Compress project CLAUDE.md and memory-bank markdown to reduce session tokens

memory_wal()

Memory-bank WAL read, anomaly hints, snapshot/restore

propose_framework_optimization()

Draft/self-test a Synapse prompt/rule change in an isolated, always-removed worktree

Read-only discovery uses resources (not in this table): cortex://health/connection, cortex://structure, cortex://context, cortex://rules, cortex://validation, cortex://analysis. Quick “do not” guidance: AGENTS.md quick reference.

Prompts

Prompts are for setup and migration; for daily work use plan → do → commit tools.

Situation

Prompt

New project, no Memory Bank

initialize

Legacy Memory Bank under memory-bank/ or .memory-bank/

migrate

Share rules across projects

setup_synapse

tiktoken cache missing (local encoding cache setup)

populate_tiktoken_cache

Full prompt list: docs/prompts

Memory Bank Structure

The Memory Bank lives under .cortex/ and works with any editor, LLM, or agent.

  • .cortex/memory-bank/ — core files: projectBrief, productContext, activeContext, systemPatterns, techContext, progress, roadmap

  • .cortex/plans/ — development plans linked to the roadmap

  • .cortex/synapse/ — shared rules and prompts (Git submodule)

  • .cortex/config/, .cortex/history/, .cortex/index.json — configuration, history, and metadata

Legacy layouts are migrated by the migrate prompt; see Getting started.

Limitations

  • Token counts are tiktoken-based; when tiktoken is unavailable offline, a character-count heuristic (~1 token per 4 characters) is used. It tracks English prose closely but under-counts source code (~0.6x), Cyrillic (~0.7x), CJK (~0.3x) and emoji (~0.1x), so budgets enforced on such content while offline can overflow.

  • Memory-bank summarization never rewrites what it keeps: under the default extract_key_sections strategy kept sections are replayed verbatim and dropped sections are disclosed by name or count. It is not lossless — whole sections are removed to meet the budget — and it may miss its target reduction rather than rewrite content. The compress_verbose and headers_only strategies additionally rewrite lines, elide code blocks and keep partial bodies, so a path, error string or constraint can disappear mid-section. Prefer the default when content must survive intact.

  • AS-OF reconstruction is unavailable for WAL entries whose reverse delta was pruned or dropped by compaction; those historical versions cannot be recovered.

  • BM25 relevance (retrieval/bm25.py) computes IDF over the per-call candidate corpus only — there is no global index, so scores are not comparable across calls.

  • The Memory Bank format is deliberately editor/LLM/agent-agnostic; Cortex does not attempt semantic understanding beyond retrieval and summarization heuristics.

Documentation

Available Tools

10 tools
autofixFix Quality IssuesA

Auto-fix formatting, linting, type errors, and markdown lint. Zero args required.

USE WHEN: Phase A fails and automated fixes are needed before re-running checks. Called by commit-checks, commit-final-gate, and implement-code agents after preflight_passed=false. Runs fix_errors, format, type_check, and markdown auto-fix.

INTEGRITY SAFEGUARDS:

  • Do not use this tool output as a "done" signal by itself; always re-run run_quality_gate() and validate changed modules still import cleanly.

  • If a fix iteration introduces new failures/regressions, roll back that attempt and retry with a different approach (max 3 attempts).

EXAMPLES:

  • autofix() immediately after a failing run_quality_gate() call to auto-fix formatting, linting, type, and markdown issues.

  • autofix() inside implement-code or commit-checks agents on the fix path before re-running the quality gate.

Inputs: no named parameters.

compress_memory_bankCompress Memory Bank (CLAUDE.md, .cortex/memory-bank/*.md)A

Compress project memory files (CLAUDE.md, .cortex/memory-bank/*.md) to reduce session token cost. Creates .original backups; validates structural integrity before overwriting. Returns per-file compression ratios.

USE WHEN: Attached projects need shorter CLAUDE.md / memory-bank prose after cortex://analysis flags compression candidates, or before long sessions.

DO NOT: Run on source code, tests, or user-facing docs outside memory paths.

EXAMPLES:

  • compress_memory_bank() — zero-arg uses MCP workspace root

  • compress_memory_bank(project_root="/path/to/project")

RETURNS: JSON with status and result (CompressMemoryBankResult fields).

Inputs: project_root.

memory_walMemory bank write-ahead log (audit / rollback)A

Inspect or manage the memory-bank WAL (JSONL audit log and snapshots).

USE WHEN: You need an audit trail of memory-bank writes, anomaly hints, or a filesystem snapshot/restore of .cortex/memory-bank/*.md (not a git substitute).

DO NOT: Treat WAL as authoritative security auditing; it is best-effort and can be disabled by disk errors (writes still proceed).

EXAMPLES:

  • memory_wal(operation="read") — last 50 WAL entries

  • memory_wal(operation="anomalies") — heuristic warnings

  • memory_wal(operation="snapshot", label="backup-2026-04-15")

  • memory_wal(operation="restore", label="backup-2026-04-15")

Pre-compact automation: there is no bundled Claude PreCompact hook in this repo; run memory_wal(operation="snapshot", label="pre-compact-…") manually before risky compaction if you want a rollback point.

Inputs: label, since, operation.

pipeline_handoffPipeline Handoff (Inter-Agent State)A

Structured inter-agent communication for pipeline workflows.

USE WHEN: Orchestrators need to exchange structured data between pipeline phases. Each phase writes its output; the next phase reads it. All data persists in .cortex/.session/{id}/{pipeline}/.

WORKFLOW (simplified):

  1. pipeline_handoff(operation="init", pipeline="commit")

  2. pipeline_handoff(operation="write", pipeline="commit", phase="preflight", data='{"status":"complete","snapshot_ref":"abc123"}')

  3. pipeline_handoff(operation="read", pipeline="commit", phase="preflight") → reads phase data

  4. pipeline_handoff(operation="read", pipeline="commit") → reads full pipeline state (all phases)

  5. pipeline_handoff(operation="clear", pipeline="commit")

EXAMPLES:

  • pipeline_handoff(operation="init", pipeline="commit")

  • pipeline_handoff(operation="write", pipeline="commit", phase="checks", data='{"status":"passed","coverage":0.94}')

  • pipeline_handoff(operation="read", pipeline="commit", phase="checks")

  • pipeline_handoff(operation="read", pipeline="commit")

  • pipeline_handoff(operation="clear", pipeline="commit")

Legacy aliases (write_task, read_task, write_result, read_state) still work.

RETURNS: JSON with {status, ...} for write ops; JSON file content for reads.

Args: operation: init | write | read | read_log | status | mark_running | clear | snapshot | rollback (legacy: write_task, read_task, write_result, read_state) pipeline: Pipeline name (e.g. "commit", "implement"). Default: "default". phase: Phase name (e.g. "preflight", "checks"). Required for write. For read: if given, reads that phase; if omitted, reads full state. data: Payload for write and init. Accepts JSON string or native object. When the JSON includes free-text fields such as context or summary, write compact technical prose (see cortex://rules, Agent-Internal Communication): no filler or hedging; keep file paths and error messages verbatim. paths: Paths to snapshot for operation="snapshot". Can be passed via this argument or via data={"paths":[...]} for arg-stripping clients. snapshot_id: Snapshot id for operation="rollback". Can be passed via this argument or via data={"snapshot_id":"..."}. ctx: MCP context (auto-provided).

Inputs: data, paths, phase, pipeline, +2 more.

planPlan (Create/List/Get/Complete/Register)B
Destructive

Plan lifecycle: create, list, get, complete, register, graph, or archive_completed.

USE WHEN: managing plan files, marking plans complete, registering roadmap entries, or reading the plan dependency graph (operation="graph"). EXAMPLES: plan(operation="create", ...), plan(operation="graph"), plan(operation="register", ...).

Inputs: slug, title, status, content, +17 more.

run_docs_gateRun Docs GateA
Idempotent

Run Phase B docs/memory-bank sync validation. Zero args required.

USE WHEN: Validating that timestamps, roadmap_sync, and memory-bank files are consistent after documentation updates. Called by the commit-docs subagent as a zero-arg alternative to execute_pre_commit_checks(phase="B") (which Cursor's MCP bridge zero-args to Phase A, running tests instead).

RETURNS: JSON with docs_phase_passed (bool), timestamps_result, and roadmap_sync_result. Does NOT run tests or code quality checks.

EXAMPLES:

  • run_docs_gate() after updating memory-bank files via manage_file() in Phase B of the commit pipeline.

  • run_docs_gate() to re-check roadmap_sync and timestamps without re-running tests or other quality checks.

Inputs: no named parameters.

run_quality_gateRun Quality GateA

Run Phase A quality gate end-to-end and return full result. Zero args required.

USE WHEN: Running the commit pipeline Phase A quality gate or the Step 12 final gate. Spawns checks as a detached subprocess and polls with heartbeat progress notifications, keeping the MCP stdio connection alive.

Config is read from the pipeline session file written by pipeline_handoff(operation="write", pipeline="commit", phase="checks"). Supported keys: coverage_threshold (float), test_timeout (int), force_fresh (bool), reflection (bool), force_reflection (bool). When reflection is enabled and primary checks pass, a heuristic reflection pass runs; error-level findings set preflight_passed to false.

EXAMPLES:

  • run_quality_gate() before commit Phase A.

  • pipeline_handoff(write, checks, {"force_fresh": true, "test_timeout": 600}) then run_quality_gate() for Step 12 final gate.

Inputs: no named parameters.

sessionSession (Start/Register/Deregister/Compact)C
Destructive

USE WHEN: Session lifecycle (orientation, registry, compaction).

EXAMPLES: session(operation="start", goal="Fix auth bug"); session(operation="compact", summary="Session handoff").

Inputs: goal, role, summary, blockers, +10 more.

thinkThinkingA

Append a thought to internal scratchpad.

USE WHEN: Agent needs reasoning before action or multi-step deliberation. EXAMPLES: think(thought="Check constraints"), think(thought="Step 1", thought_number=1, total_thoughts=2, next_thought_needed=True).

Inputs: thought, branch_id, is_revision, thought_number, +5 more.

update_memory_bankUpdate Memory Bank (Roadmap & Append)A

Add/remove roadmap entries and append memory-bank entries.

USE WHEN: You need a single memory-bank mutation entrypoint for roadmap edits (add/remove section entries) or append-style updates for progress, active context, or operations log entries.

DO NOT use this tool for free-form markdown rewrites; Prefer targeted operation modes so validation and sync rules remain enforceable.

EXAMPLES:

  • update_memory_bank(operation="roadmap_add", section="pending", entry_text="- Improve retrieval scoring")

  • update_memory_bank(operation="progress_append", date_str="2026-04-14", entry_text="Implemented typed memory reader")

  • update_memory_bank(operation="log_append", operation_type="fix", title="Resolve docs gate mismatch", summary="Aligned roadmap and progress")

Inputs: title, section, summary, date_str, +8 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

    TDQS

    A3.7/5.0

    Scored across 10 tools

    Disambiguation5/5

    Each tool addresses a unique aspect of the development workflow: autofix handles fixes, compress and memory_wal manage memory, pipeline_handoff and session handle orchestration, plan and update_memory_bank manage planning and memory mutations, run_* gates run checks, and think provides reasoning. No two tools have overlapping purposes.

    Naming Consistency3/5

    Names mix verb_noun (run_docs_gate, update_memory_bank, compress_memory_bank) with noun phrases (memory_wal, pipeline_handoff) and bare verbs (autofix, think). The pattern is inconsistent, though all use lowercase and underscores.

    Tool Count5/5

    10 tools is a well-scoped set for the domain: code quality, memory management, pipeline handoff, planning, sessions, and cognition. No tool seems redundant or missing.

    Completeness4/5

    The tool set covers the full lifecycle of code quality checks, memory operations, pipeline communication, planning, and session management. Minor gaps exist (e.g., no tool to inspect raw quality gate output without re-running), but core workflows are well-supported.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      Not graded
      maintenance
      An MCP server that provides persistent project context, workflow management, and knowledge capture for AI coding agents. It enables agents to maintain structured memory across sessions by tracking project profiles, conventions, skills, and technical debt.
      7
      -
    • A
      license
      B
      quality
      D
      maintenance
      An MCP server that gives AI assistants persistent memory across sessions. It stores project context, decisions, and progress in structured markdown files as well as a knowledge graph and sequential thinking for better memory storage.
      36
      40 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Cortex MCP provides AI agents with long-term portfolio memory by transforming project history and developer decisions into a structured, queryable knowledge graph. It enables assistants to maintain context across different repositories by exposing historical patterns, architectural decisions, and technology preferences through the Model Context Protocol.
      25 npm
      6
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that provides persistent, cross-session memory and team knowledge sharing for AI development workflows. It enables project DNA scanning, semantic search, context budgeting, and git-aware indexing to prevent AI context loss between sessions.
      44 npm
      MIT