Skip to main content
Glama

Memory MCP

A Model Context Protocol (MCP) server that gives AI coding agents persistent, evolving knowledge about a codebase. Instead of starting cold every session, agents can store and retrieve observations about architecture, conventions, gotchas, and recent work context.

Tools

Tool

Description

memory_context

Session start AND pre-task lookup. Call with no args for user + preferences + stale nudges; call with context for task-specific knowledge

memory_query

Structured search with brief/standard/full detail levels and AND/OR/NOT filter syntax. Scope defaults to "*" (all topics)

memory_store

Store a knowledge entry with dedup detection, preference surfacing, lobe auto-detection, and a review-required gate for likely-ephemeral content

memory_correct

Correct, update, or delete an existing entry (suggests storing as preference)

memory_bootstrap

First-use scan to seed knowledge from repo structure, README, and build files

Hidden tools (still callable, not in the catalog — agents learn about them from hints/errors): memory_list_lobes (lobe paths and stats), memory_stats (entry counts, freshness, storage), memory_diagnose (server health, crash history, recovery steps)

Related MCP server: @brainfeather/mcp

Knowledge Topics

Topic

Purpose

Global?

Expires?

Default Trust

user

Personal info (name, role, communication style)

Yes

Never

user

preferences

Corrections, opinions, coding rules

Yes

Never

user

gotchas

Pitfalls and known issues

No

Never

user

architecture

System design, patterns, module structure

No

30 days

agent-inferred

conventions

Code style, naming, patterns

No

30 days

agent-inferred

modules/<name>

Per-module knowledge

No

30 days

agent-inferred

recent-work

Current task context (branch-scoped)

No

30 days

agent-inferred

Global topics (user, preferences) are stored in a shared global store at ~/.memory-mcp/global/ and are accessible from all lobes. This means your identity and coding preferences follow you across every repository without duplication.

Smart Surfacing

  • Dedup detection: When you store an entry, the response shows similar existing entries in the same topic (>35% keyword overlap) with consolidation instructions

  • Preference surfacing: Storing a non-preference entry shows relevant preferences that might conflict

  • Ephemeral review gate: Likely-ephemeral content is blocked before persistence by default. Re-run memory_store(..., durabilityDecision: "store-anyway") only when you intentionally want to keep it.

  • Piggyback hints: memory_correct suggests storing corrections as reusable preferences

  • memory_context: Describe your task in natural language and get ranked results across all topics with topic-based boosting (preferences 1.8x, gotchas 1.5x)

Smart Filter Syntax

memory_query supports a filter mini-language for precise searches:

Syntax

Meaning

Example

A B

AND (both required)

reducer sealed

A|B

OR (either matches)

MVI|MVVM

-A

NOT (exclude)

-deprecated

combined

Mix freely

kotlin sealed|swift protocol -deprecated

Filters use stemmed matching, so reducers matches reducer and exceptions matches exception.

Quick Start

# Install dependencies
npm install

# Build
npm run build

# Run tests
npm test

Configuration

Create a memory-config.json file next to the memory MCP server:

{
  "lobes": {
    "workspace-mcp": {
      "root": "$HOME/git/personal/workspace-mcp",
      "budgetMB": 2
    },
    "workrail": {
      "root": "$HOME/git/personal/workrail",
      "budgetMB": 2
    }
  }
}

Note: memoryDir is optional. When omitted, storage auto-detects to .git/memory/ for git repos.

What's a "lobe"? Each repository gets its own memory lobe -- a dedicated knowledge scope. Think of it like brain regions: the "workrail lobe" stores knowledge about workrail, the "workspace-mcp lobe" stores knowledge about workspace-mcp.

Benefits:

  • Portable ($HOME and ~ expansion works across machines)

  • Discoverable (use memory_list_lobes to see what's configured)

  • Easy to extend (just add a new lobe entry)

Environment Variables (Fallback)

If no memory-config.json is found, the server falls back to environment variables:

Variable

Default

Description

MEMORY_MCP_WORKSPACES

--

JSON mapping workspace names to repo paths (multi-repo mode)

MEMORY_MCP_REPO_ROOT

process.cwd()

Fallback: single-repo path (if WORKSPACES not set)

MEMORY_MCP_DIR

(auto-detect)

Override storage dir (relative to repo root, or absolute). Disables git-native auto-detection.

MEMORY_MCP_BUDGET

2097152 (2MB)

Storage budget per workspace in bytes

Adding a New Lobe

  1. Edit memory-config.json (create if it doesn't exist)

  2. Add lobe entry:

    {
    "my-project": {
      "root": "$HOME/git/my-project",
      "budgetMB": 2
    }
    }
  3. Restart the memory MCP server

  4. Verify: Use memory_list_lobes to confirm it loaded

The agent will see the new lobe in tool descriptions and can immediately use it with memory_store(lobe: "my-project", ...).

MCP Client Registration

With memory-config.json (recommended):

{
  "mcpServers": {
    "memory": {
      "command": "node",
      "args": ["/path/to/memory-mcp/dist/index.js"]
    }
  }
}

The server reads memory-config.json automatically -- no env vars needed.

Environment Variable Mode

{
  "mcpServers": {
    "memory": {
      "command": "node",
      "args": ["/path/to/memory-mcp/dist/index.js"],
      "env": {
        "MEMORY_MCP_WORKSPACES": "{\"android\":\"/path/to/android\",\"ios\":\"/path/to/ios\"}"
      }
    }
  }
}

Storage Location

Knowledge is stored as human-readable Markdown files -- one file per entry. The storage location is auto-detected with the following priority:

  1. Explicit memoryDir config -- if set in memory-config.json or MEMORY_MCP_DIR, uses that path

  2. Git-native (default) -- <git-common-dir>/memory/ using git rev-parse --git-common-dir. This ensures:

    • Invisible to git -- .git/ contents are never tracked, no .gitignore needed

    • Shared across worktrees -- all worktrees of the same repo share one memory store

    • Worktree/submodule safe -- resolves to the common .git/ directory regardless

  3. Central fallback -- ~/.memory-mcp/<lobe-name>/ for non-git directories

Use memory_stats or memory_list_lobes to see where memory is stored for each lobe.

File Structure

Each entry gets its own file. Recent-work entries are scoped by branch.

.git/memory/
  architecture/
    arch-e8d4f012.md              # One entry per file
  conventions/
    conv-a1b2c3d4.md
  gotchas/
    gotcha-7k3m9p2q.md
  recent-work/
    main/                          # Branch-scoped
      recent-f5e6d7c8.md
    feature-messaging-refactor/    # Sanitized branch name
      recent-9i0j1k2l.md
  modules/
    messaging/
      mod-4d5e6f7g.md

~/.memory-mcp/global/              # Global store (shared across all lobes)
  user/
    user-3f7a2b1c.md              # Personal info
  preferences/
    pref-5c9b7e3d.md              # Coding opinions & corrections

Concurrency Safety

Each entry is its own file with a random hex ID. Two MCP processes (e.g., Firebender + Cursor) writing different entries to the same repo never conflict -- they write to different files. The store reloads from disk before every read to pick up changes from other processes.

Branch-Scoped Recent Work

Recent-work entries are automatically tagged with the current git branch and stored in a branch-named subdirectory. memory_query filters recent-work to the current branch by default. Use branch: "*" to see recent-work from all branches.

Entry Format

# Build System & Language
- **id**: arch-3f7a2b1c
- **topic**: architecture
- **confidence**: 0.70
- **trust**: agent-inferred
- **created**: 2026-02-18T12:00:00.000Z
- **lastAccessed**: 2026-02-18T12:00:00.000Z

Detected: Node.js/TypeScript project (npm)

Trust Levels

Level

Confidence

Meaning

user

1.0

Human-provided or human-corrected knowledge

agent-confirmed

0.85

Agent-observed and verified against code

agent-inferred

0.70

Agent-observed, not yet verified

Resilience

The server uses a degradation ladder to stay useful even when things go wrong:

  • Running -- all lobes healthy, full functionality

  • Degraded -- some lobes failed to initialize but healthy ones continue working. Failed lobes report specific recovery steps via memory_diagnose.

  • Safe Mode -- all lobes failed. Only memory_diagnose and memory_list_lobes work, giving you enough information to fix the problem.

Crash journaling: On uncaught exceptions, the server writes a structured crash report to ~/.memory-mcp/crashes/ before exiting. The next startup surfaces the crash in memory_context() (briefing mode) with recovery steps. Use memory_diagnose(showCrashHistory: true) to see the full history.

Argument Normalization

Agents frequently guess wrong parameter names. The server silently resolves common aliases to avoid wasted round-trips:

Alias

Resolves to

key, name

title

value, body, text

content

query, search

filter

workspace, repo

lobe

Wildcard scope aliases (all, everything, global, project) resolve to *.

Architecture

types.ts          Domain types (discriminated unions, parse functions)
store.ts          MarkdownMemoryStore (CRUD, search, bootstrap, briefing)
text-analyzer.ts  Keyword extraction, stemming, similarity (stateless)
normalize.ts      Argument alias resolution (pure)
formatters.ts     Response formatters for tool handlers (pure)
config.ts         3-tier config loading (file > env > default)
git-service.ts    Git operations boundary (injectable for testing)
crash-journal.ts  Crash report lifecycle (build, write, read, format)
index.ts          MCP server, tool handlers, startup, migration

Design

See ideas/codebase-memory-mcp-design-thinking.md for the full design thinking document with 67 ideas, 5 concept packages, pre-mortem analysis, and test plan.

Available Tools

10 tools
briefA

Start of conversation — call once to load context for a project. Returns stored preferences, gotchas overview, stale entries needing review, and entry counts. Example: {"lobe": "my-project"} Surfaces everything previously saved via learn/gotcha/convention/prefer. Call once at session start. Results stay valid for the entire conversation — no need to re-call.

Inputs: lobe.

conventionA

When you notice a pattern the codebase follows, record it here. For personal style rules, use prefer() instead. Example: {"lobe": "my-project", "observation": "All ViewModels use StateFlow for UI state. LiveData is banned."} Store facts that help future sessions, not notes about this one. Wrong: "Migrated to StateFlow." Right: "All ViewModels use StateFlow." One insight per call. Persists across sessions, surfaces in brief() and recall(). Returns related knowledge. Required params: "lobe", "observation".

Inputs: lobe (required), observation (required), durabilityDecision.

conventionsA

Before writing new code, check how this codebase does things. Retrieves stored conventions, optionally filtered. Example: {"lobe": "my-project", "area": "testing"} or {"lobe": "my-project"} for all. recall() also surfaces conventions. Use this for focused convention lookup, recall() for broader cross-topic search.

Inputs: area, lobe.

fixA

When a stored entry is wrong or outdated, correct or delete it. IDs appear in brief/recall/gotchas/conventions results. Example: {"id": "gotcha-3f7a", "correction": "Updated text"} to replace, or {"id": "gotcha-3f7a"} to delete. Required param: "id". Pass "correction" to update; omit to delete.

Inputs: id (required), lobe, correction.

gotchaA

When something surprises you or doesn't work as expected, flag it here. Example: {"lobe": "my-project", "observation": "Gradle cache must be cleaned after Tuist changes or builds silently use stale artifacts"} Store facts that help future sessions, not notes about this one. Wrong: "Build failed because of stale cache." Right: "Gradle cache must be cleaned after Tuist changes." One insight per call. Persists across sessions, gets priority in brief() and recall(). Returns related knowledge. Required params: "lobe", "observation".

Inputs: lobe (required), observation (required), durabilityDecision.

gotchasA

Before making changes to an area, check for known pitfalls. Retrieves stored gotchas, optionally filtered. Example: {"lobe": "my-project", "area": "auth"} or {"lobe": "my-project"} for all. brief() already includes a gotchas overview. Use this when you need gotchas for a specific area not covered in the briefing.

Inputs: area, lobe.

learnA

When you understand how something works — architecture, dependencies, module boundaries — store it here. Catch-all for knowledge not covered by gotcha/convention. Example: {"lobe": "my-project", "observation": "Payments module depends on auth for tokens only, no other cross-module dependency"} Store facts that help future sessions, not actions you took or bugs you fixed. Wrong: "Fixed the null pointer in UserService." Right: "UserService.getUser() returns null when session expires — callers must handle this." One insight per call. Persists across sessions. Returns related knowledge. Required params: "lobe", "observation".

Inputs: lobe (required), observation (required), durabilityDecision.

memory_bootstrapA

When no lobe exists for a project — run this before any other tool. Scans repo structure, README, and build system to create a named lobe and seed initial memory. Required param: "root" (absolute path to repo) when the lobe does not yet exist. Example: {"lobe": "my-project", "root": "/absolute/path/to/repo"}. After bootstrapping, all other tools become available for that lobe.

Inputs: lobe, root, budgetMB.

preferA

When the user corrects you or states how they want things done, record it here. Example: {"rule": "Never use !! operator"} or {"rule": "Use Anvil for DI", "lobe": "my-project"} Highest trust level. Persists across sessions, surfaced in every brief(). Omit lobe for global preferences; add lobe to scope to one project. Required param: "rule".

Inputs: rule (required), lobe.

recallA

Before starting a task, surface prior knowledge you haven't loaded yet. Searches stored memory using semantic + keyword matching. Example: {"context": "auth token refresh", "lobe": "my-project"} Searches YOUR memory entries (from learn/gotcha/convention/prefer). Does NOT search the codebase or the internet. Call once per area. Skip if you already recalled this topic or received it from brief(). Knowledge stays in your context. Required param: "context" — the area you need knowledge about.

Inputs: context (required), lobe, maxResults.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 10 tools

    Disambiguation4/5

    Most tools have clear, distinct purposes: brief loads the full context, recall searches broadly, gotchas/conventions retrieve specific types, and gotcha/convention/learn/prefer add different kinds of knowledge. The overlap between recall and the focused retrieval tools is intentional and described, but the singular/plural pairs (convention vs. conventions, gotcha vs. gotchas) could cause misselection if the agent does not read descriptions carefully.

    Naming Consistency2/5

    Tool names follow no consistent pattern. Some are verbs (brief, recall, learn, prefer, fix), some are plural nouns used for retrieval (gotchas, conventions), some are singular nouns used for adding (gotcha, convention), and one is a compound (memory_bootstrap). This mix of conventions makes the naming unpredictable.

    Tool Count5/5

    With 10 tools, the set is well-scoped for a memory/knowledge server. Each tool covers a necessary function: adding knowledge (four types), retrieving it (three approaches), fixing entries, and bootstrapping a project. The count feels appropriate and not bloated.

    Completeness4/5

    The tool surface covers the full lifecycle of memory: create (gotcha, convention, learn, prefer), read (brief, recall, gotchas, conventions), update/delete (fix), and initialization (memory_bootstrap). The only minor gap is that there is no dedicated list tool for 'learn' or 'prefer' entries, but recall and brief surface them adequately.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Provides persistent, searchable memory and knowledge capture for AI-assisted development, enabling agents to retain decisions, bugs, and patterns across sessions and projects.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI coding agents to persist and retrieve durable project knowledge across coding sessions, capturing decisions, conventions, lessons and reusable skills through ordinary chat requests. It supports searching, editing and reviewing saved items, and promoting local notes into Git-shareable versioned knowledge alongside repository changes.
      205 npm
      1
      MIT