Skip to main content
Glama

Logotipo de Mem0

@pinkpixel/mem0-mcp Servidor MCP ✨

Un servidor de Protocolo de Contexto de Modelo (MCP) que se integra con Mem0.ai para proporcionar memoria persistente a los LLM. Permite a los agentes de IA almacenar y recuperar información entre sesiones.

Este servidor utiliza el SDK Node.js mem0ai para su funcionalidad principal.

Características 🧠

Herramientas

  • add_memory : almacena un fragmento de contenido de texto como una memoria asociada con un userId específico.

    • Entrada: content (cadena, obligatorio), userId (cadena, obligatorio), sessionId (cadena, opcional), agentId (cadena, opcional), metadata (objeto, opcional)

    • Almacena el texto proporcionado, lo que permite recuperarlo en interacciones futuras.

  • search_memory : busca memorias almacenadas basándose en una consulta en lenguaje natural para un userId específico.

    • Entrada: query (cadena, obligatoria), userId (cadena, obligatoria), sessionId (cadena, opcional), agentId (cadena, opcional), filters (objeto, opcional), threshold (número, opcional)

    • Recupera recuerdos relevantes basándose en la similitud semántica.

  • delete_memory : elimina una memoria específica del almacenamiento por su ID.

    • Entrada: memoryId (cadena, obligatoria), userId (cadena, obligatoria), sessionId (cadena, opcional), agentId (cadena, opcional)

    • Elimina permanentemente la memoria especificada.

    • Recupera recuerdos relevantes basándose en la similitud semántica.

Related MCP server: mindcore-memory-mcp

Prerrequisitos 🔑

Este servidor admite dos modos de almacenamiento:

  1. Modo de almacenamiento en la nube ☁️ (Recomendado)

    • Requiere una clave API Mem0 (proporcionada como variable de entorno MEM0_API_KEY )

    • Los recuerdos se almacenan de forma persistente en los servidores en la nube de Mem0

    • No se necesita base de datos local

  2. Modo de almacenamiento local 💾

    • Requiere una clave API de OpenAI (proporcionada como variable de entorno OPENAI_API_KEY )

    • Las memorias se almacenan en una base de datos vectorial en memoria (no persistente de forma predeterminada)

    • Los datos se pierden cuando el servidor se reinicia a menos que esté configurado para almacenamiento persistente

Instalación y configuración ⚙️

Puedes ejecutar este servidor de dos formas principales:

1. Uso de npx (recomendado para un uso rápido)

Instale el paquete globalmente usando npm:

npm install -g @pinkpixel/mem0-mcp

Configure su cliente MCP (por ejemplo, Claude Desktop, Cursor, Cline, Roo Code, etc.) para ejecutar el servidor usando npx :

Configuración de almacenamiento en la nube (recomendado)

{
  "mcpServers": {
    "mem0-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@pinkpixel/mem0-mcp"
      ],
      "env": {
        "MEM0_API_KEY": "YOUR_MEM0_API_KEY_HERE",
        "DEFAULT_USER_ID": "user123"
      },
      "disabled": false,
      "alwaysAllow": [
        "add_memory",
        "search_memory"
      ]
    }
  }
}

Nota: Reemplace "YOUR_MEM0_API_KEY_HERE" con su clave API Mem0 real.

Configuración de almacenamiento local (alternativa)

{
  "mcpServers": {
    "mem0-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@pinkpixel/mem0-mcp"
      ],
      "env": {
        "OPENAI_API_KEY": "YOUR_OPENAI_API_KEY_HERE",
        "DEFAULT_USER_ID": "user123"
      },
      "disabled": false,
      "alwaysAllow": [
        "add_memory",
        "search_memory"
      ]
    }
  }
}

Nota: Reemplace "YOUR_OPENAI_API_KEY_HERE" con su clave API de OpenAI real.

2. Ejecución desde un repositorio clonado

Nota: este método requiere que primero clones el repositorio.

Clonar el repositorio, instalar las dependencias y compilar el servidor:

git clone https://github.com/pinkpixel-dev/mem0-mcp 
cd mem0-mcp
npm install
npm run build

Luego, configure su cliente MCP para ejecutar el script creado directamente usando node :

{
  "mcpServers": {
    "mem0-mcp": {
      "command": "node",
      "args": [
        "/absolute/path/to/mem0-mcp/build/index.js" 
      ],
      "env": {
        "MEM0_API_KEY": "YOUR_MEM0_API_KEY_HERE",
        "DEFAULT_USER_ID": "user123"
        // OR use "OPENAI_API_KEY": "YOUR_OPENAI_API_KEY_HERE" for local storage
      },
      "disabled": false,
      "alwaysAllow": [
        "add_memory",
        "search_memory"
      ]
    }
  }
}

Notas importantes:

  1. Reemplace /absolute/path/to/mem0-mcp/ con la ruta absoluta real a su repositorio clonado

  2. Utilice el archivo build/index.js , no el archivo src/index.ts

  3. El servidor MCP requiere una salida estándar limpia para la comunicación del protocolo: cualquier biblioteca o código que escriba en la salida estándar puede interferir con el protocolo.

ID de usuario predeterminado (respaldo opcional)

Tanto las herramientas add_memory como search_memory requieren un argumento userId para asociar memorias con un usuario específico.

Para mayor comodidad durante las pruebas o en escenarios de un solo usuario, puede configurar opcionalmente la variable de entorno DEFAULT_USER_ID al iniciar el servidor. Si esta variable está configurada y se omite el argumento userId al llamar a la herramienta search_memory , el servidor usará el valor de DEFAULT_USER_ID para la búsqueda.

Nota: Si bien existe esta alternativa, generalmente se recomienda que el agente que llama (LLM) proporcione explícitamente el userId correcto tanto para agregar como para buscar memorias para evitar ambigüedades.

Ejemplo de configuración utilizando DEFAULT_USER_ID :

{
  "mcpServers": {
    "mem0-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "@pinkpixel/mem0-mcp"
      ],
      "env": {
        "MEM0_API_KEY": "YOUR_MEM0_API_KEY_HERE",
        "DEFAULT_USER_ID": "user123" 
      },
    }
  }
}

O cuando se ejecuta directamente con node :

git clone https://github.com/pinkpixel-dev/mem0-mcp 
cd mem0-mcp
npm install
npm run build
{
  "mcpServers": {
    "mem0-mcp": {
      "command": "node",
      "args": [
        "path/to/mem0-mcp/build/index.js"
      ],
      "env": {
        "OPENAI_API_KEY": "YOUR_OPENAI_API_KEY_HERE",
        "DEFAULT_USER_ID": "user123" 
      },
    }
  }
}

Almacenamiento en la nube vs. almacenamiento local 🔄

Almacenamiento en la nube (API Mem0)

  • Persistente de forma predeterminada : sus recuerdos permanecen disponibles en todas las sesiones y reinicios del servidor.

  • No se requiere base de datos local : todos los datos se almacenan en los servidores de Mem0

  • Mayor calidad de recuperación : utiliza los algoritmos de búsqueda optimizados de Mem0

  • Campos adicionales : admite parámetros agent_id y threshold

  • Requiere : una clave API Mem0

Almacenamiento local (API de OpenAI)

  • En memoria por defecto : los datos se almacenan únicamente en la RAM y no son persistentes a largo plazo . Si bien puede haber almacenamiento en caché, no debe confiar en él para el almacenamiento permanente.

  • Riesgo de pérdida de datos : los datos de la memoria se perderán al reiniciar el servidor, el sistema o si se finaliza el proceso.

  • Recomendado para : desarrollo, pruebas o uso temporal únicamente

  • Para almacenamiento persistente : utilice la opción de almacenamiento en la nube con API Mem0 si necesita una memoria a largo plazo confiable

  • Utiliza incrustaciones de OpenAI : para la funcionalidad de búsqueda de vectores

  • Autónomo : todos los datos permanecen en su máquina

  • Requiere : una clave API de OpenAI

Desarrollo 💻

Clonar el repositorio e instalar las dependencias:

git clone https://github.com/pinkpixel-dev/mem0-mcp 
cd mem0-mcp
npm install

Construir el servidor:

npm run build

Para el desarrollo con reconstrucción automática ante cambios de archivos:

npm run watch

Depuración 🐞

Dado que los servidores MCP se comunican a través de stdio, la depuración puede ser complicada. Aquí hay algunos enfoques:

  1. Utilice el Inspector MCP : esta herramienta puede supervisar la comunicación del protocolo MCP:

npm run inspector
  1. Registro de la consola : al agregar registros de la consola, utilice siempre console.error() en lugar de console.log() para evitar interferir con el protocolo MCP

  2. Archivos de entorno : utilice un archivo .env para el desarrollo local para simplificar la configuración de claves API y otras opciones de configuración

Notas técnicas de implementación 🔧

Parámetros avanzados de la API Mem0

Al usar el modo de almacenamiento en la nube con la API Mem0, puede aprovechar parámetros adicionales para una gestión de memoria más sofisticada. Aunque no se exponen explícitamente en el esquema de la herramienta, estos pueden incluirse en el objeto metadata al agregar memorias:

Parámetros avanzados para add_memory :

Parámetro

Tipo

Descripción

metadata

objeto

Almacena contexto adicional sobre la memoria (p. ej., ubicación, hora, identificadores). Esto puede usarse para filtrar durante la recuperación.

includes

cadena

Preferencias específicas para incluir en la memoria.

excludes

cadena

Preferencias específicas para excluir de la memoria.

infer

booleano

Si inferir recuerdos o almacenar mensajes directamente (predeterminado: verdadero).

output_format

cadena

Versión de formato, ya sea v1.0 (predeterminada, obsoleta) o v1.1 (recomendada).

custom_categories

objeto

Lista de categorías con nombres y descripciones.

custom_instructions

cadena

Pautas específicas del proyecto para el manejo y la organización de los recuerdos.

immutable

booleano

Si la memoria es inmutable (predeterminado: falso).

expiration_date

cadena

Cuando caducará la memoria (formato: AAAA-MM-DD).

org_id

cadena

ID de organización asociada a esta memoria.

project_id

cadena

ID del proyecto asociado a esta memoria.

version

cadena

Versión de memoria (v1 está obsoleta, se recomienda v2 para nuevas aplicaciones).

Para usar estos parámetros con el servidor MCP, inclúyalos en su objeto de metadatos al llamar a la herramienta add_memory . Por ejemplo:

{
  "content": "Important information to remember",
  "userId": "user123",
  "sessionId": "project-abc",
  "metadata": {
    "includes": "important context",
    "excludes": "sensitive data",
    "immutable": true,
    "expiration_date": "2025-12-31",
    "custom_instructions": "Prioritize this memory for financial questions",
    "version": "v2"
  }
}

Parámetros avanzados para search_memory :

La API de búsqueda Mem0 v2 ofrece potentes capacidades de filtrado que se pueden utilizar a través del parámetro filters :

Parámetro

Tipo

Descripción

filters

objeto

Filtros complejos con operadores lógicos y condiciones de comparación

top_k

entero

Número de resultados principales a devolver (predeterminado: 10)

fields

cadena[]

Campos específicos a incluir en la respuesta

rerank

booleano

Si desea reordenar los recuerdos (predeterminado: falso)

keyword_search

booleano

Si se debe buscar según palabras clave (predeterminado: falso)

filter_memories

booleano

Si desea filtrar los recuerdos (predeterminado: falso)

threshold

número

Umbral mínimo de similitud para los resultados (predeterminado: 0,3)

org_id

cadena

ID de organización para filtrar recuerdos

project_id

cadena

ID de proyecto para filtrar recuerdos

El parámetro filters admite operaciones lógicas complejas (AND, OR) y varios operadores de comparación:

Operador

Descripción

in

Coincide con cualquiera de los valores especificados

gte

Mayor o igual que

lte

Menor o igual a

gt

Más que

lt

Menos que

ne

No es igual a

icontains

Comprobación de contención sin distinción entre mayúsculas y minúsculas

Ejemplo de uso de filtros complejos con la herramienta search_memory :

{
  "query": "What are Alice's hobbies?",
  "userId": "user123",
  "filters": {
    "AND": [
      {
        "user_id": "alice"
      },
      {
        "agent_id": {"in": ["travel-agent", "sports-agent"]}
      }
    ]
  },
  "threshold": 0.5,
  "top_k": 5
}

Esto buscaría recuerdos relacionados con los pasatiempos de Alice donde el user_id es "alice" Y el agent_id es "travel-agent" O "sports-agent", devolviendo como máximo 5 resultados con un puntaje de similitud de al menos 0,5.

Para obtener información más detallada sobre estos parámetros, consulte la documentación de la API de Mem0 .

SafeLogger

El servidor MCP implementa una clase SafeLogger que redirige selectivamente las llamadas console.log desde la biblioteca mem0ai a stderr sin interrumpir el protocolo MCP:

  • Intercepta llamadas de console.log y examina los seguimientos de la pila para determinar la fuente

  • Solo redirecciona llamadas de registro desde la biblioteca mem0ai o nuestro propio código

  • Conserva la salida estándar limpia para la comunicación del protocolo MCP

  • Limpia automáticamente los recursos al salir del proceso

Esto permite el funcionamiento adecuado dentro de los clientes MCP manteniendo información de depuración útil.

Variables de entorno

El servidor reconoce varias variables de entorno que controlan su comportamiento:

  • MEM0_API_KEY : Clave API para el modo de almacenamiento en la nube

  • OPENAI_API_KEY : Clave API para el modo de almacenamiento local (incrustaciones)

  • DEFAULT_USER_ID : ID de usuario predeterminado para operaciones de memoria


Hecho con ❤️ por Pink Pixel

Available Tools

3 tools
add_memoryC

Stores a piece of text as a memory in Mem0.

ParametersJSON Schema
NameRequiredDescriptionDefault
agentIdNoOptional agent ID to associate with the memory (for cloud API).
contentYesThe text content to store as memory.
metadataNoOptional key-value metadata.
sessionIdNoOptional session ID to associate with the memory.
userIdYesUser ID to associate with the memory.

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool stores text as memory but doesn't mention whether this is a write operation (implied), what permissions are needed, how the memory is persisted, rate limits, or what happens on success/failure. This is inadequate for a mutation tool with zero annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that gets straight to the point with zero wasted words. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a mutation tool with no annotations and no output schema, the description is insufficient. It doesn't explain what the tool returns, error conditions, or behavioral nuances like idempotency. Given the complexity (5 parameters including nested objects) and lack of structured coverage, more context is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents all 5 parameters. The description doesn't add any parameter-specific details beyond what's in the schema (e.g., it doesn't explain format constraints or usage examples). Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Stores') and resource ('a piece of text as a memory in Mem0'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'delete_memory' or 'search_memory' beyond the obvious verb difference, which prevents a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'search_memory' or 'delete_memory'. It doesn't mention prerequisites, typical use cases, or exclusions, leaving the agent to infer usage from the tool name alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

delete_memoryC

Deletes a specific memory from Mem0 by ID.

ParametersJSON Schema
NameRequiredDescriptionDefault
agentIdNoOptional agent ID associated with the memory (for cloud API).
memoryIdYesThe unique ID of the memory to delete.
sessionIdNoOptional session ID associated with the memory.
userIdYesUser ID associated with the memory.

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool deletes a memory, implying a destructive operation, but doesn't cover critical aspects like permissions needed, whether deletion is permanent or reversible, rate limits, or error handling. This leaves significant gaps for a mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence with zero waste—it directly states the tool's function without unnecessary words. It's appropriately sized and front-loaded, making it highly efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (a destructive operation with 4 parameters) and lack of annotations and output schema, the description is insufficient. It doesn't explain behavioral traits, return values, or usage context, leaving the agent with incomplete information for safe and effective invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, so all parameters are documented in the input schema. The description mentions 'by ID', which aligns with the 'memoryId' parameter but doesn't add meaningful semantic context beyond what the schema already provides. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Deletes') and resource ('a specific memory from Mem0 by ID'), making the purpose unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'add_memory' or 'search_memory' beyond the obvious verb difference, which is why it doesn't reach a 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'search_memory' or 'add_memory', nor does it mention prerequisites or exclusions. It's a straightforward statement of function without contextual usage advice.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_memoryC

Searches stored memories in Mem0 based on a query.

ParametersJSON Schema
NameRequiredDescriptionDefault
agentIdNoOptional agent ID to filter search (for cloud API).
filtersNoOptional key-value filters for metadata.
queryYesThe search query.
sessionIdNoOptional session ID to filter search.
thresholdNoOptional similarity threshold for results (for cloud API).
userIdYesUser ID to filter search.

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It only states the basic action of searching without detailing aspects like whether it's read-only (implied but not explicit), potential side effects, rate limits, authentication needs, or what the search returns. This leaves significant gaps for a tool with multiple parameters and no output schema.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without any fluff or redundancy. It's appropriately sized and front-loaded, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (6 parameters, no output schema, and no annotations), the description is insufficient. It lacks details on behavioral traits, return values, or how to interpret results, leaving the agent with incomplete information to use the tool effectively in context with its siblings.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description mentions 'based on a query,' which aligns with the 'query' parameter, but adds no additional meaning beyond what the schema provides. With 100% schema description coverage, the baseline is 3, as the schema already documents all parameters well, and the description doesn't compensate with extra context or examples.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('searches') and resource ('stored memories in Mem0'), making the purpose understandable. However, it doesn't differentiate from sibling tools like 'add_memory' or 'delete_memory' beyond the basic verb difference, missing specific scope or functional distinctions that would warrant a 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives, such as how it differs from 'add_memory' or 'delete_memory' in practice, nor does it mention any prerequisites or exclusions. It's a generic statement that offers no contextual usage advice.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

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

  1. 3 tool updatesv1.0.0
    • First observedadd_memory
    • First observeddelete_memory
    • First observedsearch_memory

TDQS

B3.3/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: add_memory stores new data, delete_memory removes by ID, and search_memory retrieves based on queries. There is no overlap or ambiguity between these three core operations.

Naming Consistency5/5

All tools follow a consistent verb_noun pattern (add_memory, delete_memory, search_memory) with snake_case throughout. The naming is predictable and uniform across the set.

Tool Count3/5

With only 3 tools, the set feels minimal for a memory system. While it covers basic CRUD operations (create, delete, read), it lacks update functionality and other potential features like listing or managing memory collections, making it borderline thin for the domain.

Completeness4/5

The tools provide essential CRUD coverage (add, delete, search) for a memory system, but there are minor gaps such as no update_memory tool to modify existing memories and no way to list all memories without a query. Agents can work around this by deleting and re-adding, but it's not ideal.

Maintenance

ActivityInactive
ResponsivenessUnresponsive

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    A
    maintenance
    An MCP-native, local-first memory server that gives AI agents persistent, structured memory across sessions and tools, enabling them to maintain identity and context without reconfiguration.
    3
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    A production-grade long-term memory MCP server that enables AI agents to persist and recall memories across sessions with importance weighting, confidence calibration, and efficient context window management.
    9
    73 PyPI
    1
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    An MCP server that provides persistent memory capabilities for AI agents using Mem0, enabling storage, search, and management of contextual information across conversations with support for multiple backends and LLM providers.
    18
    24 PyPI
    MIT