集成与框架适配(3/6)
Persistent cross-session memory for Claude Code. Install once, memories are captured automatically and recalled in every future session.
Claude Code forgets everything between sessions. This plugin fixes that. Install it, work normally, and Claude remembers what happened across sessions.
Current plugin version: 0.3.1.
Prerequisites
- A Mem0 Platform account and API key (starts with
m0-): - Sign up at app.mem0.ai
-
A Claude Code version that supports plugin agents, worktree isolation for agents, and the
SubagentStart,SubagentStop, andPostToolUseFailurehook events. -
Python 3.10+ and Git on your machine.
Quick start
export MEM0_API_KEY='your-mem0-api-key'
claude plugin marketplace add mem0ai/mem0
claude plugin install mem0@mem0-plugins --scope user --config api_key="$MEM0_API_KEY"
unset MEM0_API_KEY
Restart Claude Code (or run /reload-plugins), open a Git repository, and work normally. That's it.
Managing the plugin
claude plugin marketplace update mem0-plugins # refresh the marketplace catalog
claude plugin update mem0@mem0-plugins --scope user # update the plugin (restart to apply)
claude plugin uninstall mem0@mem0-plugins # uninstall the plugin (keeps the marketplace)
What you can do
Automatic memory
Once installed, memory works without any action from you:
- Capture happens in the background as you work. Hooks save user messages, Claude's answers, changed files, and test/build results locally. Capture records evidence locally; memory extraction runs through Mem0 in a background worker.
- Recall happens automatically before Claude's first response in a new session. If the first prompt has at least 20 characters, the plugin searches with that prompt and injects up to five relevant memories. For shorter prompts or later questions, use explicit search.
Commands
| Command | What it does |
|---|---|
/mem0:search |
Search memories from earlier sessions. Supports --top-k <n>, --category <name>, --scope <repo\|dir\|mine>, and --run-id <session-id>. |
/mem0:status |
Check if memory is working: config, capture state, pending flushes, API key validity. |
/mem0:forget |
Delete your memories for this repo (shared project memory stays unless you pass --include-project-memory). |
/mem0:pause |
Pause memory capture. |
/mem0:resume |
Resume capture after a pause. |
/mem0:remember |
Tell Claude to capture something specific in its reply. |
Categories for --category: project_knowledge, decisions_and_constraints, workflows, problems_and_fixes, results. Without it, all categories are searched.
Search tool
After the automatic first-prompt search, Claude can also call search_memories with a specific question, and you can run /mem0:search yourself. Explicit searches return up to 3 results by default (configurable to 20). The combined search output is capped at 4,000 characters by default, configurable with max_context_chars. This recall limit does not truncate captured messages sent for extraction.
Sidekick agent
Sidekick is available only in Claude Code.
mem0:sidekick is a Sonnet coding agent that runs in a separate Git worktree. Use it to offload investigation, implementation, testing, or review without burning main-session context.
Ask Mem0's sidekick to investigate and implement this in its separate worktree.
Review its result and send any corrections back to the same sidekick.
Changes stay in the sidekick's worktree until the main agent reviews and copies them over. By default the worktree branches from the repo's default branch. Set worktree.baseRef to "head" in your Claude settings to branch from the current commit instead. Uncommitted changes are not copied into the sidekick's worktree.
At startup, Sidekick receives the memories already recalled for its parent session. It can also call the Mem0 search tool for its assigned task. Start and completion hooks track its work locally; completing a Sidekick task does not independently send a memory-extraction request. Sidekick returns its result, validation, and a local commit when it changes files, so the main agent can review the work before incorporating it.
How it works
The plugin follows a simple cycle: capture during a session, extract memories in the background, recall in the next session.
<img alt="Sequence diagram: the first user prompt triggers search, hooks capture activity during the session, a background worker extracts memories after every five exchanges or on idle/exit, and the next session recalls them." />
Step by step:
-
Capture. Hooks save the main agent's activity locally: user messages, Claude's answers, changed files, and short test/build results. Direct Sidekick lifecycle records stay local. Subagent results included in the main transcript can provide supporting evidence for extraction; the main agent's final response establishes the outcome. Capture does not call a model.
-
Flush. After every five completed exchanges, a detached background worker sends that batch to Mem0. Large exchanges flush sooner. Ending or compacting the session flushes anything remaining. If the session sits idle, an auto-flush runs after five minutes (configurable with
MEM0_CODE_IDLE_FLUSH_SECONDS). The timer resets on each new exchange. The worker survives Claude Code exiting. -
Extract. Each flush sends
addcalls withagent_id(the project identity),user_id(you),app_id(the repository), andrun_id(the session). Prompts and responses are redacted without a character cutoff. Large conversations are split across requests without dropping message text. Mem0 classifies each extracted memory as shared project knowledge or a personal preference. -
Recall. On the next session's first prompt, the plugin searches automatically and supplies up to five relevant memories. No model is called to write the query.
Memory scoping
Each add call carries separate extraction instructions for project facts and personal facts. Mem0 sorts each memory into one of two buckets:
-
Shared project memory (keyed by
agent_id, scoped byapp_id): one namespace per repository. Stores conventions, decisions, constraints, commands that work, and commands that failed with what fixed them. Everyone on the repo reads and writes the same pool. Project memory never carries auser_id, so teammates' searches never mix in your preferences. Directory information is stored in metadata for directory-scoped searches. -
Personal memory (keyed by
user_id, scoped byapp_id): your preferred tools, style, habits, and anything you asked to be remembered. Scoped to the repository byapp_id, private to you.
Credentials are redacted before anything leaves your machine.
<img alt="Venn diagram showing one add call producing shared project memory (agent_id, visible to team) and personal memory (user_id, private to you). Search returns the union of both." />
Search scope
Every memory carries identifiers showing where it came from:
| Identifier | What it is | Example |
|---|---|---|
user_id |
You (personal memory only) | Your Mem0 user ID |
agent_id |
The project identity (shared memory only) | acme-payments-api-<hash> |
app_id |
The repository (scopes both lanes) | acme-payments-api |
run_id |
The Claude Code session | The session ID |
New Git repository memories use an agent_id with a hash of the Git remote identity so matching owner/repository names on different hosts stay separate. Searches also include the previous unhashed agent_id, scoped by the repository's app_id, so existing shared memories remain available after upgrading. Those older memories retain their original namespace, which did not distinguish Git hosts. Local folders continue using a hash of their path.
Explicitly forgetting shared project memory with --include-project-memory covers both repository IDs. Without that option, shared memories are preserved.
A search returns the union of shared project memory and your personal preferences. The scope narrows the project part:
| Scope | What you get |
|---|---|
repo (default) |
All project memory across every subdirectory, plus your preferences |
dir |
Project memory from the directory you're in (and its children), plus your preferences |
mine |
Your personal preferences only |
The dir scope is hierarchical: a parent directory sees everything in its children, but a child never sees the parent's memories.
The search tool accepts an optional run_id with every scope (repo, dir, and mine); /mem0:search exposes it as --run-id session-id. It restricts both shared and personal results to memories saved in that coding-agent session. Omit it to search across sessions. This is a memory filter, not a label for the session making the request; automatically filtering by the current session would hide earlier-session memories. Each memory update still records the session's run_id. Set the default scope with the search_scope setting or MEM0_CODE_SEARCH_SCOPE env var.
Settings
| Setting | Default | What it controls |
|---|---|---|
api_key |
required | Mem0 Platform API key. |
user_id |
local account name | User ID for memory storage. Resolved from: setting, MEM0_CODE_USER_ID, MEM0_USER_ID, MEM0_RESOLVED_USER_ID, $USER, %USERNAME%, then default. Set explicitly to share memories across machines. |
top_k |
3 |
Max memories per explicit search (1 to 20). |
max_context_chars |
4000 |
Max characters returned per search (1,000 to 10,000). |
search_scope |
repo |
Default scope: repo, dir, or mine. Also read from MEM0_CODE_SEARCH_SCOPE. |
Upgrading from 0.2.x
Breaking update. Your memories carry over, most local config does not.
- Memories carry over. Same user and repository scoping, including
~/.mem0/project_map.json. - Env vars still work.
MEM0_API_KEY,MEM0_USER_ID,MEM0_PROJECT_ID. - Commands replaced. Old commands replaced by
/mem0:search,/mem0:status,/mem0:forget,/mem0:pause,/mem0:resume,/mem0:remember. - MCP server replaced. Nine read/write tools replaced by the single read-only
search_memoriestool. - Local config ignored.
~/.mem0/settings.jsonand per-projectmem0.mdfiles are no longer read. - Old memories remain searchable. Pre-upgrade memories may use different categories. Omit category filters if an older memory is missing from the results.
claude plugin marketplace update mem0-plugins
claude plugin update mem0@mem0-plugins --scope user
Troubleshooting
| Problem | Fix |
|---|---|
| Missing key | Reinstall with --config api_key="$MEM0_API_KEY" while the var is set. |
401 Unauthorized |
API key is invalid or expired. Run /mem0:status to confirm. |
| No memory after ending a session | Extraction runs in the background. Wait a moment, then search again. |
| Sidekick won't start | Must be in a Git repo. Check that your Claude Code version supports plugin agents and worktrees. |
| Remove the plugin | claude plugin uninstall mem0@mem0-plugins |
Telemetry
The plugin sends usage events (which hook ran, timing, result counts, failure types) so Mem0 can see what's used and what's breaking.
These events are not anonymous. When an API key is configured, which installing the plugin requires, they are sent under your Mem0 account email, the same way the Python SDK and the CLI attribute theirs. Without a key they are sent under a random per-machine id.
Each event carries the event name, the plugin version, the harness it ran in, your OS and Python version, and per-event properties describing what happened: timings, counts, coarse outcome and failure labels, and which model was configured. Repository and session identifiers are hashed with a random salt generated on your machine, so they cannot be linked back to a repository name or path.
The exact set is enforced in code rather than by this list: every property is filtered through a denylist of sensitive keys and credential-shaped values are redacted before anything is sent.
Prompts, memory text, queries, file paths, repository names, and API keys are never sent.
Turn it off:
export MEM0_TELEMETRY=false
Detailed MCP configuration for all clients
Add Mem0 memory to OpenAI Codex workflows
<Snippet />
Create voice-based conversational AI agents with ElevenLabs and Mem0 for context-aware voice interactions.
Create voice-based conversational AI agents with memory capabilities by integrating ElevenLabs and Mem0. This integration enables persistent, context-aware voice interactions that remember past conversations.
Overview
In this guide, we'll build a voice agent that:
- Uses ElevenLabs Conversational AI for voice interaction
- Leverages Mem0 to store and retrieve memories from past conversations
- Provides personalized responses based on user history
Setup and Configuration
Install necessary libraries:
pip install elevenlabs mem0ai python-dotenv
Configure your environment variables:
You'll need both an ElevenLabs API key and a Mem0 API key to use this integration.
# Create a .env file with these variables
AGENT_ID=your-agent-id
USER_ID=unique-user-identifier
ELEVENLABS_API_KEY=your-elevenlabs-api-key
MEM0_API_KEY=your-mem0-api-key
Integration Code Breakdown
Let's break down the implementation into manageable parts:
1. Imports and Environment Setup
First, we import required libraries and set up the environment:
import os
import signal
import sys
from mem0 import AsyncMemoryClient
from elevenlabs.client import ElevenLabs
from elevenlabs.conversational_ai.conversation import Conversation
from elevenlabs.conversational_ai.default_audio_interface import DefaultAudioInterface
from elevenlabs.conversational_ai.conversation import ClientTools
These imports provide:
- Standard Python libraries for system operations and signal handling
AsyncMemoryClientfrom Mem0 for memory operations- ElevenLabs components for voice interaction
2. Environment Variables and Validation
Next, we validate the required environment variables:
def main():
# Required environment variables
AGENT_ID = os.environ.get('AGENT_ID')
USER_ID = os.environ.get('USER_ID')
API_KEY = os.environ.get('ELEVENLABS_API_KEY')
MEM0_API_KEY = os.environ.get('MEM0_API_KEY')
# Validate required environment variables
if not AGENT_ID:
sys.stderr.write("AGENT_ID environment variable must be set\n")
sys.exit(1)
if not USER_ID:
sys.stderr.write("USER_ID environment variable must be set\n")
sys.exit(1)
if not API_KEY:
sys.stderr.write("ELEVENLABS_API_KEY not set, assuming the agent is public\n")
if not MEM0_API_KEY:
sys.stderr.write("MEM0_API_KEY environment variable must be set\n")
sys.exit(1)
# Set up Mem0 API key in the environment
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
This section:
- Retrieves required environment variables
- Performs validation to ensure required variables are present
- Exits the application with an error message if required variables are missing
- Sets the Mem0 API key in the environment for the Mem0 client to use
3. Client Initialization
Initialize both the ElevenLabs and Mem0 clients:
# Initialize ElevenLabs client
client = ElevenLabs(api_key=API_KEY)
# Initialize memory client and tools
client_tools = ClientTools()
mem0_client = AsyncMemoryClient()
Here we:
- Create an ElevenLabs client with the API key
- Initialize a ClientTools object for registering function tools
- Create an AsyncMemoryClient instance for Mem0 interactions
4. Memory Function Definitions
Define the two key memory functions that will be registered as tools:
# Define memory-related functions for the agent
async def add_memories(parameters):
"""Add a message to the memory store"""
message = parameters.get("message")
await mem0_client.add(
messages=message,
user_id=USER_ID
)
return "Memory added successfully"
async def retrieve_memories(parameters):
"""Retrieve relevant memories based on the input message"""
message = parameters.get("message")
# For Platform API, user_id goes in filters
filters = {"user_id": USER_ID}
# Search for relevant memories using the message as a query
results = await mem0_client.search(
query=message,
filters=filters
)
# Extract and join the memory texts
memories = ' '.join([result["memory"] for result in results.get('results', [])])
print("[ Memories ]", memories)
if memories:
return memories
return "No memories found"
These functions:
add_memories:
- Takes a message parameter containing information to remember
- Stores the message in Mem0 using the
addmethod - Associates the memory with the specific USER_ID
- Returns a success message to the agent
retrieve_memories:
- Takes a message parameter as the search query
- Sets up filters to only retrieve memories for the current user
- Uses semantic search to find relevant memories
- Joins all retrieved memories into a single text
- Prints retrieved memories to the console for debugging
- Returns the memories or a "No memories found" message if none are found
5. Registering Memory Functions as Tools
Register the memory functions with the ElevenLabs ClientTools system:
# Register the memory functions as tools for the agent
client_tools.register("addMemories", add_memories, is_async=True)
client_tools.register("retrieveMemories", retrieve_memories, is_async=True)
This allows the ElevenLabs agent to:
- Access these functions through function calling
- Wait for asynchronous results (is_async=True)
- Call these functions by name ("addMemories" and "retrieveMemories")
6. Conversation Setup
Configure the conversation with ElevenLabs:
# Initialize the conversation
conversation = Conversation(
client,
AGENT_ID,
# Assume auth is required when API_KEY is set
requires_auth=bool(API_KEY),
audio_interface=DefaultAudioInterface(),
client_tools=client_tools,
callback_agent_response=lambda response: print(f"Agent: {response}"),
callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
callback_user_transcript=lambda transcript: print(f"User: {transcript}"),
# callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),
)
This sets up the conversation with:
- The ElevenLabs client and Agent ID
- Authentication requirements based on API key presence
- DefaultAudioInterface for handling audio I/O
- The client_tools with our memory functions
- Callback functions for:
- Displaying agent responses
- Showing corrected responses (when the agent self-corrects)
- Displaying user transcripts for debugging
- (Commented out) Latency measurements
7. Conversation Management
Start and manage the conversation:
# Start the conversation
print(f"Starting conversation with user_id: {USER_ID}")
conversation.start_session()
# Handle Ctrl+C to gracefully end the session
signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session())
# Wait for the conversation to end and get the conversation ID
conversation_id = conversation.wait_for_session_end()
print(f"Conversation ID: {conversation_id}")
if __name__ == '__main__':
main()
This final section:
- Prints a message indicating the conversation has started
- Starts the conversation session
- Sets up a signal handler to gracefully end the session on Ctrl+C
- Waits for the session to end and gets the conversation ID
- Prints the conversation ID for reference
Memory Tools Overview
This integration provides two key memory functions to your conversational AI agent:
1. Adding Memories (addMemories)
The addMemories tool allows your agent to store important information during a conversation, including:
- User preferences
- Important facts shared by the user
- Decisions or commitments made during the conversation
- Action items to follow up on
When the agent identifies information worth remembering, it calls this function to store it in the Mem0 database with the appropriate user ID.
How it works:
- The agent identifies information that should be remembered
- It formats the information as a message string
- It calls the
addMemoriesfunction with this message - The function stores the memory in Mem0 linked to the user's ID
- Later conversations can retrieve this memory
Example usage in agent prompt:
When the user shares important information like preferences or personal details,
use the addMemories function to store this information for future reference.
2. Retrieving Memories (retrieveMemories)
The retrieveMemories tool allows your agent to search for and retrieve relevant memories from previous conversations. The agent can:
- Search for context related to the current topic
- Recall user preferences
- Remember previous interactions on similar topics
- Create continuity across multiple sessions
How it works:
- The agent needs context for the current conversation
- It calls
retrieveMemorieswith the current conversation topic or question - The function performs a semantic search in Mem0
- Relevant memories are returned to the agent
- The agent incorporates these memories into its response
Example usage in agent prompt:
At the beginning of each conversation turn, use retrieveMemories to check if we've
discussed this topic before or if the user has shared relevant preferences.
Configuring Your ElevenLabs Agent
To enable your agent to effectively use memory:
- Add function calling capabilities to your agent in the ElevenLabs platform:
- Go to your agent settings in the ElevenLabs platform
- Navigate to the "Tools" section
- Enable function calling for your agent
-
Add the memory tools as described below
-
Add the
addMemoriesandretrieveMemoriestools to your agent with these specifications:
For addMemories:
{
"name": "addMemories",
"description": "Stores important information from the conversation to remember for future interactions",
"parameters": {
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The important information to remember"
}
},
"required": ["message"]
}
}
For retrieveMemories:
{
"name": "retrieveMemories",
"description": "Retrieves relevant information from past conversations",
"parameters": {
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The query to search for in past memories"
}
},
"required": ["message"]
}
}
- Update your agent's prompt to instruct it to use these memory functions. For example:
You are a helpful voice assistant that remembers past conversations with the user.
You have access to memory tools that allow you to remember important information:
- Use retrieveMemories at the beginning of the conversation to recall relevant context from prior conversations
- Use addMemories to store new important information such as:
* User preferences
* Personal details the user shares
* Important decisions made
* Tasks or follow-ups promised to the user
Before responding to complex questions, always check for relevant memories first.
When the user shares important information, make sure to store it for future reference.
Example Conversation Flow
Here's how a typical conversation with memory might flow:
-
User speaks: "Hi, do you remember my favorite color?"
-
Agent retrieves memories:
# Agent calls retrieve_memories
memories = retrieve_memories({"message": "user's favorite color"})
# If found: "The user's favorite color is blue"
- Agent processes with context:
- If memories found: Prepares a personalized response
-
If no memories: Prepares to ask and store the information
-
Agent responds:
- With memory: "Yes, your favorite color is blue!"
-
Without memory: "I don't think you've told me your favorite color before. What is it?"
-
User responds: "It's actually green."
-
Agent stores new information:
# Agent calls add_memories
add_memories({"message": "The user's favorite color is green"})
- Agent confirms: "Thanks, I'll remember that your favorite color is green."
Example Use Cases
- Personal Assistant - Remember user preferences, past requests, and important dates
User: "What restaurants did I say I liked last time?"
Agent: *retrieves memories* "You mentioned enjoying Bella Italia and The Golden Dragon."
- Customer Support - Recall previous issues a customer has had
User: "I'm having that same problem again!"
Agent: *retrieves memories* "Is this related to the login issue you reported last week?"
- Educational AI - Track student progress and tailor teaching accordingly
User: "Let's continue our math lesson."
Agent: *retrieves memories* "Last time we were working on quadratic equations. Would you like to continue with that?"
- Healthcare Assistant - Remember symptoms, medications, and health concerns
User: "Have I told you about my allergy medication?"
Agent: *retrieves memories* "Yes, you mentioned you're taking Claritin for your pollen allergies."
Troubleshooting
- Missing API Keys:
- Error: "API_KEY environment variable must be set"
-
Solution: Ensure all environment variables are set correctly in your .env file or system environment
-
Connection Issues:
- Error: "Failed to connect to API"
-
Solution: Check your network connection and API key permissions. Verify the API keys are valid and have the necessary permissions.
-
Empty Memory Results:
- Symptom: Agent always responds with "No memories found"
-
Solution: This is normal for new users. The memory database builds up over time as conversations occur. It's also possible your query isn't semantically similar to stored memories - try different phrasing.
-
Agent Not Using Memories:
- Symptom: The agent retrieves memories but doesn't incorporate them in responses
- Solution: Update the agent's prompt to explicitly instruct it to use the retrieved memories in its responses
Conclusion
By integrating ElevenLabs Conversational AI with Mem0, you can create voice agents that maintain context across conversations and provide personalized responses based on user history. This powerful combination enables:
- More natural, context-aware conversations
- Personalized user experiences that improve over time
- Reduced need for users to repeat information
-
Long-term relationship building between users and AI agents
Build real-time voice and video agents
Create voice-first AI applications
<Snippet />
