Generated banner for mnemory
Generated logo for mnemory

mnemory

Memory server

Created by Filip Pytloun

Published in fpytloun/mnemory. Publisher page

283 GitHub stars

What it is

A self-hosted, secure, feature-rich memory system for AI agents and assistants. Provides intelligent fact extraction and deduplication, with an artifact store for detailed content.
— the description by Filip Pytloun

AutoGineer overview, from the brain’s own files

mnemory is a self-hosted memory system designed to provide AI agents and assistants with persistent, long-term memory. It functions as an MCP server, allowing it to integrate seamlessly with various AI clients like Claude Code, Cursor, and Open WebUI. The system uses a two-tier architecture: a vector store for fast, semantically searchable summaries and an artifact store for detailed content. It features an intelligent pipeline that performs fact extraction, deduplication, and contradiction resolution in a single LLM call. mnemory also includes a built-in management UI for monitoring and memory maintenance, along with health checks to ensure data quality. It is built for production environments with support for Qdrant, S3/MinIO, and Prometheus monitoring.

How it works

Memory model: Vector store

AutoGineer overview, from the brain’s own files

mnemory operates by intercepting information shared during agent conversations. It uses an LLM pipeline to extract facts, classify them by importance and category, and resolve contradictions against existing data. These facts are stored in a vector database for semantic search, while detailed artifacts are kept in a separate store. During interaction, the system retrieves relevant memories based on the current context and user queries. It also manages memory lifecycles using configurable time-to-live (TTL) settings and provides a health-checking mechanism to detect and fix data inconsistencies.

Folders
FolderRoleFiles
.githubagent-config4
docsdocs31
teststests42
benchmarksfolder16
filesfolder8
integrationsfolder40
mnemoryfolder59

The agent reads

The agent writes

Requirements

Runtimes: Python >=3.11

Databases: Qdrant, Redis

API keys (by name): OPENAI_API_KEY

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Google Antigravity, Kiro, OpenCode, Amp, Roo Code, Cline, JetBrains Junie, Devin (ex-Windsurf)

Set it up

  1. Not scanned by AutoGineerIts dependencies are installed by pip or uv when you run it and were not scanned by AutoGineer (9 declared). https://pypi.org/project/mnemory/
  2. Created by Filip Pytloun. Published in fpytloun/mnemory. Licence: Apache License 2.0.

Usage

AutoGineer overview, from the brain’s own files

  • Connects to AI agents via the Model Context Protocol (MCP).
  • Provides a REST API for custom integrations and plugin development.
  • Includes a web-based dashboard for memory management and visualization.
  • Supports automatic recall and memory persistence across sessions.
  • Offers built-in health checks and maintenance tools for memory quality.
  • Integrates with monitoring tools like Prometheus and Grafana.
“What did I decide last week about the database?”
The agent performs a temporal-aware semantic search across stored memories to retrieve the specific decision made.
“I drive a Skoda.”
The system extracts this fact and stores it; if a later statement says 'I bought a Tesla', it updates the record instead of creating a duplicate.

Documentation by Filip Pytloun

<p align="center"> <img src="files/banner.png" alt="mnemory banner" /> </p>

mnemory

Looking for a complete Agent OS? Meet Cognis — a cloud-native, self-hosted workspace where AI agents do real work. Bring together conversations, tools, workflows, and remote executors, with long-term memory powered by mnemory and guardrails provided by Intaris.

Deletion is intentionally best effort, not a verified-erasure or compliance guarantee. Normal deletion retracts and preserves history; explicit privacy erasure attempts physical cleanup. See deletion limits.

Give your AI agents persistent memory. mnemory is a self-hosted MCP server that adds personalization and long-term memory to any AI assistant — Claude Code, ChatGPT, Open WebUI, Cursor, or any MCP-compatible client.

Plug and play. Connect mnemory and your agent immediately starts remembering user preferences, facts, decisions, and context across conversations. No system prompt changes needed.

Self-hosted and secure. Your data stays on your infrastructure. No cloud dependencies, no third-party access to your memories.

Intelligent. Uses a unified LLM pipeline for fact extraction, deduplication, and contradiction resolution in a single call. Memories are semantically searchable, automatically categorized, and expire naturally when no longer relevant.

Features

  • Zero config — uvx mnemory, connect your MCP client, done. Works out of the box with any OpenAI-compatible API.

  • Intelligent extraction — A single LLM call extracts facts, classifies metadata, and deduplicates against existing memories.

  • Contradiction resolution — "I drive a Skoda" + later "I bought a Tesla" = automatic update, not a duplicate.

  • Two-tier memory — Fast searchable summaries in a vector store + detailed artifact storage (reports, code, research) retrieved on demand.

  • AI-powered search — Multi-query semantic search with temporal awareness. Ask "What did I decide last week about the database?" and it finds the right memories.

  • Memory health checks — Built-in three-phase consistency checker (fsck) detects duplicates, contradictions, quality issues, and prompt injection. Run manually or on a schedule with auto-fix.

  • 10+ client support — Claude Code, ChatGPT, Open WebUI, OpenClaw, Cursor, Windsurf, Cline, OpenCode, and more. Native plugins available for automatic recall/remember.

  • Built-in management UI — Dashboard, semantic search, memory browser with full CRUD, relationship graph visualization, and health check interface. No extra tools needed.

  • Production ready — Qdrant for vectors, S3/MinIO for artifacts, API key or Cognis JWT authentication, per-user isolation, Kubernetes-friendly stateless HTTP.

  • Secure by default — API key or Cognis JWT authentication with session-level identity binding, per-user memory isolation, anti-injection safeguards in extraction prompts.

  • REST API + MCP — Dual interface with the same backend. 16 MCP tools + full REST API with OpenAPI spec. Build plugins, integrations, or use directly.

  • Prometheus monitoring — Built-in /metrics endpoint with operation counters and memory gauges. Pre-built Grafana dashboard included.

Quick Start

mnemory needs an OpenAI-compatible API key for LLM and embeddings. It picks up OPENAI_API_KEY from your environment automatically.

uvx mnemory

If uvx reports No module named 'mcp.server.fastmcp', update uv. Older uv versions on Alpine can ignore mnemory's MCP v1 dependency constraint. Until you update uv, run:

uvx --with "mcp<2" mnemory

That's it. mnemory starts on http://localhost:8050/mcp, stores data in ~/.mnemory/.

Now connect your client — for Claude Code, add to your MCP config:

{
  "mcpServers": {
    "mnemory": {
      "type": "streamable-http",
      "url": "http://localhost:8050/mcp",
      "headers": {
        "X-Agent-Id": "claude-code"
      }
    }
  }
}

Start a new conversation. Memory works automatically.

Also available via Docker, pip, or production setup with Qdrant + S3. See the full quick start guide for more clients and options.

Screenshots

<p align="center"> <img src="files/screenshots/ui-dashboard.jpg" alt="Dashboard — memory totals, breakdowns, and operation counts" width="800" /> <br><em>Dashboard with memory breakdowns by type, category, and role</em> </p>

<p align="center"> <img src="files/screenshots/ui-search.jpg" alt="Search — semantic and AI-powered search with filters" width="800" /> <br><em>Semantic search and AI-powered find with filters</em> </p>

<p align="center"> <img src="files/screenshots/ui-graph.jpg" alt="Graph — D3.js force-directed memory relationship visualization" width="800" /> <br><em>Memory relationship graph visualization</em> </p>

See all screenshots and UI features including memory browser, health checks, and artifact management.

Supported Clients

mnemory works with any MCP-compatible client. Some clients also have dedicated plugins for automatic recall/remember.

ClientMCPPluginSetup Guide
Claude CodeYesYes (hooks)Guide
ChatGPTYes (MCP connector)--Guide
Claude DesktopYes--Guide
Hermes AgentYesYes (plugin)Guide
Open WebUIYesYes (filter)Guide
OpenCodeYesYes (plugin)Guide
OpenClawYesYes (plugin)Guide
CursorYes--Guide
WindsurfYes--Guide
ClineYes--Guide
Continue.devYes--Guide
Codex CLIYes--Guide

MCP = works via Model Context Protocol (LLM-driven tool calls). Plugin = dedicated integration with automatic recall/remember (no LLM tool-calling needed).

How It Works

Storing: You share information naturally. mnemory extracts individual facts, classifies them (type, category, importance), checks for duplicates and contradictions against existing memories, and stores them as searchable vectors — all in a single LLM call.

Searching: Ask a question and mnemory generates multiple search queries covering different angles and associations, runs them in parallel, and reranks results by relevance. Temporal-aware — "what did I decide last week?" just works.

Recalling: At conversation start, your agent loads pinned memories (core facts, preferences, identity) plus recent context. During conversation, relevant memories are found automatically based on what you're discussing.

Maintaining: Memories have configurable TTL — context expires in 7 days, episodic memories in 90. Frequently accessed memories stay alive (reinforcement). The built-in health checker detects and fixes duplicates, contradictions, and quality issues.

Learn more in the architecture docs.

Benchmark

Evaluated on the LoCoMo benchmark — 10 multi-session dialogues with 1540 QA questions across 4 categories:

Systemsingle_hopmulti_hoptemporalopen_domainOverall
mnemory63.153.174.878.273.2
mnemory (gpt-oss-120b)66.359.468.573.870.5
Memobase70.952.185.077.275.8
Mem0-Graph65.747.258.175.768.4
Mem067.151.255.572.966.9
Zep61.741.449.376.666.0
LangMem62.247.923.471.158.1

Configuration: gpt-5-mini for extraction, text-embedding-3-small for vectors. gpt-oss-120b via Groq is a budget alternative at ~5x lower cost with comparable quality. See configuration docs for model options and benchmarks/ for reproduction.

Documentation

DocumentDescription
Quick StartGet running in 5 minutes with any client
ConfigurationAll environment variables — LLM, storage, server, memory behavior
Memory ModelTypes, categories, importance, TTL, roles, scoping, sub-agents
MCP Tools16 MCP tools — memory CRUD, search, artifacts
REST APIFull REST API, fsck pipeline, recall/remember endpoints
ArchitectureSystem diagram, detailed flows for storing/searching/recalling
Management UIScreenshots, features, access, UI development
MonitoringPrometheus metrics, Grafana dashboard
DeploymentProduction setup, Docker, authentication, Kubernetes
DevelopmentBuilding, testing, linting, contributing
Client GuidesPer-client setup instructions (10 clients)
System PromptsTemplates for personality agents and custom setups

License

Apache 2.0

docs/memory-model.md

Memory Model

Two-Tier Architecture

Fast Memory (vector store): Concise facts and summaries, max 1000 characters. Semantically searchable via embeddings. Stored in Qdrant (local embedded or remote).

Slow Memory (artifact store): Detailed content — research reports, analysis, logs, code, images, PDFs. Up to 10MB per artifact (configurable via MAX_ARTIFACT_SIZE). Stored in S3/MinIO or local filesystem. Attached to fast memories, retrieved on demand. Text artifacts support pagination; binary artifacts are returned in full.

Memory Types

TypePurposeDefault TTL
preferenceLikes, dislikes, style choicesPermanent
factBiographical, factual informationPermanent
episodicEvents, interactions, conclusions90 days
proceduralWorkflows, habits, "how to"60 days
contextSession/short-term context7 days

Default TTLs are configurable via environment variables (see Configuration).

Categories

Predefined categories ensure LLM discoverability:

CategoryDescription
personalPersonal life, family, relationships
preferencesLikes, dislikes, style preferences
healthPhysical, mental, medical
workJob, career, professional
technicalTools, languages, infrastructure
financeMoney, investments, billing
homeHouse, appliances, maintenance
vehiclesCars, bikes, maintenance history
travelTrips, places, itineraries
entertainmentMovies, music, books, games
goalsObjectives, plans, ambitions
decisionsConclusions, choices, reasoning
projectProject-specific (use project:<name>)

Dynamic subcategories via prefix: project:myapp, project:demo/deployment-files.

Importance Levels

LevelSearch WeightUse For
low0.1Minor details, temporary notes
normal0.4Standard memories (default)
high0.7Important facts, key decisions
critical1.0Essential information, always-relevant

Search uses hybrid retrieval: dense vectors (semantic similarity via OpenAI embeddings) and BM25 sparse vectors (keyword matching via FastEmbed) are fused server-side using Qdrant's Reciprocal Rank Fusion (RRF). After fusion, an importance-based score boost is applied: score = rrf_score + importance_weight * importance_value, where importance_weight = 1 - SEARCH_SIMILARITY_WEIGHT (default 0.1). This makes importance a tiebreaker rather than a primary ranking factor. Results below SEARCH_SCORE_THRESHOLD_HYBRID (default 0.0) are filtered out. RRF score range depends on Qdrant's k constant: with the default k=1, scores are ~0.1-1.0 (similar to cosine similarity); with k=60, scores are ~0.01-0.03.

Pinned Memories

Memories with pinned: true are loaded at every conversation start via get_core_memories. Use for:

  • User identity facts ("Lives in Prague", "DevOps engineer")

  • Core preferences ("Prefers direct communication")

  • Agent identity ("Your name is Bob", "You speak casually")

  • Agent knowledge ("You researched X and concluded Y")

TTL (Time-To-Live)

Memories can have a TTL that causes them to decay (soft-expire) after a set number of days. Each memory type has a configurable default TTL (see Memory Types table above). You can override the default by passing ttl_days to add_memory.

Lifecycle:

  1. Memory is created with expires_at calculated from ttl_days

  2. When expires_at passes, the memory enters decayed state (soft-deleted)

  3. Decayed memories are excluded from search and list by default

  4. Use include_decayed=true to browse historical/expired memories

  5. Decayed memories can be restored via update_memory (set new ttl_days)

Reinforcement: When a memory is accessed via search_memories, its TTL is automatically reset — expires_at is recalculated from now + original ttl_days. This means frequently-used memories stay alive. Controlled by TRACK_MEMORY_ACCESS config.

Pinned exemption: Pinned memories (pinned: true) are exempt from TTL — they never decay, even if expires_at is set.

Existing memories: No migration needed. Memories without TTL fields are treated as permanent.

Memory Layer

Memories have a memory_layer field that controls their role in the two-layer system:

LayerSourcePurposeRecall Priority
rawremember endpointProvisional evidence from conversation extractionLower (penalized in ranking)
consolidatedadd_memory, consolidation serviceDurable canonical knowledgeHigher (baseline)

Backward compatibility: Memories without a memory_layer field are treated as consolidated.

FieldTypeDescription
memory_layer"raw" or "consolidated"Which layer this memory belongs to
superseded_bystr or nullID of the consolidated memory that replaced this raw memory
derived_fromlist[str] or nullIDs of source raw memories (on consolidated memories from consolidation)
Dedup isolation

The remember pipeline only deduplicates against other raw memories — it never modifies consolidated memories. This prevents noisy raw extraction from overwriting high-quality consolidated content.

Consolidation

A background consolidation service synthesizes durable knowledge from raw memories and their session summaries:

  1. Within-session: After a session goes idle, reads the session summary + raw memories, LLM synthesizes consolidated memories

  2. Re-consolidation: If a session continues after consolidation, new raw memories reset the session to idle. The next consolidation run is append-only — the LLM receives both new raw memories and previously consolidated memories as context, produces new consolidated outputs, and the new consolidated memory IDs are appended alongside previous ones

  3. Automated maintenance (fsck): An automated maintenance engine keeps durable memories coherent. Auto-fsck runs incrementally — only memories changed since the last check are processed. The four-phase pipeline (security → duplicates → content quality → metadata normalization) runs with bounded LLM cost (FSCK_MAX_LLM_CALLS). Manual fsck runs a full scan. Raw memories are excluded by default

  4. Garbage collection: Old superseded raw memories without artifacts are deleted after a configurable retention period. GC runs independently of fsck during the maintenance cycle

Recall ranking

Search results are scored with layer-aware penalties:

  • Consolidated (or absent memory_layer): baseline score

  • Raw, not superseded: small penalty (RECALL_RAW_PENALTY, default 0.05)

  • Raw, superseded: larger penalty (RECALL_SUPERSEDED_PENALTY, default 0.15)

Role

The role parameter controls who the memory is about:

RoleDescriptionExample
user (default for add_memory)Facts about the user"User lives in Prague", "User prefers dark mode"
assistantFacts about the agent itself"Your name is Bob", "You speak casually"

When role="assistant", the server uses an agent-specific fact extraction prompt that focuses on the assistant's identity, personality, and capabilities. When role="user" (default for add_memory), user fact extraction is used. The role is stored in metadata and can be used as a filter in search_memories and list_memories.

The REST POST /api/remember endpoint also supports auto mode (role=null, the default for remember). In auto mode, the LLM extracts facts from all participants and attributes each fact to the correct role. Assistant facts are silently dropped if no agent_id is set in the session. This is the recommended mode for plugins that send full conversation exchanges.

get_core_memories uses role to organize agent-scoped memories into sections:

  • Agent Identity: pinned, role=assistant, fact/preference type

  • Agent Knowledge: pinned, role=assistant, other types

  • Agent Instructions: pinned, role=user, agent-scoped (user preferences specific to this agent)

Scoping

  • user_id (required): Every memory belongs to a user. Shared across all agents. Can be set at session level via API key mapping (MCP_API_KEYS) or X-User-Id header, eliminating the need to pass it per tool call.

  • agent_id (optional): Set for agent-scoped memories. Two use cases:

    • Agent identity (role="assistant"): The agent's name, personality, capabilities, knowledge.

    • Agent-scoped user preferences (role="user"): User preferences that apply only to this agent (e.g., "User wants me to create commit messages").

    Different agents see different agent memories but share user memories. Can be set at session level via X-Agent-Id header.

Sub-agents

Sub-agents allow creating multiple independent agent identities under a single session. Use a colon-separated prefix matching the session's X-Agent-Id:

X-Agent-Id: openwebui          <- session agent
agent_id: openwebui:bob        <- sub-agent "bob" (allowed)
agent_id: openwebui:alice      <- sub-agent "alice" (allowed)
agent_id: cursor:foo           <- different parent (blocked)

Sub-agents are fully independent — they have their own memories and do NOT inherit from the parent agent. The session agent can access and manage all its sub-agents' memories.

Memory Metadata

Custom metadata is stored as flat fields in the Qdrant payload alongside standard fields:

FieldTypeDescription
memory_typestrpreference, fact, episodic, procedural, context
categorieslist[str]Category tags
importancestrlow, normal, high, critical
pinnedboolWhether to include in core memories
rolestr"user" or "assistant" — who the memory is about. Always stored as one of these two values.
artifactslist[dict]Artifact metadata (id, filename, content_type, size, created_at)
event_datestr|NoneISO 8601 UTC datetime of when the event occurred
created_at_utcstrUTC timestamp
ttl_daysint|NoneOriginal TTL setting in days (None = permanent)
expires_atstr|NoneISO 8601 expiration timestamp (None = never expires)
decayed_atstr|NoneWhen memory entered decayed state (None = active)
labelsdict|NoneClient-provided key-value metadata (e.g., project, topic, conversation_id). Bypasses LLM extraction. Filterable in search/list queries.
last_accessed_atstr|NoneLast time returned in search
access_countintNumber of times accessed in search

Labels

Labels are client-provided key-value metadata that can be attached to any memory. Unlike categories and memory types, labels bypass the LLM entirely — they are stored exactly as provided and never inferred or modified by the extraction pipeline.

Use Cases
  • Project scoping: {"project": "myapp"} — filter memories by project

  • Conversation tracking: {"conversation_id": "conv-123"} — link memories to conversations

  • Environment tagging: {"env": "prod", "region": "eu-west-1"} — tag by deployment context

  • Custom workflows: {"reviewed": true, "priority": 1} — application-specific metadata

Value Types

Labels support flat values only:

TypeExample
str"myapp"
int42
float3.14
booltrue
list[str]["tag1", "tag2"]

Nested dicts and other complex types are not allowed.

Inheritance

When using infer=True or the remember pipeline, labels are inherited by all extracted facts. If you call add_memory(content="...", labels={"project": "myapp"}) and the LLM extracts 3 facts, all 3 get those labels.

Filtering

Labels can be used as filters in search_memories, find_memories, and list_memories. Filtering uses AND logic across multiple keys, with list values using any-of (OR) within a single key:

labels={"project": "myapp", "env": "prod"}

This matches memories where labels.project == "myapp" AND labels.env == "prod".

Updating
  • Passing labels={"key": "value"} to update_memory merges with existing labels (caller wins on key conflicts)

  • Passing labels={} (empty dict) clears all labels

  • Passing labels=None (or omitting) preserves existing labels

Constraints
ConstraintDefaultConfig
Max labels per memory20LABELS_MAX_FIELDS
Max key length64 charsLABELS_MAX_KEY_LENGTH
Max string value length1000 charsLABELS_MAX_VALUE_LENGTH
Key pattern^[a-zA-Z_][a-zA-Z0-9_]*$—
Reserved keysSystem field names (e.g., memory_type, user_id, labels)—
212 files · 196 not served here

Advantages

  • Intelligent extraction and contradiction resolution ensure memory accuracy and prevent duplicate entries. evidence: README.md
  • Self-hosted architecture ensures data privacy with no third-party access to stored memories. evidence: README.md
  • Supports a wide range of clients through the Model Context Protocol and dedicated plugins. evidence: README.md

Limitations

  • Deletion is best-effort and does not guarantee verified erasure or compliance. evidence: README.md
  • Most MCP clients require a specific system prompt instruction to initialize memory correctly. evidence: docs/README.md

Security

Risk level: Low risk

This brain runs

Agent instructions that run or fetch something (8)

  • AGENTS.md: docker buildx build --platform linux/amd64,linux/arm64 -t ghcr.io/fpytloun/mnemory:latest .
  • AGENTS.md: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/fpytloun/mnemory:latest .
  • AGENTS.md: # Unit tests (fast, no API key needed, default pytest run)
  • AGENTS.md: They are **excluded from the default `pytest` run** via `addopts = "-m 'not e2e'"` in `pyproject.toml`.
  • AGENTS.md: **When to run e2e tests:**
  • AGENTS.md: Migrations run automatically on startup before the server accepts requests.
  • AGENTS.md: Each migration has a unique ID (e.g., `001_add_sparse_vectors`), a `description`, and a `run()` method
  • AGENTS.md: Migrations must be **idempotent** — safe to re-run if interrupted mid-way or if multiple instances start simultaneously

MCP servers (1)

  • README.md (mnemory): http://localhost:8050/mcp · uses the network
  • Low risk: network-instructions (AGENTS.md:88)

Attribution and licence

Created by
Filip Pytloun
Declared authors
  • Filip Pytloun (declared in pyproject.toml)
Publisher
Filip Pytloun (Community)
Source
fpytloun/mnemory · commit 2d83c47
Licence
Apache License 2.0 (files served here)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Filip Pytloun.

Install from source

196 of its files are not served here, so there is no ZIP. fpytloun/mnemory at 2d83c47