Skip to main content
Glama

cortexmem

Persistent memory for AI coding agents. Zero config, works with Cursor, Claude Code, Codex, and any MCP-compatible editor.

npm version License: MIT Node.js >= 18

AI coding agents lose all context when a session ends. CortexMem fixes this by building a semantic memory store from your git history, codebase, and session context, then making it searchable via MCP tools.

Setup

Step 1: Initialize your project

cd your-project
npx cortexmem init

This scans your git history and codebase, embeds everything locally, and stores it in .cortexmem/store.db. It also generates editor config files (CLAUDE.md, .cursorrules, codex.md) that instruct AI agents to use cortexmem automatically.

First run downloads the embedding model (~30MB, one-time). Subsequent runs are incremental and only re-index new commits and changed files.

$ npx cortexmem init

CortexMem — initializing context for /Users/you/my-project

Full scan — first-time initialization...
  Found 142 commits → 87 chunks
  Found 38 files → 52 chunks

Embedding 139 chunks...
Storing in database...
Building project summary...
Generating editor configs...
  Created: CLAUDE.md, .cursorrules, codex.md
Done!

Summary:
  Git commits indexed: 142
  Source files scanned: 38
  Total chunks stored: 139

Storage: /Users/you/my-project/.cortexmem/store.db

Add to your MCP config to start using cortexmem with your AI agent.

You can optionally include a project spec or requirements doc:

npx cortexmem init ./PROJECT.md

Step 2: Add to your editor's MCP config

Cursor (add to ~/.cursor/mcp.json):

{
  "mcpServers": {
    "cortexmem": {
      "command": "npx",
      "args": ["-y", "cortexmem"]
    }
  }
}

Claude Code (add to ~/.claude.json or project settings):

{
  "mcpServers": {
    "cortexmem": {
      "command": "npx",
      "args": ["-y", "cortexmem"]
    }
  }
}

With LLM-powered compaction (optional, add your Anthropic API key):

{
  "mcpServers": {
    "cortexmem": {
      "command": "npx",
      "args": ["-y", "cortexmem"],
      "env": {
        "ANTHROPIC_API_KEY": "sk-ant-..."
      }
    }
  }
}

Restart your editor. CortexMem is running.

ANTHROPIC_API_KEY is optional. It enables LLM-based session compaction via summarize_session. Without it, everything else works and compaction uses a deterministic fallback.

Step 3: There is no step 3

The generated editor config files (CLAUDE.md, .cursorrules, codex.md) instruct your AI agent to use cortexmem automatically. It will:

  • Load context from previous sessions on startup

  • Save decisions, discoveries, and constraints as you work

  • Compact memory at session end

No manual tool calls needed.

Related MCP server: ContextWeave

Example: What a session looks like

Session 1: You start working on auth

Your AI agent automatically calls get_context at session start:

## CortexMem Context — my-project
Initialized: 2026-03-08T10:30:00Z

### Project Overview
my-project: Node.js/TypeScript API server. 142 commits, 38 files.
Stack: Express, PostgreSQL, Jest. Main modules: auth, payments, users.

### Index Stats
- Commit Summaries: 87 chunks
- Code Summaries: 52 chunks

During work, the agent saves context automatically:

save_context({
  context_type: "decision",
  content: "Using JWT with refresh tokens for auth. Access tokens expire in 15min, refresh tokens in 7 days. Stored in httpOnly cookies, not localStorage.",
  related_files: ["src/auth/jwt.ts", "src/middleware/auth.ts"]
})
→ Saved decision context (id: 12, session: a1b2c3, branch: main)

save_context({
  context_type: "constraint",
  content: "Auth middleware must never be modified directly. Extend via plugins in src/auth/plugins/",
  related_files: ["src/middleware/auth.ts"]
})
→ Saved constraint context (id: 13, session: a1b2c3, branch: main)

save_context({
  context_type: "state",
  content: "Auth implementation: JWT service done, middleware done, refresh token rotation TODO",
  related_files: ["src/auth/jwt.ts"]
})
→ Saved state context (id: 14, session: a1b2c3, branch: main)

At session end, the agent calls summarize_session:

summarize_session({ session_summary: "Implemented JWT auth with refresh tokens" })
→ Compaction complete:
  Session: Compacted 3 entries into session summary
  Branch (main): Updated branch summary
  Project: Updated project overview

Session 2: Different day, context is preserved

The agent calls get_context and immediately has full context:

## CortexMem Context — my-project

### Project Overview
my-project: Node.js/TypeScript API with JWT auth (access + refresh tokens),
PostgreSQL, Express. Auth module complete, payment refactor in progress.

### Branch: main
JWT auth implemented with httpOnly cookies. Auth middleware uses plugin
architecture (never modify directly). Refresh token rotation still TODO.

### Recent Sessions (main)
#### Session a1b2c3 (2026-03-08)
Implemented JWT authentication with refresh tokens. Access tokens expire
in 15min, refresh in 7 days. Created plugin-based auth middleware.
Refresh token rotation is the next task.

### Index Stats
- Decisions: 1 chunks
- Constraints: 1 chunks
- State: 1 chunks
- Commit Summaries: 87 chunks
- Code Summaries: 52 chunks

The agent can also search for specific context:

get_context({ query: "auth middleware", depth: 3 })
→ ## CortexMem Context — my-project
  Query: "auth middleware" | depth: 3

  ### [project > branch:main > session:a1b2c3] (87% match)
  JWT auth with refresh tokens. Plugin-based middleware architecture.

  **Details:**
  - [Constraint] Auth middleware must never be modified directly. Extend via plugins
  - [Decision] Using JWT with refresh tokens for auth. Access tokens expire in 15min...

Re-running init (incremental)

When you come back after more commits:

$ npx cortexmem init

CortexMem — initializing context for /Users/you/my-project

Incremental update — scanning changes since last init...
  8 new commits → 6 chunks
  3 files changed
  3 changed files → 4 chunks

Embedding 10 chunks...
Storing in database...
Building project summary...
Done!

Summary (incremental):
  Git commits indexed: 8 (new)
  Source files scanned: 38
  Total chunks stored: 10 (new)

How It Works

  1. cortexmem init scans your git history and codebase, chunks and embeds everything locally

  2. Everything is stored in .cortexmem/store.db, a single SQLite file portable across editors and machines

  3. Your AI agent uses 4 MCP tools to search, save, and compact context

  4. Context is organized in a pyramid: project, branch, and session summaries with raw chunks underneath

The Context Pyramid

Project Summary              ← "What is this project about?"
├── Branch: main             ← "What's happening on main?"
│   ├── Session a1b2c3       ← "What did we do 2 days ago?"
│   └── Session d4e5f6       ← "What did we do yesterday?"
└── Branch: feature/payments ← "What's the payments work?"
    └── Session g7h8i9
  • get_context() returns the pyramid overview (~500-800 tokens)

  • get_context({ query: "..." }) searches hierarchically, matching summaries first and drilling into raw chunks only when needed

  • summarize_session() rolls up: session chunks → session summary → branch summary → project summary

What Gets Indexed

Source

What's Extracted

Git log

Commit messages, descriptions, file change patterns

Source files

Code structure, functions, classes, patterns

Config files

Stack, tooling, dependencies

Docs (.md)

Documentation content

Project file

Specs, requirements (via cortexmem init <file>)

Session context

Decisions, constraints, discoveries saved by the agent

MCP Tools

Tool

When to use

What it does

get_context

Session start, or when you need specific context

Returns pyramid overview (no args) or hierarchical search (with query). Depth 0-3 controls granularity.

save_context

When the agent makes a decision, discovers something, notes a constraint

Embeds and stores instantly. Types: decision, constraint, state, discovery, preference.

summarize_session

End of session

Compacts saved context into the pyramid. Uses Claude Haiku if ANTHROPIC_API_KEY is set, deterministic fallback otherwise.

get_status

Anytime

Quick stats: chunk counts by type, storage location, last init time.

Context Types

Type

Purpose

Example

decision

Architectural/technical choices

"Chose PostgreSQL over MongoDB for ACID transactions"

constraint

Hard rules to never violate

"Never modify auth middleware directly"

state

Current WIP status

"Payment refactor: 2/4 services done"

discovery

Non-obvious codebase facts

"UserService is called from 6 places, not 3"

preference

Code style conventions

"Snake_case for variables, PascalCase for classes"

CLI Commands

cortexmem init [project-file]   Scan git history + codebase, build context store
                                 Incremental on re-run, only indexes new changes
cortexmem inject <file>         Inject/update a project file (spec, requirements)
cortexmem status                Show what's stored
cortexmem                       Start MCP server (used by AI editors)

Portability

CortexMem stores everything in a single file: .cortexmem/store.db

# Move to a new machine
scp .cortexmem/store.db user@newmachine:~/project/.cortexmem/

# Share with teammates (commit it)
git add .cortexmem/store.db

# Switch editors, same file works everywhere
# Claude Code -> Cursor -> Codex, no migration needed

Environment Variables

Variable

Purpose

Default

ANTHROPIC_API_KEY

Enables LLM compaction in summarize_session

none (deterministic fallback)

CORTEXMEM_MAX_TOKENS

Default max tokens for get_context

3000

CORTEXMEM_MODEL

Model for compaction

claude-haiku-4-5-20251001

Architecture

  • Embeddings: all-MiniLM-L6-v2 via @xenova/transformers. Runs locally, no API key needed, ~30MB model

  • Storage: SQLite via sql.js (WASM). Zero native dependencies, works on any OS

  • Search: Hybrid keyword + vector search. Keywords by default, vector when model is warm. Both work offline.

  • Transport: MCP stdio. Works with any MCP-compatible editor

Development

git clone https://github.com/Ashprakash/cortexmem.git
cd cortexmem
npm install
npm test          # run 106 tests
npm run dev       # run with tsx
npm run build     # compile TypeScript

License

MIT

Available Tools

4 tools
get_contextA

Retrieve persistent memory from previous sessions. Call at session start with no arguments to get the context pyramid: project overview, current branch summary, and recent session summaries — all in ~500-800 tokens. Use with a query to do hierarchical search: matches project → branch → session summaries first, then drills into raw chunks only when needed. Use depth to control how deep to search. Always call this first in a new session.

ParametersJSON Schema
NameRequiredDescriptionDefault
depthNoSearch depth: 0=project summary only, 1=+branch summaries, 2=+session summaries (default), 3=+raw chunks. Start shallow, go deeper if needed.
queryNoSearch query. Searches hierarchically: project → branches → sessions → raw chunks. Omit for a full project overview pyramid.
typesNoFilter results by context type (only applies to raw chunk search at depth 3)
max_tokensNoMax tokens to return (default 3000)

TDQS

A3.9/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations present, the description carries the full burden and does meaningful work: it discloses the token budget of the default call (~500-800 tokens), the lazy hierarchical retrieval model (matches project → branch → session first, drills into raw chunks only when needed), and the depth control. It does not state permission/auth requirements or explicitly confirm the operation is read-only, though 'Retrieve' strongly implies it.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well front-loaded: the core action and the recommended no-argument session-start call come first, followed by query mode and depth. It is efficient, but the session-start instruction is stated twice ('Call at session start with no arguments' and 'Always call this first in a new session'), which is mild redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 4-parameter tool with no annotations and no output schema, the description is nearly sufficient: it explains the default invocation, the search mode, depth progression, and roughly what gets returned and how large it is. The remaining gaps are the response shape of query results and any auth/prerequisite context, neither of which is covered anywhere else.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents depth levels, the query hierarchy, the type filter, and the max_tokens default — baseline 3 applies. The description echoes the depth and query behavior but adds no syntax, format, or interaction detail beyond what the schema fields state.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb and resource ('Retrieve persistent memory from previous sessions') and describes the concrete artifact returned: the context pyramid of project overview, branch summary, and recent session summaries. It implicitly separates itself from the write-oriented sibling save_context by framing itself as the read/start-of-session tool, but it never names get_status or summarize_session, so sibling differentiation is only partial.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Gives clear conditions for the two main modes — 'Call at session start with no arguments' for the pyramid, and 'Use with a query' for hierarchical search — plus 'Use depth to control how deep to search.' It even gives ordering guidance ('Always call this first in a new session'). It stops short of naming when NOT to use it or pointing at the alternatives (get_status, summarize_session), which is what a 5 would require.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_statusB

Quick stats on cortexmem: total chunks stored, breakdown by type, storage location, last init time, last indexed commit.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the burden. It implicitly reveals a safe, read-only, zero-argument inspection operation and discloses the exact fields returned, which is useful given there is no output schema. It does not mention permission requirements, cost, or freshness guarantees for the reported values, so a moderate score is warranted.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single front-loaded sentence that gets to the point immediately, and every listed item is informative because there is no output schema to enumerate them. Slightly list-heavy but none of it is wasted.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a zero-parameter, no-output-schema status tool, the description adequately covers what the agent gets back (the enumerated stats) and how to treat the call. Missing only when to prefer it over the sibling context tools.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool takes zero parameters, so there is nothing for the description to disambiguate; baseline is 4. This is the correct ceiling for a no-argument tool.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states a specific resource (cortexmem) and enumerates exactly what the tool reports: total chunks, type breakdown, storage location, last init time, last indexed commit. It's clearly a read-only status/inspection tool, distinguishable from the save/get/summarize context siblings. No sibling is named explicitly, so it stops short of a 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

There is no statement of when to call this tool versus the alternatives (save_context, get_context, summarize_session), nor any prerequisites or exclusions. Usage is only implied by the fact that it reports status.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

save_contextA

Save context to persistent memory. Call this whenever you make a decision, discover something non-obvious about the codebase, agree on a constraint with the user, note WIP state, or learn a coding preference. Saved context persists across sessions and editors. Call proactively — future sessions depend on what you save now.

ParametersJSON Schema
NameRequiredDescriptionDefault
contentYesThe context to save. Be specific and include rationale. Example: "Chose PostgreSQL over MongoDB because we need ACID transactions for payment processing."
confidenceNoHow confident you are in this context (default: high)
context_typeYesCategory: decision (architectural choices), constraint (hard rules), state (WIP progress), discovery (non-obvious facts), preference (code style conventions)
related_filesNoFile paths related to this context

TDQS

A3.8/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description must carry the full behavioral burden. It usefully discloses that saved context 'persists across sessions and editors' and that calling proactively matters. However, it says nothing about overwrite/deduplication behavior, whether saves are keyed by type, permissions, or what a save returns — notable gaps for a mutation tool with no annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three tight sentences, front-loaded with the core action, then usage triggers, then the persistence rationale. No filler; every clause earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a four-parameter write tool with no output schema and no annotations, the description covers what it does, when to call it, and the cross-session persistence guarantee. It is nearly complete, missing only the post-save mechanics (what happens to existing context, what is returned).

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all four parameters including the enum mappings and an inline example. The description's prose enumeration of the context types mirrors the enum rather than extending it, so baseline 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb and resource: 'Save context to persistent memory.' The write-side counterpart to siblings like get_context is obvious from the verb, though the description never names a sibling to sharpen the boundary. Purpose is unambiguous and distinct from the read/summary siblings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Gives concrete, enumerated triggers — decisions, non-obvious discoveries, agreed constraints, WIP state, coding preferences — plus an explicit 'call proactively' directive. It lacks any 'when not to use' guidance or a pointer to the retrieval sibling (get_context), so it stops short of full routing guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

summarize_sessionA

Compact and persist session memory into the context pyramid. Creates a session summary from saved context, rolls it up into a branch summary, then updates the project overview. Call at end of session. Works best with ANTHROPIC_API_KEY for LLM-powered compaction; falls back to deterministic summarization without it.

ParametersJSON Schema
NameRequiredDescriptionDefault
session_summaryNoBrief description of what was accomplished this session

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and does well: it discloses that three persisted artifacts are created/updated, that an ANTHROPIC_API_KEY enables LLM compaction, and that a deterministic fallback exists without it. It omits whether repeated calls are idempotent or how the writes can be undone.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Four short sentences, front-loaded with the action and its outputs, followed by the trigger condition and the auth/fallback caveat. Every sentence contributes distinct information with no padding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a mutation tool with no annotations and no output schema, the description covers side effects, timing, and the auth-dependent execution path well. It does not describe what the agent gets back on success or failure, which is the remaining gap.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Only one optional parameter at 100% schema description coverage, so the schema already defines it fully. The description adds no format, length, or content guidance for session_summary beyond noting context comes from 'saved context,' so the baseline 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb+resource ('Compact and persist session memory') and then enumerates the three concrete artifacts it produces (session summary, branch summary, project overview), which clearly distinguishes it from save_context/get_context/get_status.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly says 'Call at end of session,' giving a clear usage trigger. It does not name a when-not condition or point at an alternative sibling for related memory operations, so it stops short of full routing guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

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

  1. 4 tool updatesv0.2.0
    • First observedget_context
    • First observedget_status
    • First observedsave_context
    • First observedsummarize_session

TDQS

A3.9/5.0

Scored across 4 tools

Disambiguation4/5

Each tool targets a distinct phase of the memory lifecycle: save_context writes raw chunks, get_context reads/search, summarize_session compacts, and get_status reports stats. The only mild overlap is that both save_context and summarize_session persist data, but the descriptions clearly differentiate raw chunks from session summaries.

Naming Consistency5/5

All tool names use a consistent snake_case verb_noun pattern: save_context, get_status, get_context, summarize_session. The verbs (save, get, summarize) are standard and predictable.

Tool Count5/5

Four tools is a well-scoped, minimal set for a persistent memory server. Each tool maps to a distinct operation (write, read, summarize, status), and none feels redundant or missing at the count level.

Completeness4/5

The surface covers saving, retrieving, summarizing, and status reporting for persistent memory. However, it lacks an explicit delete/forget or edit operation, so agents cannot easily prune stale or incorrect memories — a minor but real gap.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    A
    maintenance
    Provides persistent memory for AI coding agents via MCP, enabling agents to store and semantically recall facts, events, and lessons across sessions, all running locally without cloud dependencies.
    Apache 2.0
  • A
    license
    A
    quality
    A
    maintenance
    Semantic codebase search + persistent working memory for AI code editors. Local, zero-config, MCP. No API key.
    8
    23
    2
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Offline-first, persistent repository memory for coding agents. Provides MCP tools for repository scanning, searching, context, and impact analysis, helping agents navigate and edit code efficiently.
    Apache 2.0