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:
# Pick an embedding provider; this example uses OpenAIpip install "memorylayer-server[openai]"export MEMORYLAYER_EMBEDDING_PROVIDER=openaiexport MEMORYLAYER_EMBEDDING_OPENAI_API_KEY=sk-...memorylayer serveThe 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-pluginpackage, which exposes the same MCP server and adapts the hooks to OpenCode’s lifecycle.
Installation
First, add the MemoryLayer marketplace, then install the plugin:
# Add the marketplace (one-time setup)claude plugin marketplace add scitrera/memorylayer
# Install the pluginclaude plugin install memorylayer@memorylayer.aiThis installs the MCP server, hooks, and slash commands in one step.
Manual Installation
If you prefer to install the plugin manually without the marketplace:
# Global plugins directorycp -r memorylayer-cc-plugin ~/.claude/plugins/memorylayer
# Or project-localcp -r memorylayer-cc-plugin .claude/plugins/memorylayerVerify Setup
Run the /memorylayer-setup slash command inside Claude Code. It performs a fully automated setup sequence:
- Check server — Runs
curl -sf http://localhost:61001/health. If unreachable, offers to install and start the server. - Auto-configure permissions — Reads
.claude/settings.local.jsonand mergesmcp__plugin_memorylayer_memorylayer__*into the permissions allow list. This eliminates per-tool permission prompts. - Verify MCP tools — Calls
memory_briefingto confirm tools are connected and the server is responding. - Smoke test — Stores a test memory, recalls it, then forgets it to verify the full read/write cycle.
- Verify hooks — Reads
~/.memorylayer/hook-state.jsonto confirm the SessionStart hook fired. - Status summary — Prints server URL, workspace, session, permission status, tool count, and active hooks.
You can also verify manually:
- Start Claude Code in your project
- Run
/mcpto check the server is connected - 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:
claude mcp add --transport stdio --scope user memorylayer \ -- npx @scitrera/memorylayer-mcp-serverOr 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:
- Read the conversation transcript from the JSONL file provided in the hook input
- 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
- Store each item via
memory_rememberwith appropriate type, subtype, importance, and tags - Call
memory_session_committo checkpoint working memory to long-term storage - Call
memory_context_checkpointto 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:
| Pattern | Examples |
|---|---|
| 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
| Command | Description |
|---|---|
/memorylayer-status | Check connection and workspace info |
/memorylayer-setup | Guided 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
| Level | When to Use | Examples |
|---|---|---|
| 0.9 | Critical decisions, breaking changes, user directives | “Always use PostgreSQL”, “Never modify the auth module” |
| 0.7-0.8 | Bug fixes, architecture decisions | “Fixed N+1 query in user list”, “Chose Redis for caching” |
| 0.5-0.6 | General knowledge, patterns | “Project uses ESLint”, “Tests use pytest fixtures” |
| 0.3-0.4 | Temporary 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 neededWorkspace 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:
MEMORYLAYER_WORKSPACE_IDenvironment variable (explicit override)- Git remote origin (extracts repo name from remote URL)
- Git root directory name
- Current working directory name
To override:
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):
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_URLenvironment variable - Port conflict: Try
MEMORYLAYER_PORT=61002 memorylayer serve
Hooks not firing
- Verify plugin is installed:
claude plugin list - Check hooks are loaded:
claude hooks list - 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_IDif 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:
export MEMORYLAYER_WORKSPACE_ID="my-custom-workspace"SessionStart hook state missing
Check that the hook state file exists:
cat ~/.memorylayer/hook-state.jsonIf the file doesn’t exist or has no sessionId, the hooks may not be configured. Verify the plugin is installed and restart the session.