Skip to content

Claude Code Integration

The MemoryLayer plugin for Claude Code gives Claude persistent memory that survives context-window compaction. It adds session context at startup, recall that is aware of what you’re working on, and durable capture of the raw transcript before compaction.

What It Does

  • Pre-compaction transcript capture: Before Claude Code compacts the context window, the plugin durably uploads the new raw transcript bytes to MemoryLayer, then commits working memory and checkpoints sandbox state
  • Session context packs: Loads one bounded, deterministic context pack (directives, working memory, recent activity, contradictions, checkpoint recovery) when a session starts
  • Contextual recall: Injects relevant memories before edits, writes, and subagent tasks, and when your prompt asks about conventions, past decisions, reviews, implementation, or errors
  • Observation capture: Records outcomes such as commits, file changes, and agent results as working memory
  • Context sandbox: A server-side Python sandbox that persists through compaction

Prerequisites

The plugin needs a running MemoryLayer server:

Terminal window
pip install memorylayer-server
memorylayer serve

The server runs on http://localhost:61001 by default. Out of the box it uses a dependency-free lexical hash embedder so it works with no API keys. For real semantic recall, configure an embedding provider (for example pip install "memorylayer-server[openai]" with MEMORYLAYER_EMBEDDING_PROVIDER=openai, or a self-hosted memorylayer-embed-server). See Configuration.

Using OpenCode or Codex instead of Claude Code? See the OpenCode and Codex integrations, which use the same MCP server.

Installation

First, add the MemoryLayer marketplace, then install the plugin:

Terminal window
# Add the marketplace (one-time setup)
claude plugin marketplace add scitrera/memorylayer
# Install the plugin
claude plugin install memorylayer@memorylayer.ai

This registers the MCP server, hooks, slash commands, and setup skill in one step.

Install the command-line tools

The plugin’s MCP configuration runs the memorylayer-mcp command, and its hooks run the memorylayer-hook command. Both must be on your PATH:

Terminal window
npm install -g @scitrera/memorylayer-mcp-server @scitrera/memorylayer-cc-plugin

@scitrera/memorylayer-mcp-server provides memorylayer-mcp, and @scitrera/memorylayer-cc-plugin provides memorylayer-hook. Both require Node.js 18 or later.

Install from a local checkout

To install from a clone of the repository instead of GitHub, add the checkout as a local marketplace:

Terminal window
git clone https://github.com/scitrera/memorylayer.git
claude plugin marketplace add ./memorylayer
claude plugin install memorylayer@memorylayer.ai

Configuration

The plugin reads these environment variables and passes them to the MCP server:

Terminal window
# Server URL (default: http://localhost:61001)
export MEMORYLAYER_URL="http://your-server:61001"
# Optional API key for secured deployments
export MEMORYLAYER_API_KEY="ml_..."
# Workspace override (default: auto-detected from the git repo)
export MEMORYLAYER_WORKSPACE_ID="my-project"

Verify Setup

Run /memorylayer:setup inside Claude Code. It runs an automated setup sequence:

  1. Check server: Runs curl -sf http://localhost:61001/health. If the server is unreachable, it offers to install and start it.
  2. Configure permissions: Reads .claude/settings.local.json and adds mcp__plugin_memorylayer_memorylayer__* to the permissions allow list, so you aren’t prompted for every tool call.
  3. Verify MCP tools: Calls memory_briefing to confirm the tools are connected and the server responds.
  4. Smoke test: Stores a test memory, recalls it, and forgets it to check the full read/write cycle.
  5. Verify hooks: Reads ~/.memorylayer/hook-state.json to confirm the SessionStart hook fired.
  6. Status summary: Prints the server URL, workspace, session, permission status, tool count, and active hooks.

You can also verify manually:

  1. Start Claude Code in your project
  2. Run /mcp to check the server is connected
  3. Ask Claude to remember something: “Remember that this project uses SQLite”

Manual MCP Setup (Alternative)

To configure only the MCP server, without the plugin’s hooks and slash commands:

Terminal window
claude mcp add --transport stdio --scope user memorylayer \
-- npx @scitrera/memorylayer-mcp-server

Or add .mcp.json to your project root:

{
"mcpServers": {
"memorylayer": {
"command": "npx",
"args": ["@scitrera/memorylayer-mcp-server"],
"env": {
"MEMORYLAYER_URL": "http://localhost:61001"
}
}
}
}

Without the plugin there is no automatic pre-compaction capture. See MCP Server for all options.

What the Plugin Provides

Hooks

The plugin’s hooks fire automatically at key points in the Claude Code lifecycle. They are defined in the plugin’s hooks/hooks.json, run as command hooks (memorylayer-hook <Event>), and need no manual configuration.

PreCompact (Before Context Compaction)

Matcher: * (fires on every compaction)

This is the most important hook. Before the context window is compacted, it:

  1. Captures the raw transcript. It reads the transcript file Claude Code provides and uploads only the bytes after the last acknowledged boundary, as idempotent raw checkpoints (memory_session_checkpoint semantics: SHA-256 content hash plus a stable idempotency key, chunked at UTF-8 boundaries). Because the capture is raw, nothing depends on an LLM deciding what to keep, and derived indexing never blocks it.
  2. Commits working memory to long-term storage.
  3. Checkpoints sandbox state if a context environment is active.

Each step retries a bounded number of times. Failures are logged but never block compaction. On the next session start, the context pack’s checkpoint-recovery section can bring the captured material back.

SessionStart (Session Begins)

Matcher: *

When a Claude Code session begins, this hook:

  • Starts a server-side session for workspace resolution and working memory tracking
  • Loads one bounded context pack (about 2,048 tokens) and adds it to the session together with a context cursor
  • On servers without context packs, falls back to a briefing, a directives/preferences recall, and sandbox state

Stop (Session Ends)

Matcher: *

When the session ends, this hook commits working memory to long-term storage and ends the server session.

PreToolUse (Before Tool Execution)

Matchers: Task, Edit|Write

Fires before Task, Edit, and Write tool calls and injects recalled context relevant to the operation. It uses query-aware deduplication so it doesn’t repeat context the conversation already has.

PostToolUse (After Tool Execution)

Matchers: Bash, Edit|Write, Task, Read|Glob|Grep

Fires after tool calls complete and captures outcomes, including:

  • Git commit summaries (after Bash commands)
  • File changes and new file creation (after Edit/Write)
  • Agent results (after Task)
  • File reading activity (after Read/Glob/Grep)

UserPromptSubmit (On User Input)

Fires when you submit a prompt. The hook recalls memories only when the prompt matches one of these pattern groups:

PatternExamples
Convention/preference queries“which framework should we use”, “what’s our preferred…”
Recall/memory queries“remember”, “recall”, “what did we…”, “remind me”
Review/analysis tasks“review”, “assess”, “analyze”, “evaluate”, “gap analysis”
Implementation tasks“implement”, “build”, “create”, “add”, “fix”, “refactor”
Error/debugging tasks“error”, “bug”, “issue”, “broken”, “failing”, “crash”

Slash Commands

Claude Code namespaces plugin commands with the plugin name:

CommandDescription
/memorylayer:statusCheck connection and workspace info
/memorylayer:setupGuided setup and troubleshooting
/memorylayer:remember <content>Quick memory storage
/memorylayer:recall <query>Quick memory search

The Memory Protocol for CLAUDE.md

Add these instructions to your project’s CLAUDE.md to teach Claude to use memory proactively:

## Memory Protocol
You have MemoryLayer MCP tools. Use them proactively:
**Session Start**: The plugin injects a context pack. Call `memory_recall` for the current task when you need more.
**Auto-Store** (without being asked):
- Bug fixes → problem + solution (type: "semantic", subtype: "fix", importance: 0.8)
- Architecture decisions → decision + rationale (type: "semantic", subtype: "decision", importance: 0.9)
- User directives → "always do X", "never do Y" (type: "semantic", subtype: "directive", importance: 0.9)
- Patterns discovered → pattern + when to use (type: "procedural", subtype: "code_pattern", importance: 0.7)
- Current task state → progress and context (type: "working", importance: 0.6)
**Memory Types**:
- episodic: Events, what happened
- semantic: Facts, concepts, knowledge
- procedural: How-to, solutions, patterns
- working: Current task context (auto-expires)
**Tags**: Always include component names and technologies.
**After compaction**: Call `memory_context_inspect` to re-orient with existing sandbox state.

Importance Levels Guide

LevelWhen to UseExamples
0.9Critical decisions, breaking changes, user directives“Always use PostgreSQL”, “Never modify the auth module”
0.7-0.8Bug fixes, architecture decisions“Fixed N+1 query in user list”, “Chose Redis for caching”
0.5-0.6General knowledge, patterns“Project uses ESLint”, “Tests use pytest fixtures”
0.3-0.4Temporary notes, minor context“Currently debugging the login flow”

Context Compaction Protection

Without MemoryLayer, Claude loses everything that gets truncated when the context window fills up. With the plugin installed, the PreCompact hook stores the exact new transcript segment before compaction. You don’t need to configure anything.

Without MemoryLayer:
[Long conversation] → context full → COMPACTION → Claude forgets everything
With MemoryLayer:
[Long conversation] → context full → PreCompact hook fires
→ new raw transcript bytes checkpointed to MemoryLayer
→ working memory committed, sandbox checkpointed
→ COMPACTION → next context pack and recall can restore what matters

Workspace Isolation

Each project automatically gets its own workspace, based on your git repository or directory name, so memories are isolated per project by default. The detection order is:

  1. MEMORYLAYER_WORKSPACE_ID environment variable (explicit override)
  2. Git remote origin (the repo name from the remote URL)
  3. Git root directory name
  4. Current working directory name

To override:

Terminal window
export MEMORYLAYER_WORKSPACE_ID="my-custom-workspace"

Permission Configuration

/memorylayer:setup configures permissions for you. To configure them manually:

Project-local (.claude/settings.local.json):

{
"permissions": {
"allow": [
"mcp__plugin_memorylayer_memorylayer__*"
]
}
}

Per-session (CLI flag):

Terminal window
claude --allowedTools "mcp__plugin_memorylayer_memorylayer__*"

Available Tools

Once connected, Claude Code can use the MemoryLayer MCP tools from the default cc profile (28 tools). Set MEMORYLAYER_TOOL_PROFILE=full for all 40. See MCP Server for the complete tool reference.

Troubleshooting

“Connection refused” errors

  • The server isn’t running: start it with memorylayer serve
  • Wrong URL: check the MEMORYLAYER_URL environment variable
  • Port conflict: run the server on another port with memorylayer serve --port 61002 (or MEMORYLAYER_SERVER_PORT=61002), then set MEMORYLAYER_URL=http://localhost:61002

MCP server or hooks fail to start

  • Check that memorylayer-mcp and memorylayer-hook are on your PATH (which memorylayer-mcp memorylayer-hook). If not, run npm install -g @scitrera/memorylayer-mcp-server @scitrera/memorylayer-cc-plugin.

Hooks not firing

  1. Run /plugin in Claude Code and check that memorylayer is installed and enabled
  2. Run /hooks to see the loaded hooks
  3. Restart the Claude Code session after installing the plugin

Permission prompts on every tool call

Run /memorylayer:setup to configure permissions automatically, or add mcp__plugin_memorylayer_memorylayer__* to your settings by hand (see Permission Configuration above).

Workspace not found

  • Workspaces are auto-created on first use
  • Check the workspace name with memory_briefing
  • Override with MEMORYLAYER_WORKSPACE_ID if needed

Memories not persisting

  • Check the server logs for errors (run memorylayer serve in the foreground)
  • Check that the storage path is writable
  • Check disk space

SessionStart hook state missing

Check that the hook state file exists:

Terminal window
cat ~/.memorylayer/hook-state.json

If the file is missing or has no sessionId, the hooks may not be configured. Check that the plugin is installed, then restart the session.