Skip to main content
Glama
mem0-agent-memory

mem0-agent-memory

Mem0 Agent Memory

PyPI version PyPI Downloads PyPI Downloads Python versions License: MIT

A Model Context Protocol (MCP) server that provides persistent memory capabilities for AI agents using Mem0. Store, search, and manage contextual information across conversations with support for multiple backends and LLM providers.

Features

Core Capabilities:

  • 🧠 Persistent Memory: Store and retrieve contextual information across sessions

  • 🔍 Semantic Search: Find relevant memories using natural language queries

  • 📚 Document Ingestion: Import PDFs, DOCX, Markdown, and text files as knowledge base

  • 🏷️ Metadata Filtering: Organize and filter memories by type, priority, status, and custom fields

  • 📊 Memory Management: Full CRUD operations with history tracking and bulk operations

Backend Support:

  • Vector Stores: FAISS (local), Qdrant (embedded/server), OpenSearch (AWS), Mem0 Platform (cloud)

  • LLM Providers: AWS Bedrock (Claude, Titan), Ollama (local), LM Studio (local)

  • Graph Store: KuzuDB integration for relationship tracking (experimental)

Developer Experience:

  • ⚡ Auto-configuration: Automatic user/agent detection from system context

  • 🎯 Memory-First Workflows: One-command setup for Kiro IDE integration

  • 🔧 Performance Tuning: Configurable inference, relevance filtering, and connection pooling

  • 📦 Session Partitioning: Isolate memories by run_id for multi-session management

Related MCP server: MCP-Mem0

Quick Start

Installation

pip install mem0-agent-memory

Basic Setup

Add to your MCP client configuration:

Kiro: .kiro/settings/mcp.json Amazon Q CLI: ~/.aws/amazonq/mcp.json or .amazonq/mcp.json

{
  "mcpServers": {
    "mem0-agent-memory": {
      "command": "uvx",
      "args": ["mem0-agent-memory"],
      "env": {
        "AWS_ACCESS_KEY_ID": "your-key",
        "AWS_SECRET_ACCESS_KEY": "your-secret",
        "AWS_REGION": "us-west-2"
      }
    }
  }
}

Enable Memory-First Workflows (Kiro Only)

In your first chat session:

setup steering for memory

This configures the AI to automatically check memory before tasks and store important outcomes.

Configuration

LLM Providers

Choose your LLM backend by setting the appropriate environment variables:

export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_REGION="us-west-2"

# Optional: Customize models
export BEDROCK_LLM_MODEL="us.anthropic.claude-3-5-haiku-20241022-v1:0"
export BEDROCK_EMBED_MODEL="amazon.titan-embed-text-v2:0"
export BEDROCK_MAX_TOKENS="1500"  # Default: 1500

Performance: Built-in optimizations include connection pooling (50 connections), adaptive retries, and reduced latency settings.

export OLLAMA_HOST="http://localhost:11434"
export OLLAMA_LLM_MODEL="llama3.2"           # Default
export OLLAMA_EMBED_MODEL="nomic-embed-text" # Default

# Pull models first:
ollama pull llama3.2
ollama pull nomic-embed-text

Note: For Nomic embeddings, set NOMIC_USE_PREFIXES=true for better search accuracy.

export LMSTUDIO_HOST="http://localhost:1234"
export LMSTUDIO_LLM_MODEL="llama-3.2-3b-instruct"
export LMSTUDIO_EMBED_MODEL="text-embedding-nomic-embed-text-v1.5"

Vector Store Backends

export FAISS_PATH="/path/to/.mem0/memory"  # Optional, defaults to .mem0/memory

Best for: Development, small-medium datasets (<100k memories), single-user scenarios.

Embedded Mode (No Docker):

export QDRANT_PATH=".mem0/qdrant"

Server Mode (Production):

export QDRANT_HOST="localhost"
export QDRANT_PORT="6333"  # Optional

Benefits: Native metadata filtering, better performance for complex queries, production-ready clustering. See Qdrant Setup Guide for details.

export OPENSEARCH_HOST="your-opensearch-endpoint"
export AWS_REGION="us-west-2"

Best for: Large datasets (>100k memories), complex filtering, enterprise deployments.

export MEM0_API_KEY="your-api-key"

Best for: Managed service, no infrastructure management, built-in features.

Additional Settings

# User/Agent ID (optional - auto-detected if not set)
export MEM0_USER_ID="custom-user-id"      # Defaults to system username
export MEM0_AGENT_ID="custom-agent-id"    # Defaults to workspace name
export MEM0_RUN_ID="session-123"          # Optional: session partitioning

# Performance
export MEM0_INFER_DEFAULT="true"          # LLM inference for fact extraction
export MEM0_MIN_RELEVANCE_SCORE="0.7"     # Search result threshold (0.0-1.0)

# Response Optimization (v1.3.0+)
export MEM0_VERBOSE="false"               # Compact responses (default) vs verbose
export MEM0_MAX_RELATIONS="20"            # Max graph relations in compact mode

# Nomic embeddings (Ollama only)
export NOMIC_USE_PREFIXES="true"          # Improves search accuracy

Response Modes (v1.3.0+):

  • Compact (default): Returns only essential fields (id, memory, metadata, score). Reduces token usage by ~55% per memory.

  • Verbose: Returns all fields including hash, timestamps, user_id, agent_id, etc.

  • Graph relations: Preserved in both modes, truncated to 20 in compact mode to prevent token bloat

  • Control per-call with verbose parameter or globally with MEM0_VERBOSE environment variable.

Available Tools

Core Operations

Tool

Description

store_memory

Store memory with optional metadata and inference control

search_memories

Semantic search with relevance filtering

list_memories

List all memories with pagination

get_memory

Retrieve specific memory by ID

get_recent_memories

Get recently added/updated memories

Advanced Operations

Tool

Description

update_memory

Update existing memory directly (no LLM processing)

search_by_metadata

Filter memories by metadata fields (type, priority, status)

get_memory_history

View change history for a memory

get_memory_stats

Get memory usage statistics

Bulk Operations

Tool

Description

delete_memory

Delete single memory (permanent)

delete_all_memories

Delete all memories for a scope (permanent)

bulk_delete_memories

Delete multiple memories by filter (dry-run supported)

Import/Export

Tool

Description

export_memories

Export to JSON or Markdown format

import_memories

Import memories from JSON export

ingest_documents

Ingest PDF, DOCX, MD, TXT files as knowledge base

Utilities

Tool

Description

health_check

Verify backend connectivity

reset_memory

Reset entire memory store (destructive)

setup_steering

Create Kiro memory-first steering file

For detailed parameter documentation, see the tool descriptions in your MCP client.

Usage Examples

Basic Memory Operations

# Store a memory
store_memory(
    content="User prefers React over Vue for frontend development",
    metadata={"type": "preference", "priority": "high"}
)

# Search memories
search_memories(query="React preferences", limit=5)

# Get recent memories
get_recent_memories(days=7, limit=10)

# Filter by metadata
search_by_metadata(type="preference", priority="high")

Document Ingestion

# Ingest single file
ingest_documents(path="/path/to/manual.pdf")

# Ingest directory recursively
ingest_documents(
    path="/path/to/docs",
    recursive=True,
    chunk_size=2048,
    chunk_overlap=400,
    file_metadata={"type": "documentation", "version": "2.0"}
)

# Search ingested documents
search_memories(query="how to configure authentication")

Session Partitioning

# Store memory for specific session
store_memory(
    content="Current task: Implementing user authentication",
    run_id="session-123",
    metadata={"type": "task", "status": "in_progress"}
)

# Search within session
search_memories(query="authentication", run_id="session-123")

# Clean up session
delete_all_memories(run_id="session-123")

Performance Optimization

# Fast storage (no LLM inference)
store_memory(
    content="Completed: API refactoring - 30% faster response times",
    metadata={"type": "task_completion"},
    infer=False  # 5-10x faster
)

# Smart storage (with deduplication)
store_memory(
    content="User mentioned they prefer TypeScript for type safety",
    metadata={"type": "preference"},
    infer=True  # Extracts facts, prevents duplicates
)

# Compact response (default - saves tokens)
search_memories(query="React preferences", limit=5)
# Returns: {"memories": [{"id": "...", "memory": "...", "metadata": {...}}], "count": 5}

# Verbose response (full details)
search_memories(query="React preferences", limit=5, verbose=True)
# Returns: Full details including hash, timestamps, user_id, agent_id, etc.

Performance Tips

Storage Speed:

  • Use infer=false for 5-10x faster writes when you don't need deduplication

  • Use infer=true (default) for important information to prevent duplicates

Response Optimization:

  • Use verbose=false (default) for 55% token reduction per memory

  • Compact mode returns only: id, memory, metadata, score

  • Graph relations preserved and truncated to 20 in compact mode

  • Verbose mode returns all fields including timestamps, hashes, etc.

  • Set MEM0_VERBOSE=true globally or use verbose parameter per-call

  • Configure relations limit with MEM0_MAX_RELATIONS (default: 20)

Search Optimization:

  • FAISS uses L2 distance: lower scores = higher similarity

  • Adjust MEM0_MIN_RELEVANCE_SCORE to filter less relevant results

  • Use metadata filtering for precise queries

Backend Selection:

  • FAISS: Best for <100k memories, single-user, development

  • Qdrant: Best for metadata-heavy queries, production deployments

  • OpenSearch: Best for >100k memories, enterprise scale

LLM Provider:

  • Bedrock: Fastest with built-in optimizations, production-ready

  • Ollama: Good for local development, privacy-focused

  • LM Studio: Alternative local option with UI

Advanced Features

KuzuDB Graph Store (Experimental)

Track relationships between entities (people, companies, technologies) alongside vector embeddings. See docs/KUZU_GRAPH_STORE.md for details.

Known Limitations

  • Amazon Nova Models: Now fully compatible via bedrock_patch.py

  • Metadata Filtering: mem0 v1.0.x only supports implicit AND operations (flat dictionary)

  • Platform Features: Some features (custom_categories, expiration_date) only available in Mem0 Platform

For troubleshooting, see TROUBLESHOOTING.md

Contributing

Contributions are welcome! Please:

  1. Fork the repository

  2. Create a feature branch

  3. Submit a pull request

See CONTRIBUTING.md for guidelines.

Documentation

Citation

If you use this project in your research or work, please cite:

@software{selvam_mem0_agent_memory_2025,
  author = {Selvam, Arunkumar},
  title = {Mem0 Agent Memory - MCP Server},
  url = {https://github.com/arunkumars-mf/mem0-agent-memory},
  version = {1.3.0},
  year = {2025}
}

See CITATION.cff for more formats.

License

MIT License - see LICENSE for details.

Available Tools

18 tools
bulk_delete_memoriesA

Delete multiple memories matching filter criteria. PERMANENT deletion.

OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) OPTIONAL: 'run_id' - filter by session/run identifier OPTIONAL: 'metadata_type' - delete memories with this metadata type (e.g., "test", "note") OPTIONAL: 'older_than_days' - delete memories older than this many days OPTIONAL: 'dry_run' - if True, returns what would be deleted without actually deleting (default: True)

⚠️ WARNING: Set dry_run=False to actually delete. This cannot be undone.

Examples:

  • Preview test cleanup: {"metadata_type": "test", "dry_run": true}

  • Delete old memories: {"older_than_days": 90, "dry_run": false}

  • Delete by type: {"metadata_type": "note", "dry_run": false}

Returns: List of deleted (or would-be-deleted) memory IDs.

Inputs: run_id, dry_run, user_id, verbose, +3 more. Returns: result

delete_all_memoriesA

Delete all memories for a specific scope. PERMANENT deletion.

OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) OPTIONAL: 'run_id' - delete all memories for this session/run

⚠️ WARNING: This permanently removes ALL memories matching the scope. Cannot be undone.

Examples:

  • Delete all user memories: {"user_id": "john"}

  • Delete session memories: {"run_id": "session_123"}

Returns: Confirmation of deletion with count.

Inputs: run_id, user_id, verbose, agent_id. Returns: result

delete_memoryA

Delete memory by its unique ID. PERMANENT deletion.

REQUIRED: 'memory_id' - the UUID of the memory to delete

⚠️ WARNING: This permanently removes the memory and cannot be undone.

Inputs: memory_id (required), verbose. Returns: result

export_memoriesA

Export memories to JSON or Markdown format for backup or migration.

OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) OPTIONAL: 'format' - output format: "json" (default) or "markdown" OPTIONAL: 'include_metadata' - include metadata in export (default: True) OPTIONAL: 'output_path' - custom file path (default: .mem0/exports/memories_.) OPTIONAL: 'return_content' - if True, returns content instead of writing to file (default: False)

Returns: File path where export was saved, or content if return_content=True.

Use for: Backup, migration between backends, documentation, sharing.

Inputs: format, user_id, verbose, agent_id, +3 more. Returns: result

get_memoryA

Get specific memory by its unique ID.

REQUIRED: 'memory_id' - the UUID of the memory to retrieve

Returns: Complete memory details including content, metadata, timestamps.

Inputs: memory_id (required), verbose. Returns: result

get_memory_historyA

Get change history for a specific memory by ID.

REQUIRED: 'memory_id' - the UUID of the memory to get history for

Returns: Chronological list of all changes made to the memory.

Inputs: memory_id (required), verbose. Returns: result

get_memory_statsA

Get statistics about stored memories.

OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user)

Returns: Memory counts by metadata type, date ranges, and storage summary.

Use for: Understanding memory usage, identifying cleanup opportunities, monitoring growth.

Inputs: user_id, verbose, agent_id. Returns: result

get_recent_memoriesA

Get recently added or updated memories for session continuity.

OPTIONAL: 'days' - how many days back to search (default: 7) OPTIONAL: 'limit' - max memories to return (default: 10) OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) OPTIONAL: 'run_id' - filter by session/run identifier

Returns: Most recently added/updated memories sorted by newest first

Inputs: days, limit, run_id, user_id, +2 more. Returns: result

health_checkA

Check the health and connectivity of the memory backend.

Returns: Backend type, connection status, and basic diagnostics.

Use for: Troubleshooting connection issues, verifying configuration.

Inputs: no named parameters. Returns: result

import_memoriesA

Import memories from exported JSON file.

REQUIRED: 'file_path' - path to the JSON export file OPTIONAL: 'user_id' OR 'agent_id' - override the user/agent from the export file OPTIONAL: 'skip_existing' - if True, skip memories that already exist (default: True) OPTIONAL: 'infer' - use LLM processing during import (default: False for speed)

Imports memories from a JSON file created by export_memories tool. Useful for backup restoration, migration between backends, or sharing memory sets.

Examples:

  • Import from backup: {"file_path": ".mem0/exports/memories_john_20250113.json"}

  • Import to different user: {"file_path": "export.json", "user_id": "jane"}

  • Force reimport: {"file_path": "export.json", "skip_existing": false}

Returns: Import summary with success/failure counts.

Inputs: file_path (required), infer, user_id, verbose, +2 more. Returns: result

ingest_documentsA

Ingest documents into memory as a knowledge base using LlamaIndex.

Supports: PDF, DOCX, TXT, MD, HTML, and more. Automatically chunks and stores content.

REQUIRED: 'path' - file path or directory path to ingest OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) OPTIONAL: 'run_id' - session/run identifier for partitioning OPTIONAL: 'recursive' - recursively process subdirectories (default: False) OPTIONAL: 'chunk_size' - max characters per chunk (default: 1024, min: 100, max: 8192) OPTIONAL: 'chunk_overlap' - overlap between chunks (default: 200, min: 0, max: chunk_size-1) OPTIONAL: 'file_metadata' - additional metadata to attach to all chunks OPTIONAL: 'infer' - use LLM for fact extraction (default: False for speed)

Examples:

  • Ingest single file: {"path": "/path/to/document.pdf"}

  • Ingest directory: {"path": "/path/to/docs", "recursive": true}

  • With metadata: {"path": "manual.pdf", "file_metadata": {"type": "documentation", "version": "2.0"}}

  • Custom chunking: {"path": "large.pdf", "chunk_size": 2048, "chunk_overlap": 400}

Returns: Summary of ingested documents with chunk counts and memory IDs.

Inputs: path (required), infer, run_id, user_id, +6 more. Returns: result

list_memoriesA

List all memories for a user or agent with pagination.

OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) OPTIONAL: 'run_id' - filter by session/run identifier OPTIONAL: 'page', 'page_size' - pagination controls (default: page_size=25)

Returns: All memories belonging to the specified user/agent, sorted by creation date.

Inputs: page, run_id, user_id, verbose, +2 more. Returns: result

reset_memoryA

Reset the entire memory store. DESTRUCTIVE operation.

⚠️ CRITICAL WARNING: This deletes ALL memories in the backend, regardless of user/agent/app. Only use this for testing or when you need to completely clear the memory store.

This operation cannot be undone.

Returns: Confirmation of reset.

Inputs: no named parameters. Returns: result

search_by_metadataA

Search memories by metadata fields without semantic search.

OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) OPTIONAL: 'type' - filter by metadata type (e.g., "decision", "preference", "task_completion") OPTIONAL: 'priority' - filter by priority (e.g., "high", "medium", "low") OPTIONAL: 'status' - filter by status (e.g., "complete", "in_progress", "blocked") OPTIONAL: 'custom_filters' - dict of additional metadata key-value pairs to match OPTIONAL: 'page' - page number for pagination (default: 1) OPTIONAL: 'page_size' - results per page (default: 50, max: 100)

Returns: Memories matching all specified filters with pagination.

Examples:

  • Find decisions: {"type": "decision"}

  • Find high priority: {"priority": "high"}

  • Find blocked items: {"status": "blocked"}

  • Custom filter: {"custom_filters": {"category": "api"}}

  • Paginated: {"type": "documentation", "page": 2, "page_size": 20}

Note: Uses native Qdrant filtering when available, falls back to post-filtering for other backends.

Inputs: page, type, status, user_id, +5 more. Returns: result

search_memoriesA

Search memories with semantic similarity and relevance filtering.

REQUIRED: 'query' - what to search for (natural language) OPTIONAL: 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) OPTIONAL: 'run_id' - filter by session/run identifier OPTIONAL: 'limit' - max results to return (default: 10, also sets page_size if not specified) OPTIONAL: 'page' - page number for pagination (default: 1) OPTIONAL: 'page_size' - results per page (default: uses limit value)

Returns: Relevant memories filtered by maximum score threshold (configurable via MEM0_MAX_RELEVANCE_SCORE, default: 1000)

Score interpretation (FAISS uses L2 distance - lower is more similar):

  • 0-100: Very high similarity (near-exact matches)

  • 100-400: High similarity (closely related)

  • 400-600: Moderate similarity (somewhat related)

  • 600-1000: Low similarity (loosely related)

  • 1000+: Very low similarity (likely unrelated)

Note: Default threshold of 1000 keeps reasonably similar results. Lower to 400-600 for stricter filtering.

Examples:

  • Search user memories: {"query": "React patterns", "user_id": "john"}

  • Auto-detect user: {"query": "my project status"}

  • Limit results: {"query": "API endpoints", "limit": 3}

  • Session-scoped: {"query": "current task", "run_id": "session_123"}

  • Pagination: {"query": "all tasks", "page": 2, "page_size": 5}

Use for: Finding relevant code, recalling user preferences, retrieving project context.

Inputs: query (required), page, limit, run_id, +4 more. Returns: result

setup_steeringA

Setup the memory-first steering file for Kiro.

Creates a steering file at .kiro/steering/memory-first.md that instructs the AI to always check memory before starting tasks and store important outcomes.

OPTIONAL: 'workspace_path' - path to workspace root (default: current directory)

Call this once after adding the MCP server to enable memory-first workflows.

Returns: Success message with file path created.

Inputs: workspace_path. Returns: result

store_memoryA

Store memory content with metadata support.

REQUIRED: Either 'user_id' OR 'agent_id' (if neither provided, auto-detects current user) REQUIRED: 'content' - the information to remember

OPTIONAL: 'metadata' - structured data about the memory (JSON object) OPTIONAL: 'infer' - if True (default), uses LLM to extract facts and dedupe. Set False for faster raw storage. OPTIONAL: 'run_id' - session/run identifier for temporary context OPTIONAL: 'custom_instructions' - per-call instructions to control what gets stored OPTIONAL: 'verbose' - if True, return full details. If False (default), return compact response.

Examples:

  • Store personal info: {"content": "User prefers React over Vue", "user_id": "john"}

  • Store with metadata: {"content": "API endpoint changed", "metadata": {"type": "technical", "priority": "high"}}

  • Fast storage (no LLM): {"content": "Quick note", "infer": false}

  • Session-scoped: {"content": "Current task context", "run_id": "session_123"}

Use for: Storing code patterns, user preferences, project details, technical knowledge.

Note: With infer=True (default), mem0 uses an LLM to extract key facts and intelligently update existing memories. This is slower (~5-15s) but smarter. Use infer=False for faster raw storage (~1-2s) without deduplication.

Config: Set MEM0_INFER_DEFAULT=false in env to disable infer by default. Config: Set MEM0_VERBOSE=true in env to enable verbose responses by default.

Returns: Success message with memory ID (compact) or full details (verbose).

Inputs: content (required), infer, run_id, user_id, +4 more. Returns: result

update_memoryA

Update an existing memory's content and/or metadata directly.

REQUIRED: 'memory_id' - the UUID of the memory to update REQUIRED: 'content' - the new content for the memory

OPTIONAL: 'metadata' - new metadata to replace existing (JSON object)

Unlike store_memory with infer=true, this directly updates the specified memory without LLM processing or deduplication. Preserves memory history.

Examples:

  • Update content: {"memory_id": "abc-123", "content": "Updated preference: Vue over React"}

  • Update with metadata: {"memory_id": "abc-123", "content": "New content", "metadata": {"priority": "high"}}

Returns: Updated memory details.

Inputs: content (required), memory_id (required), verbose, metadata. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 18 tools

    Disambiguation4/5

    The tools are largely distinct, with clear separation between CRUD, semantic search, metadata search, bulk operations, and export/import. The main potential confusion is among the multiple deletion tools (delete_memory, delete_all_memories, bulk_delete_memories, reset_memory) and between list_memories and get_recent_memories, but the descriptions clarify scope well.

    Naming Consistency5/5

    Tool names consistently follow a verb_noun snake_case pattern, with plural nouns for collection operations and singular nouns for single-item operations. Minor outliers like health_check and setup_steering are still readable and do not break the overall convention.

    Tool Count4/5

    Eighteen tools is slightly above the ideal range, but each tool occupies a reasonable niche in a comprehensive memory-management workflow. The count feels justified given coverage of CRUD, search, bulk deletion, import/export, stats, history, ingestion, and health checks.

    Completeness5/5

    The tool surface covers the full memory lifecycle: create, read, update, delete, search, bulk operations, backup/restore, analytics, and history. No critical dead ends are apparent for the stated purpose of agent/assistant memory management.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers