Skip to content

Claude Code Integration

The MemoryLayer plugin for Claude Code provides persistent memory that survives context window compaction, session briefings, and automatic memory triggers.

What It Does

  • PreCompact Memory Capture — Automatically saves important information before context window compaction
  • Session Briefings — Recalls relevant context at session start
  • Automatic Memory Triggers — Suggests storing memories after git commits and significant events
  • Knowledge Graph — Links related memories with typed relationships
  • Context Sandbox — Server-side Python sandbox that persists through compaction

Prerequisites

The plugin requires a running MemoryLayer server:

Terminal window
# Pick an embedding provider; this example uses OpenAI
pip install "memorylayer-server[openai]"
export MEMORYLAYER_EMBEDDING_PROVIDER=openai
export MEMORYLAYER_EMBEDDING_OPENAI_API_KEY=sk-...
memorylayer serve

The server runs on http://localhost:61001 by default. See Configuration for embedding and LLM provider setup (cloud, self-hosted via memorylayer-embed-server, or mock for testing).

Using OpenCode instead of Claude Code? The same workflow is available via the @scitrera/memorylayer-opencode-plugin package, which exposes the same MCP server and adapts the hooks to OpenCode’s lifecycle.

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 installs the MCP server, hooks, and slash commands in one step.

Manual Installation

If you prefer to install the plugin manually without the marketplace:

Terminal window
# Global plugins directory
cp -r memorylayer-cc-plugin ~/.claude/plugins/memorylayer
# Or project-local
cp -r memorylayer-cc-plugin .claude/plugins/memorylayer

Verify Setup

Run the /memorylayer-setup slash command inside Claude Code. It performs a fully automated setup sequence:

  1. Check server — Runs curl -sf http://localhost:61001/health. If unreachable, offers to install and start the server.
  2. Auto-configure permissions — Reads .claude/settings.local.json and merges mcp__plugin_memorylayer_memorylayer__* into the permissions allow list. This eliminates per-tool permission prompts.
  3. Verify MCP tools — Calls memory_briefing to confirm tools are connected and the server is responding.
  4. Smoke test — Stores a test memory, recalls it, then forgets it to verify the full read/write cycle.
  5. Verify hooks — Reads ~/.memorylayer/hook-state.json to confirm the SessionStart hook fired.
  6. Status summary — Prints 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)

If you prefer to configure just 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"
}
}
}
}

What the Plugin Provides

Hooks

The plugin includes hooks that fire automatically at key moments in the Claude Code lifecycle. These hooks are defined in the plugin’s hooks.json and require no manual configuration.

PreCompact (Before Context Compaction)

Matcher: * (fires on every compaction event) Type: Agent hook (uses claude-sonnet-4-5, 60-second timeout)

This is the most critical hook. When the context window fills up, Claude normally forgets everything that gets truncated. The PreCompact hook fires automatically before compaction to:

  1. Read the conversation transcript from the JSONL file provided in the hook input
  2. Identify important information by priority:
    • Critical (importance 0.9): User directives and instructions (“always do X”, “never do Y”)
    • High (importance 0.7-0.8): Decisions with rationale, problem/solution pairs, current task state
    • Normal (importance 0.5-0.6): Discovered patterns, actively worked files
  3. Store each item via memory_remember with appropriate type, subtype, importance, and tags
  4. Call memory_session_commit to checkpoint working memory to long-term storage
  5. Call memory_context_checkpoint to persist sandbox state if a context environment session is active

SessionStart (Session Begins)

Matcher: * (fires on every session start) Type: Command hook (memorylayer-hook SessionStart, 10-second timeout)

Runs when a Claude Code session begins. It:

  • Loads context briefing with recent memories and workspace stats
  • Loads any stored directives
  • Starts a server-side session for workspace resolution and working memory tracking

Stop (Session Ends)

Matcher: * (fires on every session end) Type: Command hook (memorylayer-hook Stop, 5-second timeout)

Runs when a session ends. It:

  • Commits working memory to long-term storage
  • Ends the server session

PreToolUse (Before Tool Execution)

Matchers: Task, Edit|Write Type: Command hook (memorylayer-hook PreToolUse, 8-second timeout)

Fires before Task, Edit, and Write tool calls. Injects recalled context relevant to the operation being performed. Uses query-aware deduplication to avoid repeating context already present in the conversation.

PostToolUse (After Tool Execution)

Matchers: Bash, Edit|Write, Task, Read|Glob|Grep Type: Command hook (memorylayer-hook PostToolUse, 5-second timeout)

Fires after tool calls complete. 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)

Type: Command hook (memorylayer-hook UserPromptSubmit, 8-second timeout)

Fires when the user submits a prompt, but only when the prompt matches specific patterns. Each pattern group triggers memory recall relevant to the user’s intent:

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

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 how to use memory proactively:

## Memory Protocol
You have MemoryLayer MCP tools. Use them proactively:
**Session Start**: Call `memory_briefing` for context, then `memory_recall` for the current task.
**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, when the context window fills up, Claude forgets everything that gets truncated. With the plugin installed, the PreCompact hook fires automatically before compaction to store important information — no manual configuration needed.

Without MemoryLayer:
[Long conversation] → context full → COMPACTION → Claude forgets everything
With MemoryLayer:
[Long conversation] → context full → PreCompact hook fires
→ Claude stores key information to MemoryLayer
→ COMPACTION → Claude can recall stored memories when needed

Workspace Isolation

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

  1. MEMORYLAYER_WORKSPACE_ID environment variable (explicit override)
  2. Git remote origin (extracts repo name from 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

The /memorylayer-setup command automatically configures permissions. If you need to configure them manually:

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

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

Global (~/.claude.json):

{
"projects": {
"/path/to/your/project": {
"allowedTools": ["mcp__plugin_memorylayer_memorylayer__*"]
}
}
}

Per-session (CLI flag):

Terminal window
claude --allowedTools "mcp__plugin_memorylayer_memorylayer__*"

Available Tools

Once connected, Claude Code will have access to all MemoryLayer MCP tools. See the MCP Server Integration for the complete tool reference.

Troubleshooting

“Connection refused” errors

  • Server not running: memorylayer serve
  • Wrong URL: Check MEMORYLAYER_URL environment variable
  • Port conflict: Try MEMORYLAYER_PORT=61002 memorylayer serve

Hooks not firing

  1. Verify plugin is installed: claude plugin list
  2. Check hooks are loaded: claude hooks list
  3. Restart Claude Code session after plugin installation

Permission prompts on every tool call

Run /memorylayer-setup to auto-configure permissions, or manually add mcp__plugin_memorylayer_memorylayer__* to your settings (see Permission Configuration above).

Workspace not found

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

Memories not persisting

  • Check server logs for errors: memorylayer serve (foreground mode)
  • Verify storage path is writable
  • Check disk space

Wrong workspace

The workspace is auto-detected from the git repo or directory name. To override:

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

SessionStart hook state missing

Check that the hook state file exists:

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

If the file doesn’t exist or has no sessionId, the hooks may not be configured. Verify the plugin is installed and restart the session.