mem0 Memory System
@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 unuserIdespecí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 unuserIdespecí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:
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
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-mcpConfigure 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 buildLuego, 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:
Reemplace
/absolute/path/to/mem0-mcp/con la ruta absoluta real a su repositorio clonadoUtilice el archivo
build/index.js, no el archivosrc/index.tsEl 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_idythresholdRequiere : 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 installConstruir el servidor:
npm run buildPara el desarrollo con reconstrucción automática ante cambios de archivos:
npm run watchDepuración 🐞
Dado que los servidores MCP se comunican a través de stdio, la depuración puede ser complicada. Aquí hay algunos enfoques:
Utilice el Inspector MCP : esta herramienta puede supervisar la comunicación del protocolo MCP:
npm run inspectorRegistro de la consola : al agregar registros de la consola, utilice siempre
console.error()en lugar deconsole.log()para evitar interferir con el protocolo MCPArchivos de entorno : utilice un archivo
.envpara 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 |
| objeto | Almacena contexto adicional sobre la memoria (p. ej., ubicación, hora, identificadores). Esto puede usarse para filtrar durante la recuperación. |
| cadena | Preferencias específicas para incluir en la memoria. |
| cadena | Preferencias específicas para excluir de la memoria. |
| booleano | Si inferir recuerdos o almacenar mensajes directamente (predeterminado: verdadero). |
| cadena | Versión de formato, ya sea v1.0 (predeterminada, obsoleta) o v1.1 (recomendada). |
| objeto | Lista de categorías con nombres y descripciones. |
| cadena | Pautas específicas del proyecto para el manejo y la organización de los recuerdos. |
| booleano | Si la memoria es inmutable (predeterminado: falso). |
| cadena | Cuando caducará la memoria (formato: AAAA-MM-DD). |
| cadena | ID de organización asociada a esta memoria. |
| cadena | ID del proyecto asociado a esta memoria. |
| 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 |
| objeto | Filtros complejos con operadores lógicos y condiciones de comparación |
| entero | Número de resultados principales a devolver (predeterminado: 10) |
| cadena[] | Campos específicos a incluir en la respuesta |
| booleano | Si desea reordenar los recuerdos (predeterminado: falso) |
| booleano | Si se debe buscar según palabras clave (predeterminado: falso) |
| booleano | Si desea filtrar los recuerdos (predeterminado: falso) |
| número | Umbral mínimo de similitud para los resultados (predeterminado: 0,3) |
| cadena | ID de organización para filtrar recuerdos |
| 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 |
| Coincide con cualquiera de los valores especificados |
| Mayor o igual que |
| Menor o igual a |
| Más que |
| Menos que |
| No es igual a |
| 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 nubeOPENAI_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 toolsadd_memoryC
Stores a piece of text as a memory in Mem0.
| Name | Required | Description | Default |
|---|---|---|---|
| agentId | No | Optional agent ID to associate with the memory (for cloud API). | |
| content | Yes | The text content to store as memory. | |
| metadata | No | Optional key-value metadata. | |
| sessionId | No | Optional session ID to associate with the memory. | |
| userId | Yes | User ID to associate with the memory. |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| agentId | No | Optional agent ID associated with the memory (for cloud API). | |
| memoryId | Yes | The unique ID of the memory to delete. | |
| sessionId | No | Optional session ID associated with the memory. | |
| userId | Yes | User ID associated with the memory. |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| agentId | No | Optional agent ID to filter search (for cloud API). | |
| filters | No | Optional key-value filters for metadata. | |
| query | Yes | The search query. | |
| sessionId | No | Optional session ID to filter search. | |
| threshold | No | Optional similarity threshold for results (for cloud API). | |
| userId | Yes | User ID to filter search. |
TDQS
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.
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.
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.
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.
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.
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.
3 tool updates
v1.0.0- First observed
add_memory - First observed
delete_memory - First observed
search_memory
TDQS
Scored across 3 tools
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.
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.
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.
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
Related MCP Connectors
An MCP memory server. One memory your agents share — across models, devices and apps.
One memory, every AI. A shared, user-owned markdown memory your AI clients read and write over MCP.
Persistent, portable memory for AI assistants — your private memory graph, from any MCP client.
Persistent memory for AI agents to retain, retrieve, and recall conversation context through MCP.
Related MCP Servers
- AlicenseNot gradedqualityAmaintenanceAn 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.3MIT
- AlicenseAqualityCmaintenanceA 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.973 PyPI1MIT
- AlicenseAqualityDmaintenanceAn 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.1824 PyPIMIT
- AlicenseNot gradedqualityDmaintenanceA portable MCP server providing a shared intelligent memory system for any MCP-compatible AI tool, enabling storage, retrieval, extraction, and governance of memories across sessions.10 npmMIT