Skip to main content
doc0blade47/mem0documentation home
Sign in

Overview

Last updated Oct 11, 2026100% grounded
Relevant source files

The following files were used as context for generating this wiki page:

Overview

Mem0 provides an extensible memory infrastructure and agent runtime integration suite designed to equip AI agents and applications with persistent context across dual deployment tiers: open-source (OSS) local backends and the hosted Mem0 Platform. At its core, the architecture coordinates cross-runtime command-line interfaces in both Python and Node.js Python CLI Architecture, Node.js CLI Architecture, alongside a unified family of agent harness plugins such as Claude Code Plugin that synchronize conversation history, background session flows, and diagnostic telemetry.

Platform Architecture and Core Concepts

Core Components and Client Entrypoints

Mem0 defines its foundational memory layers and client entrypoints across dedicated package modules. The core package exposes synchronous and asynchronous interfaces for both local engine management via Memory and AsyncMemory, alongside hosted cloud interactions through MemoryClient and AsyncMemoryClient.

Component / ClassModule PathPurpose
Memorymem0.memory.mainSynchronous core memory engine for local management
AsyncMemorymem0.memory.mainAsynchronous core memory engine
MemoryClientmem0.client.mainSynchronous client interface for the Mem0 platform
AsyncMemoryClientmem0.client.mainAsynchronous client interface for the Mem0 platform

Sources: mem0/init.py:5-6

Deployment Tiers and Versioning

The architecture operates across dual deployment tiers: open-source self-hosted backends and remote platform synchronization. Package versioning is dynamically retrieved via metadata for the underlying distribution (mem0ai), while command-line operations are governed by the dedicated CLI distribution version.

"""mem0 CLI — the command-line interface for the mem0 memory layer."""
 
__version__ = "0.2.13"

Sources: cli/python/src/mem0_cli/init.py:1-3, mem0/init.py:1-3

Note

The Python core package inspects installed distribution metadata via importlib.metadata.version("mem0ai") to populate __version__, distinguishing the core library version from the mem0-cli package distribution version (0.2.13). Sources: cli/python/src/mem0_cli/init.py:3-3, mem0/init.py:3-3

Unified CLI Specification and Dual-Runtime Interfaces

CLI Schema and Branding Specifications

Mem0 unifies its command-line interfaces through a cross-runtime JSON specification file (cli/cli-spec.json) that establishes metadata, brand assets, configuration directories, and remote API endpoints for both Python and Node client entrypoints. The specification defines global branding identifiers, color palettes, and operational icons used to render terminal output consistently across runtime boundaries.

Branding PropertyKey / ValuePurpose
namemem0CLI application command name
version0.1.0CLI specification version
logoMini◆ mem0Compact CLI banner logo
brand#8b5cf6Primary brand color hex code
accent#a78bfaAccent color hex code
success#22c55eSuccess indicator color
error#ef4444Error indicator color
warning#f59e0bWarning indicator color
dim#6b7280Dimmed text color

Sources: cli/cli-spec.json:1-34

Note

The cross-runtime specification centralizes icon characters such as success (✓), error (✗), warning (⚠), info (◆), pending (⧗), add (+), update (~), delete (-), noop (·), connected (●), and disconnected (●) to ensure identical terminal rendering across Python and Node.js wrapper implementations. Sources: cli/cli-spec.json:20-32

Configuration Schema and Environment Bindings

Client configuration is structured around local directory storage combined with environment variable overrides. The configuration subsystem maps platform settings and default identifiers to specific environment variables, allowing seamless authentication and scoping for autonomous agents and developer workstations.

Config SectionField NameTypeDefault ValueEnvironment VariableRedact
platformapi_keystring""MEM0_API_KEYtrue
platformbase_urlstringhttps://api.mem0.aiMEM0_BASE_URL—
defaultsuser_idstring""MEM0_USER_ID—
defaultsagent_idstring""MEM0_AGENT_ID—
defaultsapp_idstring""MEM0_APP_ID—
defaultsrun_idstring""MEM0_RUN_ID—
defaultsenable_graphbooleanfalseMEM0_ENABLE_GRAPH—

Sources: cli/cli-spec.json:35-86

Warning

The api_key field enforces credential redaction (redact: true) within logs and configuration dumps, preventing sensitive tokens from leaking into terminal outputs or diagnostic telemetry. Sources: cli/cli-spec.json:43-48

REST Endpoint Mappings

The CLI specification maps remote control actions to standardized REST API endpoints, defining HTTP methods, path patterns, authentication headers, and entity type mappings for remote synchronization Python Client SDK.

Operation NameHTTP MethodAPI Path Pattern
addPOST/v1/memories/
searchPOST/v2/memories/search/
getGET/v1/memories/{memory_id}/
listPOST/v2/memories/
updatePUT/v1/memories/{memory_id}/
deleteDELETE/v1/memories/{memory_id}/
deleteAllDELETE/v1/memories/
entitiesGET/v1/entities/
deleteEntitiesDELETE/v1/entities/

Sources: cli/cli-spec.json:87-98

Tip

All REST requests enforce an authentication scheme using the Authorization header prefixed with the Token scheme, operating with a default network timeout of 30 seconds. Sources: cli/cli-spec.json:99-101

Agent Harness Architecture and Plugins Family

Shared Core and Harness Configuration

The Mem0 agent plugin family relies on a shared core implementation (memory_core.py) that handles session event recording, background flushing, redacting sensitive secrets, and local storage operations across diverse IDE harnesses and coding assistants. Plugins configure their runtime environment using configure_harness(), which sets up harness-specific naming prefixes, data directories, and source tags for telemetry tracking.

Harness ParameterDefault ValuePurpose
namegenericIdentifier for the active coding assistant harness
env_prefixMEM0_PLUGINEnvironment variable prefix for configuration overrides
data_dir_namemem0-pluginDirectory name for local evidence and state storage
source_tagmem0_pluginTelemetry source tag identifying the originating plugin

Sources: integrations/mem0-agent-plugin/core/memory_core.py:34-38, integrations/antigravity-plugin/core/memory_core.py:34-38, integrations/kimi-plugin/core/memory_core.py:34-38, integrations/cursor-plugin/core/memory_core.py:34-38, integrations/codex-plugin/core/memory_core.py:34-38

Note

The shared core defines strict operational boundaries including command, result, and episode character limits, extraction input token caps, and a maximum of 5 flush attempts for offline retry queues. Sources: integrations/mem0-agent-plugin/core/memory_core.py, integrations/antigravity-plugin/core/memory_core.py, integrations/kimi-plugin/core/memory_core.py, integrations/cursor-plugin/core/memory_core.py, integrations/codex-plugin/core/memory_core.py

Diagnostic CLI and Control Operations

Each IDE plugin embeds a command-line interface (memory_cli.py) that exposes diagnostic checks, user controls, and lifecycle actions for managing local and remote memories. The CLI uses Python's argparse module to dispatch subcommands such as status inspection, health diagnostics, pausing, resuming, and repository purging.

CLI SubcommandArguments / FlagsAction Performed
status--jsonPrints operational summary, repo ID, local data path, and API key status
doctor--jsonRuns diagnostic checks against the current workspace and environment
pause—Stops saving and searching memories locally
resume—Resumes saving and searching memories locally
forget--remote, --yes, --include-project-memoryDeletes local repository evidence and optionally purges remote scopes

Sources: integrations/mem0-agent-plugin/core/memory_cli.py:61-80, integrations/antigravity-plugin/core/memory_cli.py:61-80, integrations/kimi-plugin/core/memory_cli.py:61-80, integrations/cursor-plugin/core/memory_cli.py:61-80, integrations/codex-plugin/core/memory_cli.py:61-80

Warning

The forget command enforces a safety check requiring the --yes flag; without it, the command refuses to delete data and exits with code 2. Sources: integrations/mem0-agent-plugin/core/memory_cli.py, integrations/antigravity-plugin/core/memory_cli.py, integrations/kimi-plugin/core/memory_cli.py, integrations/cursor-plugin/core/memory_cli.py, integrations/codex-plugin/core/memory_cli.py

MCP Server Integration and Manifests

Model Context Protocol (MCP) manifests (mcp.json) bind the memory core into host IDE environments using standard input/output transport streams. The manifest defines server registration parameters that execute the Python MCP server script within the plugin root directory.

{
  "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
  "mcpServers": {
    "mem0": {
      "type": "stdio",
      "command": "python3",
      "args": [
        "${PLUGIN_ROOT}/core/mcp_server.py"
      ]
    }
  }
}

Sources: integrations/mem0-agent-plugin/mcp.json:1-12

External Agent and Workflow Ecosystem

OpenClaw and Pi Agent Integrations

Mem0 extends beyond core LLM memory engines by providing specialized integrations for agent frameworks, runtime environments, and workflow automation tools. These packages bridge external architectures into the Mem0 memory fabric without requiring custom storage layers.

The OpenClaw Integration plugin (openclaw-mem0) exposes six core memory tools (memory_search, memory_add, memory_get, memory_list, memory_update, and memory_delete) while handling automatic recall and capture across agent turns. It isolates multi-agent setups by routing per-agent namespaces through session key resolution and supports both platform and self-hosted backends. Similarly, the Pi Agent Plugin package structures memory management through exported configuration loaders, scoping handlers, formatting utilities, and command extensions.

/**
 * OpenClaw Memory (Mem0) Plugin
 *
 * Long-term memory via Mem0 — supports both the Mem0 platform
 * and the open-source self-hosted SDK. Uses the official `mem0ai` package.
 *
 * Features:
 * - 6 core tools: memory_search, memory_add, memory_get, memory_list,
 *   memory_update, memory_delete
 * - Short-term (session-scoped) and long-term (user-scoped) memory
 * - Auto-recall: injects relevant memories (both scopes) before each agent turn
 * - Auto-capture: stores key facts scoped to the current session after each agent turn
 * - Per-agent isolation: multi-agent setups write/read from separate userId namespaces
 *   automatically via sessionKey routing (zero breaking changes for single-agent setups)
 * - CLI: openclaw mem0 search, openclaw mem0 status
 * - Dual mode: platform or open-source (self-hosted)
 */

Sources: integrations/openclaw/index.ts:1-17

export type {
  Scope,
  Mem0Config,
  ScopeContext,
  CustomCategory,
} from "./types.ts";
export { DEFAULT_CUSTOM_CATEGORIES } from "./types.ts";
 
export { loadConfig, CONFIG_DIR } from "./config/index.ts";
 
export { registerMemoryTool, buildToolExecute } from "./memory/tools.ts";
export { detectAppId, detectRunId, resolveSearchFilters, resolveAddParams } from "./memory/scoping.ts";
export { formatAge, formatMemoryCompact, formatMemoryList, groupByCategory } from "./memory/formatting.ts";
 
export { setupAutoCapture, extractConversation } from "./capture/index.ts";
 
export { MEMORY_POLICY } from "./prompt.ts";
 
export { registerCommands } from "./commands.ts";
 
export { captureEvent, captureToolEvent, captureCommandEvent, _getEventQueue, _resetForTesting } from "./telemetry.ts";
 

Sources: integrations/pi-agent-plugin/src/index.ts:1-22

Note

The OpenClaw plugin reads authentication settings dynamically from openclaw.json plugin config via readPluginAuth(), accommodating post-startup login commands (openclaw mem0 login) as the single source of truth. Sources: integrations/openclaw/index.ts:98-104

Strands Agent Framework Integration

The Mem0 Strands package (mem0-strands) provides persistent long-term memory for Strands agents via Mem0MemoryStore. It plugs into agent execution loops through a MemoryManager to deliver automatic memory injection and extraction.

"""Strands Mem0 -- persistent long-term memory for Strands agents, backed by Mem0.
 
:class:`Mem0MemoryStore` is a Strands ``MemoryStore`` that plugs into the agent
loop via a :class:`~strands.memory.MemoryManager`, with automatic memory injection
and extraction. It implements both write sinks, so ``extraction`` uses Mem0's
server-side extraction (no extra model call).
 
For the explicit, model-called tool (``store`` / ``retrieve`` / ``get`` / ``delete``),
use the ``mem0_memory`` tool from ``strands-agents-tools``; a store and the tool can
share one Mem0 backend and namespace.
"""

Sources: integrations/mem0-strands/python/src/mem0_strands/init.py:1-11

Tip

Mem0MemoryStore implements both write sinks so that extraction leverages Mem0's server-side extraction natively, avoiding extra language model calls during agent execution. Sources: integrations/mem0-strands/python/src/mem0_strands/init.py:4-6

Cross-Subsystem Data and Telemetry Flow

Background Telemetry and Execution Coordination

End-to-end data coordination across host harnesses, background sync workers, and anonymized diagnostic telemetry relies on decoupled logging and asynchronous flushing. In agent CLI implementations, commands execute within an instantiated EvidenceStore context that records control actions, telemetry payloads, and local sqlite state updates before finalizing execution through deferred background worker threads.

if args.plugin_data_dir:
    os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir
store = EvidenceStore()
try:
    repo = resolve_repo(os.getcwd())
    telemetry.record("control", repo=repo, action=args.command)

Sources: integrations/mem0-agent-plugin/core/memory_cli.py:86-91

finally:
    store.close()
    telemetry.spawn_flush()
return 0

Sources: integrations/mem0-agent-plugin/core/memory_cli.py:147-150

Note

Telemetry flushing and local store closures are guaranteed via a finally block in CLI entry points, invoking telemetry.spawn_flush() to transmit diagnostics asynchronously without blocking shell process exit. Sources: integrations/mem0-agent-plugin/core/memory_cli.py:147-150

Harness Configuration and Data Routing

Runtime contexts receive environment parameters, configuration prefixes, and source identifiers through modular configuration routines. The harness configuration initializes specific global variables governing environment lookup paths, local plugin data directories, and source telemetry tagging.

def configure_harness(
    name: str,
    env_prefix: str = "",
    data_dir_name: str = "",
    source_tag: str = "",
) -> None:
    global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag
    _harness_name = name
    _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}"
    _harness_data_dir_name = data_dir_name or f"{name}-plugin"
    _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin"
 

Sources: integrations/mem0-agent-plugin/core/memory_core.py:40-51

ParameterDefault ValuePurposeSources
name"generic"Identifies the active agent harness or plugin frameworkintegrations/mem0-agent-plugin/core/memory_core.py:34
env_prefix"MEM0_PLUGIN"Prefix for environment variable overridesintegrations/mem0-agent-plugin/core/memory_core.py:35
data_dir_name"mem0-plugin"Subdirectory name for local evidence and state storageintegrations/mem0-agent-plugin/core/memory_core.py:36
source_tag"mem0_plugin"Telemetry tag identifying the event origin channelintegrations/mem0-agent-plugin/core/memory_core.py:37

Sources: integrations/mem0-agent-plugin/core/memory_core.py:34-51

Where to go next

I want to…Read
How do developers and autonomous agents initialize Mem0, capture conversational memories, and query hybrid memory stores with copy-pasteable snippets across Python and Node.js?Quick Start
How is the Mem0 monorepo organized across Python packages, TypeScript packages, FastAPI backend, Next.js dashboard, CLI implementations, and agent plugins?Project Structure
How does the Python core memory engine extract, add, update, delete, search, and reset user, agent, and session memories using LLMs and vector backends?Memory Lifecycle
How does the Python retrieval engine fuse dense vector similarity, BM25 keyword matching, entity boosting, and temporal recency scoring to rank memories?Multi-Signal Retrieval
How does the Python engine record state changes, manage SQLite or relational audit logs, and isolate user, agent, run, and metadata scopes?Storage and History
How does Mem0 parse structured entities and temporal facts from raw messages using spaCy and entity extraction pipelines for cross-memory linking?Entity Extraction
How does the Python client interface with the Mem0 hosted platform and self-hosted HTTP endpoints for remote memory synchronization and project scoping?Python Client SDK
How does the TypeScript OSS package implement the core Memory class, orchestrate LLM extraction, manage message state, and execute CRUD memory operations?Typescript Core
How does the Python core adapt diverse LLM backends (OpenAI, Anthropic, Bedrock, DeepSeek, Gemini, Groq, Ollama, vLLM, LiteLLM) for structured fact extraction?Python LLM Adapters
How does the TypeScript engine configure and communicate with language model providers including OpenAI, Anthropic, Google, DeepSeek, and Mistral?TypeScript LLM Adapters
How does the Python engine generate vector embeddings across OpenAI, Azure OpenAI, AWS Bedrock, FastEmbed, Gemini, Hugging Face, Ollama, and Vertex AI?Python Embedding Adapters
How does the TypeScript engine instantiate and call embedding generators across providers such as OpenAI, Google, Hugging Face, Bedrock, and FastEmbed?TypeScript Embedding Adapters
How do Cohere, Hugging Face Cross-Encoder, LLM-based, Sentence Transformer, and ZeroEntropy rerankers re-score candidate memory retrievals?Reranking Models
What base abstractions, collection schemas, and query filters govern vector store drivers across both Python and TypeScript runtimes?Vector Store Architecture
How do Qdrant, Pinecone, Milvus, Weaviate, Turbopuffer, Upstash, and S3 Vectors execute cloud-native vector insertion and ANN querying?Cloud Vector Backends
How do relational and search engines (pgvector, Elasticsearch, OpenSearch, Redis, Valkey, Cassandra, Neptune Analytics, Oracle, MongoDB, Azure AI Search, Baidu) store embeddings?Database Vector Stores
How do Chroma, FAISS, and in-memory vector implementations provide zero-dependency local indexing for prototyping and unit testing?Embedded Vector Stores
How does the self-hosted FastAPI application bootstrap application state, handle CORS, register routers, enforce rate limits, and map errors?FastAPI Application
How does the server issue and validate API keys, manage user passwords, enforce admin RBAC, and handle JWT refresh tokens?Server Authentication
How are database connections, SQLAlchemy models, and Alembic migrations structured for user credentials, API keys, request logs, and system settings?Database and Migrations
What REST endpoints and schemas are exposed for memory manipulation, entity browsing, API key rotation, request telemetry, and health inspection?Server API Endpoints
How is the Next.js admin dashboard structured with Redux store state, API query hooks, authentication session providers, and setup wizards?Dashboard Architecture
How do the memories, entities, analytics, API keys, webhooks, and settings dashboard pages render system data and trigger admin mutations?Dashboard Views
How does the Python CLI dispatch terminal commands, switch backends (OSS vs Platform), and format rich output?Python CLI Architecture
How does the TypeScript/Node.js CLI process command line options, resolve authentication tokens, and talk to platform or local backends?Node.js CLI Architecture
How do the CLI init and agent mode commands allow autonomous agents to mint API keys without web browsers and later claim accounts?Agent Account Provisioning
How does the CLI sync configuration, MCP tool declarations, and hooks into agent IDE environments?Plugin Synchronization
How does the common Python plugin core implement memory capture, background flush workers, hook runners, and MCP servers across IDE plugins?Python Agent Core
How does the common TypeScript agent core manage lifecycle hooks, session scoping, prompt synthesis, identity detection, and memory formatting?TypeScript Agent Core
How does the Claude Code plugin intercept transcript streams and run MCP tools to synchronize conversation history with Mem0?Claude Code Plugin
How do the Cursor, Codex, Kimi, and Antigravity plugins configure MCP manifests, adapt host event hooks, and forward IDE state?IDE Plugins Family
How does OpenClaw register memory tools, handle isolation and recall, provide CLI setup wizards, and execute memory CRUD operations?OpenClaw Integration
How does the OpenCode plugin bind workspace project scopes, manage API key authentication, and inject memories into developer agent turns?OpenCode Integration
How does the Pi Agent plugin implement attribution, command handling, memory formatting, and scoping for agent execution loops?Pi Agent Plugin
How does the Hermes plugin bridge Mem0 memory management into Hermes agent pipelines using custom LLM bindings?Hermes Plugin
How does Mem0 wrap Vercel AI SDK LanguageModel instances to inject long-term user context and intercept completions?Vercel AI SDK Integration
How does the mem0-strands package structure thread-level and hierarchical memory graphs for complex agent trajectories?Mem0 Strands
How does the n8n community node expose Mem0 memory operations inside low-code workflow automations?n8n Workflow Nodes
How does the Zapier integration implement authentication, memory addition, deletion, and search triggers for automated app zaps?Zapier Integration
How do developer agent skills and the doc search tool provide inline documentation retrieval to AI coding assistants?Documentation Agent Skills
How does Mem0 record, anonymize, and transmit anonymous usage metrics across Python, TypeScript, CLI, and server components?Telemetry and Metrics
How does the conformance suite validate plugin adapters and harness behaviors against standardized memory artifacts?Plugin Conformance Testing
How do operators migrate memory collections, vector embeddings, and configurations from open-source instances to the Mem0 cloud platform?OSS to Platform Migration
Was this page helpful?