mem0-mcp-selfhosted
About
Self-hosted mem0 MCP server for Claude Code. Run a complete memory server against self-hosted Qdrant + Neo4j + Ollama while using Claude as the main LLM.
Details
- Author
- elvismdev
- Categories
- Database, AI, Other, Knowledge Base
Jump to
Setup
Install mem0-mcp-selfhosted in your MCP client (Claude Desktop, Cursor, Windsurf, and others).
Repository: https://github.com/elvismdev/mem0-mcp-selfhosted
Follow the installation instructions in the repository README, then restart your MCP client.
Uses themem0aipackage directly as a library, supports both Claude's OAT token and fully local Ollama setups, and exposes 11 MCP tools for full memory management.
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, setMEM0_PROVIDER=ollama. SeeAuthenticationfor advanced options.
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-selfhosted
All defaults work out of the box: Qdrant onlocalhost:6333, Ollama embeddings onlocalhost:11434withbge-m3(1024 dims). Override any default via--env(seeConfiguration).
uvxautomatically 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.
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-selfhosted
MEM0_PROVIDER=ollamacascades to both the main LLM and graph LLM providers. Same infrastructure defaults apply (Qdrant onlocalhost:6333,bge-m3embeddings). 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.jsonin 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" } } } }
> Search my memories for TypeScript preferences > Remember that I prefer Hatch for Python packaging > Show me all entities in my knowledge graph
Add these rules to your project'sCLAUDE.md(or~/.claude/CLAUDE.mdfor 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 withClaude Code Hooks, the CLAUDE.md rules tell Claudehow to usememory tools mid-session, while hooks handle theautomaticinjection and saving at session boundaries.
Session hooks automate memory at session boundaries, injecting memories on startup and saving summaries on exit. This happens automatically without manual tool calls.
Both hooks are non-fatal, if mem0 is unreachable or any error occurs, Claude Code continues normally.
This adds the hook entries to.claude/settings.json. The installer is idempotent, running it twice won't create duplicates.
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 Memoryheader. These are injected via the hook'sadditionalContextresponse 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 callsmemory.add(infer=True)to extract atomic facts. Graph is force-disabled in hooks to stay within the 15s/30s timeout budgets.
Hooks and CLAUDE.md are complementary layers that work best together:
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.
The server resolves an Anthropic token using a prioritized fallback chain:
In Claude Code, priority 2 always wins, the credentials file exists as long as you're logged in. This meansANTHROPIC_API_KEY(priority 3) is never reached. To override the OAT token in Claude Code, useMEM0_ANTHROPIC_TOKEN(priority 1).ANTHROPIC_API_KEYis 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.
The server registers amemory_assistantMCP prompt that provides Claude with a quick-start guide for using the memory tools effectively.
All tools use PydanticAnnotated[type, Field(description=...)]for self-documenting parameter schemas. Common patterns:
- user_iddefaults toMEM0_USER_IDenv var when not provided
- enable_graphoverrides the defaultMEM0_ENABLE_GRAPHper-call
- filterssupports structured operators:{"key": {"eq": "value"}},{"AND": [...]}
- All responses are JSON strings viajson.dumps(result, ensure_ascii=False)
All configuration is via environment variables. Create a.envfile or set them in your MCP config.
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.json
Graph memory isdisabled by default(MEM0_ENABLE_GRAPH=false) to protect your Claude quota. Eachadd_memorywith graph enabled triggers 3 additional LLM calls for entity extraction, relationship generation, and conflict resolution.
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:14b
Qwen3: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.
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-key
Thegemini_splitprovider 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-6
Benchmark 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.
For remote deployments, MCP SDK >= 1.23.0 enables DNS rebinding protection by default.
# 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/ -v
- 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 inmem0aiupgrades before they reach production.
All mem0ai telemetry is suppressed.os.environ["MEM0_TELEMETRY"] = "false"is set at package import time, before anymem0module is loaded. No PostHog events are sent.
A knowledge graph implementation with semantic search powered by the Qdrant vector database.
A server for Zero-Vector's hybrid vector-graph persona and memory management system, featuring advanced LangGraph workflow capabilities.
Implement semantic memory layer on top of the Qdrant vector search engine
Provides AI assistants with persistent memory using ChromaDB vector storage.
An MCP server for graph-based memory management, enabling AI to create, retrieve, and manage knowledge entities and their relationships.
MCP memory server with Hebbian learning — concept connections strengthen through co-activation and weaken through disuse.
Enables memory for Claude using a knowledge graph with fuzzy semantic search and persistent storage.
A knowledge graph server that provides persistent, multi-context memory for AI models.
A distributed memory bank MCP tool that stores memories in a KùzuDB graph database, with repository and branch filtering capabilities.
Provides persistent memory for AI models using a local knowledge graph.
Sign in to leave a review
Use Google, GitHub, or an email account so ratings stay tied to real people.
No reviews posted yet.





