The mem0-mcp-selfhosted server provides persistent memory management for Claude Code through 11 MCP tools, enabling cross-session context retention with optional knowledge graph capabilities using Qdrant, Neo4j, and Ollama.
Core Memory Operations
add_memory— Store text or conversation history as memories, with optional LLM-based fact extraction, metadata tagging, and per-call graph togglingsearch_memories— Semantically search memories using natural language queries, with filters, relevance thresholds, reranking, and optional graph searchget_memories— Page through memories using scope filters (user, agent, run) without semantic searchget_memory— Fetch a single memory by UUIDupdate_memory— Overwrite and re-embed an existing memory's text by UUIDdelete_memory— Delete a single memory by UUIDdelete_all_memories— Bulk-delete all memories within a given scope
Entity & Graph Management
list_entities— List all users, agents, and runs with stored memories and countsdelete_entities— Cascade-delete an entire entity and all its associated memoriesmcp_search_graph— Search the Neo4j knowledge graph for entities by name/topic, returning entities and outgoing relationshipsmcp_get_entity— Retrieve all bidirectional relationships for a specific entity in the knowledge graph
Additional Features
Session hooks for automatic memory injection on startup and summary saving on exit
CLAUDE.md integration to instruct Claude Code to proactively use memory tools
Flexible LLM configuration: Anthropic (Claude), Ollama, or Gemini for main LLM, embeddings, and graph operations
Multiple transport modes: stdio, SSE, and streamable-http
Automatic OAT token handling for zero-config use within Claude Code
Structured filter support (
AND/ORoperators) and scoped memory viauser_id,agent_id,run_idSuppressed telemetry for privacy
Supports using Google Gemini models as a provider for knowledge graph extraction and entity relationship processing.
Integrates with Neo4j as a knowledge graph backend to store and retrieve bidirectional entity relationships.
Enables fully local operation by using Ollama for both embedding generation and as the primary LLM for memory management.
mem0-mcp-selfhosted
Self-hosted mem0 MCP server for Claude Code. Run a complete memory server against self-hosted Qdrant + Neo4j + Ollama, with your choice of Anthropic (Claude) or Ollama as the main LLM.
Uses the mem0ai package directly as a library, supports both Claude's OAT token and fully local Ollama setups, and exposes 11 MCP tools for full memory management.
Prerequisites
Service | Required | Purpose |
Qdrant | Yes | Vector memory storage and search |
Ollama | Yes | Embedding generation ( |
Neo4j 5+ | Optional | Knowledge graph (entity relationships) |
Google API Key | Optional | Required only for |
Python >= 3.10 and uv.
Authentication: The default setup uses Claude (Anthropic) as the LLM for fact extraction. No API key needed, the server automatically uses your Claude Code session token. For fully local setups, set
MEM0_PROVIDER=ollama. See Authentication for advanced options.
Quick Start
Default (Anthropic)
Add the MCP server globally (available across all projects):
claude mcp add --scope user --transport stdio mem0 \
--env MEM0_USER_ID=your-user-id \
-- uvx --from git+https://github.com/elvismdev/mem0-mcp-selfhosted.git mem0-mcp-selfhostedAll defaults work out of the box: Qdrant on localhost:6333, Ollama embeddings on localhost:11434 with bge-m3 (1024 dims). Override any default via --env (see Configuration).
uvx automatically downloads, installs, and runs the server in an isolated environment, no manual installation needed. Claude Code launches it on demand when the MCP connection starts.
The server auto-reads your OAT token from ~/.claude/.credentials.json, no manual token configuration needed.
Fully Local (Ollama)
For a fully local setup with no cloud dependencies, use Ollama for both the main LLM and embeddings:
claude mcp add --scope user --transport stdio mem0 \
--env MEM0_PROVIDER=ollama \
--env MEM0_LLM_MODEL=qwen3:14b \
--env MEM0_USER_ID=your-user-id \
-- uvx --from git+https://github.com/elvismdev/mem0-mcp-selfhosted.git mem0-mcp-selfhostedMEM0_PROVIDER=ollama cascades to both the main LLM and graph LLM providers. Same infrastructure defaults apply (Qdrant on localhost:6333, bge-m3 embeddings). Per-service overrides (e.g. MEM0_LLM_URL, MEM0_EMBED_URL) still work when needed.
Or add it to a single project by creating .mcp.json in the project root:
{
"mcpServers": {
"mem0": {
"command": "uvx",
"args": ["--from", "git+https://github.com/elvismdev/mem0-mcp-selfhosted.git", "mem0-mcp-selfhosted"],
"env": {
"MEM0_PROVIDER": "ollama",
"MEM0_LLM_MODEL": "qwen3:14b",
"MEM0_USER_ID": "your-user-id"
}
}
}
}Try It
Restart Claude Code, then:
> Search my memories for TypeScript preferences
> Remember that I prefer Hatch for Python packaging
> Show me all entities in my knowledge graphCLAUDE.md Integration
Add these rules to your project's CLAUDE.md (or ~/.claude/CLAUDE.md for global use) so Claude Code proactively uses memory tools throughout the session:
# MCP Servers
- **mem0**: Persistent memory across sessions. At the start of each session, `search_memories` for relevant context before asking the user to re-explain anything. Use `add_memory` whenever you discover project architecture, coding conventions, debugging insights, key decisions, or user preferences. Use `update_memory` when prior context changes. Save information like: "This project uses PostgreSQL with Prisma", "Tests run with pytest -v", "Auth uses JWT validated in middleware". When in doubt, save it, future sessions benefit from over-remembering.This gives Claude Code behavioral instructions to actively search and save memories during the session. For best results, combine with Claude Code Hooks, the CLAUDE.md rules tell Claude how to use memory tools mid-session, while hooks handle the automatic injection and saving at session boundaries.
Claude Code Hooks
Session hooks automate memory at session boundaries, injecting memories on startup and saving summaries on exit. This happens automatically without manual tool calls.
Hook | Event | What it does |
| SessionStart ( | Searches mem0 for project-relevant memories and injects them as |
| Stop | Reads the last ~3 user/assistant exchanges from the transcript and saves a summary to mem0 via |
Both hooks are non-fatal, if mem0 is unreachable or any error occurs, Claude Code continues normally.
Install
Install hooks into your project:
mem0-install-hooksOr install globally (all projects):
mem0-install-hooks --globalThis adds the hook entries to .claude/settings.json. The installer is idempotent, running it twice won't create duplicates.
How it works
On session start, the context hook searches mem0 with two queries (project architecture + recent session summaries), deduplicates by memory ID, and formats the results as numbered lines under a # mem0 Cross-Session Memory header. These are injected via the hook's additionalContext response field.
On session stop, the stop hook reads the JSONL transcript, extracts the last 6 user/assistant messages (a sliding window via bounded deque), builds a summary prompt, and calls memory.add(infer=True) to extract atomic facts. Graph is force-disabled in hooks to stay within the 15s/30s timeout budgets.
Entry points
Command | Function | Registered in |
|
| SessionStart hook |
|
| Stop hook |
|
| CLI installer |
Hooks + CLAUDE.md
Hooks and CLAUDE.md are complementary layers that work best together:
Layer | Role | When |
Hooks | Automated data flow, injects stored memories on startup, saves session summaries on exit | Session boundaries (start/stop) |
CLAUDE.md | Behavioral instructions, tells Claude to actively search and save memories during the session | Throughout the session |
Hooks alone give you passive recall (memories appear at startup) and passive saving (summaries saved at exit). CLAUDE.md instructions add active mid-session behavior, Claude searches for relevant memories when encountering new topics, and saves important discoveries immediately rather than waiting for session end.
For the best experience, use both. Hooks ensure memories flow in and out automatically at session boundaries, while CLAUDE.md ensures Claude actively engages with memory tools during the session.
Authentication
The server resolves an Anthropic token using a prioritized fallback chain:
Priority | Source | Details |
1 |
| Explicit, user-controlled |
2 |
| Auto-reads Claude Code's OAT token (zero-config) |
3 |
| Standard pay-per-use API key |
4 | Disabled | Warns and disables Anthropic LLM features |
In Claude Code, priority 2 always wins, the credentials file exists as long as you're logged in. This means ANTHROPIC_API_KEY (priority 3) is never reached. To override the OAT token in Claude Code, use MEM0_ANTHROPIC_TOKEN (priority 1). ANTHROPIC_API_KEY is only useful for non-Claude-Code deployments (Docker, CI, standalone).
OAT tokens (sk-ant-oat...) use your Claude subscription. The server automatically detects the token type and configures the SDK accordingly. OAT tokens are automatically refreshed before expiry: the server proactively checks the token lifetime and refreshes via the Anthropic OAuth endpoint when nearing expiry (default: 30 minutes). On authentication failures, a 3-step defensive strategy kicks in, piggybacking on Claude Code's credentials file, self-refreshing via OAuth, and wait-and-retry, so long-running sessions survive token rotation seamlessly.
API keys (sk-ant-api...) use standard pay-per-use billing.
Tools
Memory Tools (9 core)
Tool | Description |
| Store text or conversation history as memories. Supports |
| Semantic search with optional |
| List/filter memories (non-search). Supports |
| Fetch a single memory by UUID. |
| Replace memory text. Re-embeds and re-indexes in Qdrant. |
| Delete a single memory by UUID. |
| Bulk-delete all memories in a scope. |
| List users/agents/runs with memory counts. Uses Qdrant Facet API. |
| Cascade-delete an entity and all its memories. |
Graph Tools
Tool | Description |
| Search Neo4j entities by name substring. Returns entities + outgoing relationships. |
| Get all relationships for an entity (bidirectional: incoming + outgoing). |
Prompt
The server registers a memory_assistant MCP prompt that provides Claude with a quick-start guide for using the memory tools effectively.
Parameters
All tools use Pydantic Annotated[type, Field(description=...)] for self-documenting parameter schemas. Common patterns:
user_iddefaults toMEM0_USER_IDenv var when not providedenable_graphoverrides the defaultMEM0_ENABLE_GRAPHper-callfilterssupports structured operators:{"key": {"eq": "value"}},{"AND": [...]}All responses are JSON strings via
json.dumps(result, ensure_ascii=False)
Configuration
All configuration is via environment variables. Create a .env file or set them in your MCP config.
Authentication
Variable | Default | Description |
| -- | Anthropic OAT or API token (priority 1) |
| -- | Standard Anthropic API key (priority 3) |
|
| OAT identity headers: |
|
| Seconds before expiry to trigger proactive OAT token refresh |
LLM
Variable | Default | Description |
|
| Top-level provider ( |
| (MEM0_PROVIDER) | Main LLM provider: |
|
| Shared Ollama base URL. Cascades to |
| (per-provider) | Model for the selected LLM provider. Defaults to |
| (cascades) | Ollama base URL for the main LLM. Cascades: |
|
| Max tokens for LLM responses (Anthropic only) |
| (MEM0_PROVIDER) | Graph LLM provider ( |
| (cascades) | Ollama base URL for graph LLM. Cascades: |
| (varies) | Graph model. Inherits |
| -- | Google API key (required for |
|
| Contradiction LLM provider in |
| (provider-aware) | Contradiction model in |
|
| How long Ollama keeps the model in VRAM between calls (e.g., |
|
| Set to |
Embedder
Variable | Default | Description |
|
| Embedding provider ( |
|
| Embedding model name |
| (cascades) | Ollama URL for embeddings. Cascades: |
|
| Embedding vector dimensions |
Vector Store (Qdrant)
Variable | Default | Description |
|
| Qdrant REST API URL |
| -- | Qdrant API key (for Qdrant Cloud) |
|
| Store vectors on disk (reduces RAM, slower search) |
| (client default) | Qdrant REST API timeout in seconds (e.g., |
|
| Qdrant collection name |
Graph Store (Neo4j)
Variable | Default | Description |
|
| Enable graph memory (entity extraction to Neo4j) |
|
| Neo4j Bolt endpoint |
|
| Neo4j username |
|
| Neo4j password |
| -- | Neo4j database name (multi-database setups) |
| -- | Custom Neo4j base label for node type grouping |
|
| Embedding similarity threshold for node matching |
Server
Variable | Default | Description |
|
| Transport: |
|
| Host for SSE/HTTP transports |
|
| Port for SSE/HTTP transports |
|
| Default user ID for memory scoping |
|
| Logging level ( |
| -- | SQLite path for memory change history |
Architecture
Claude Code
|
├── MCP stdio/SSE/streamable-http
│ |
│ ├── env.py ← Centralized env var readers (whitespace-safe)
│ ├── auth.py ← Hybrid token fallback chain + OAT self-refresh
│ ├── llm_anthropic.py ← Custom Anthropic LLM provider (OAT + structured outputs)
│ ├── llm_ollama.py ← Custom Ollama LLM provider (restored tool-calling)
│ ├── config.py ← Env vars → MemoryConfig dict (provider + URL cascades)
│ ├── helpers.py ← Error wrapper, concurrency lock, safe bulk-delete, monkey-patches
│ ├── graph_tools.py ← Direct Neo4j Cypher queries (lazy driver)
│ ├── llm_router.py ← Split-model graph LLM router (gemini_split)
│ ├── __init__.py ← Telemetry suppression (before any mem0 import)
│ └── server.py ← FastMCP orchestrator (11 tools + prompt)
│ |
│ ├── mem0ai Memory class
│ │ ├── Vector: LLM fact extraction → Ollama embed → Qdrant
│ │ └── Graph: LLM entity extraction (tool calls) → Neo4j
│ |
│ └── Infrastructure
│ ├── Qdrant ← Vector store
│ ├── Ollama ← Embeddings
│ ├── Neo4j ← Knowledge graph (optional)
│ └── Anthropic/Ollama ← Main LLM (configurable)
|
└── Session Hooks (subprocess, not MCP)
|
└── hooks.py ← Cross-session memory (SessionStart + Stop hooks)
├── context_main() → Injects memories as additionalContext on startup/compact
├── stop_main() → Saves session summary to mem0 on exit
└── install_main() → CLI to patch .claude/settings.jsonGraph Memory & Quota
Graph memory is disabled by default (MEM0_ENABLE_GRAPH=false) to protect your Claude quota. Each add_memory with graph enabled triggers 3 additional LLM calls for entity extraction, relationship generation, and conflict resolution.
Using Ollama for Graph Operations
To eliminate Claude quota usage for graph ops, use a local Ollama model:
MEM0_ENABLE_GRAPH=true
MEM0_GRAPH_LLM_PROVIDER=ollama
MEM0_GRAPH_LLM_MODEL=qwen3:14bQwen3:14b has 0.971 tool-calling F1 (nearly matching GPT-4's 0.974) and runs in ~7-8GB VRAM with Q4_K_M quantization.
Using Gemini for Graph Operations
Google's Gemini 2.5 Flash Lite is the cheapest option for graph ops while maintaining strong entity extraction accuracy:
MEM0_ENABLE_GRAPH=true
MEM0_GRAPH_LLM_PROVIDER=gemini
MEM0_GRAPH_LLM_MODEL=gemini-2.5-flash-lite
GOOGLE_API_KEY=your-google-api-keyUsing Split-Model for Best Accuracy
The gemini_split provider routes graph pipeline calls to different LLMs based on the operation. Entity extraction (Calls 1 & 2) goes to Gemini for speed and cost; contradiction detection (Call 3) goes to Claude for accuracy.
MEM0_ENABLE_GRAPH=true
MEM0_GRAPH_LLM_PROVIDER=gemini_split
GOOGLE_API_KEY=your-google-api-key
MEM0_GRAPH_CONTRADICTION_LLM_PROVIDER=anthropic
MEM0_GRAPH_CONTRADICTION_LLM_MODEL=claude-opus-4-6Benchmark results across 248 test cases: Gemini scores 85.4% on entity extraction (vs Claude's 79.1%), while Claude scores 100% on contradiction detection (vs Gemini's 80%). The split-model combines the best of both.
Transport Modes
Mode | Use Case | Config |
| Claude Code integration |
|
| Legacy remote clients |
|
| Modern remote clients |
|
For remote deployments, MCP SDK >= 1.23.0 enables DNS rebinding protection by default.
Development
# Install with dev dependencies
pip install -e ".[dev]"
# Run unit tests
python3 -m pytest tests/unit/ -v
# Run contract tests (validates mem0ai internal API assumptions)
python3 -m pytest tests/contract/ -v
# Run integration tests (requires live Qdrant + Neo4j + Ollama)
python3 -m pytest tests/integration/ -v
# Run all tests
python3 -m pytest tests/ -vTest Structure
tests/unit/-- Pure unit tests with mocked dependencies (env, auth, config, config matrix, concurrency, MCP protocol, helpers, hooks, LLM providers, graph tools, LLM router, server)tests/contract/-- Validates assumptions about mem0ai internals (schema detection invariant,vector_store.clientaccess path,LlmFactoryregistration idempotency)tests/integration/-- Live infrastructure tests (memory lifecycle, graph ops, bulk operations, hooks) against real Qdrant + Neo4j + Ollama. Marked with@pytest.mark.integration.
Contract tests catch breaking changes in mem0ai upgrades before they reach production.
Telemetry
All mem0ai telemetry is suppressed. os.environ["MEM0_TELEMETRY"] = "false" is set at package import time, before any mem0 module is loaded. No PostHog events are sent.
License
MIT