Knowledge Graph Memory Server
Permite la memoria para Claude usando un grafo de conocimiento con búsqueda semántica difusa y almacenamiento persistente.
Documentación
Knowledge Graph Memory Server (desde el sitio oficial mejorado con Búsqueda Difusa)
Una implementación básica de memoria persistente que utiliza un grafo de conocimiento local. Esto permite que Claude recuerde información sobre el usuario entre chats. Esta versión ha sido mejorada con fuse.js para proporcionar capacidades de búsqueda semántica difusa.
Prompt de instrucción. (Añade esto a tu CLAUDE.md o cualquier otro archivo relacionado)
Here is an instruction guide for each tool, focusing on best practices for using the knowledge graph effectively.
### A Guide to Using Knowledge Graph Memory
This guide outlines best practices for interacting with your knowledge graph memory. Following these principles will help you build a clean, accurate, and useful memory over time. The core idea is to first **search** for what you know, then **act** to add, update, or remove information.
---
#### **`search_nodes`**
This is your primary tool for discovery. It performs a fuzzy search across all entity names, types, and observations to find relevant information.
* **Best Practice:** Always search before you create. To avoid creating duplicate entities (e.g., "Jane_Doe" when "Jane_Doe_Dev" already exists), start with a broad search to see what the graph already knows.
* **Invocation Tip:** Use conceptual queries. You don't need an exact name. A query like "project manager who likes dogs" will effectively search observations across all entities to find the best match. Review the returned `score` to understand the confidence of the match.
---
#### **`create_entities`**
Use this to establish a new person, place, organization, or concept as a node in your graph.
* **Storage Tip:** Choose a consistent and unique `name` for each entity (e.g., `FirstName_LastName`, `Project_Name`). This name is the permanent identifier.
* **Invocation Tip:** Create entities with a few core `observations` from the start. An entity is more useful when it's created with initial facts, such as "is a software engineer" or "founded in 2021".
---
#### **`add_observations`**
Use this to add new facts or attributes to an entity that already exists.
* **Storage Tip:** Keep observations atomic. Each observation should represent a single, discrete fact (e.g., use "Loves hiking" and "Lives in Colorado" as two separate observations, not one). This makes information easier to manage and remove later.
* **Invocation Tip:** This tool is for enriching existing entities. It will not add duplicate observations, so you can safely call it with a list of facts without worrying about creating redundant entries.
---
#### **`create_relations`**
This tool connects two existing entities with a directed, active-voice relationship (e.g., `Jane_Doe` -> `reports_to` -> `John_Smith`).
* **Storage Tip:** Ensure both the `from` and `to` entities already exist before creating a relation between them. A relation is meaningless without its nodes.
* **Invocation Tip:** Use a consistent vocabulary for `relationType` (e.g., always use `works_at`, not a mix of `works_at` and `employed_by`). This makes the graph structure predictable and easier to query.
---
#### **`open_nodes`**
Use this to retrieve one or more entities by their exact name, along with any relations that exist between them.
* **Best Practice:** Use this when you know the exact name of an entity and want to see its details and local connections. It's more precise than `search_nodes` for targeted lookups.
* **Invocation Tip:** Before updating or deleting, use `open_nodes` to inspect the entity and its relationships. This helps confirm you are targeting the correct information.
---
#### **`delete_observations`**
This tool removes specific facts from an entity.
* **Best Practice:** This is the standard way to update an entity when a fact is no longer true (e.g., removing "is learning Spanish" after proficiency is achieved).
* **Invocation Tip:** You must provide the *exact* text of the observation to be deleted. Use `open_nodes` first to retrieve the exact phrasing if you are unsure.
---
#### **`delete_relations`**
This tool removes a specific connection between two entities, leaving the entities themselves intact.
* **Best Practice:** Use this to update the graph when a relationship changes. For example, if a person moves to a new team, you would delete their old `reports_to` relation.
* **Invocation Tip:** To be successful, the call must exactly match the `from` entity, `to` entity, and `relationType` of the stored relation.
---
#### **`delete_entities`**
This is a destructive action that permanently removes an entity and all relations connected to it.
* **Best Practice:** Be certain before using this tool. Deleting an entity causes a cascading delete of all its connections. If you only want to remove an incorrect fact, use `delete_observations` instead.
* **Invocation Tip:** The tool will not fail if the entity doesn't exist, so you don't need to check for its existence before calling.
---
#### **`read_graph`**
This tool retrieves the entire knowledge graph—every entity and every relation.
* **Best Practice:** Use this tool sparingly, as it can return a very large amount of data. It is best suited for offline analysis, debugging, or getting a complete overview of your memory.
* **Invocation Tip:** For nearly all interactive tasks, prefer the more focused `search_nodes` or `open_nodes` tools for better performance and relevance.
Conceptos Fundamentales
Entidades
Las entidades son los nodos principales del grafo de conocimiento. Cada entidad tiene:
- Un nombre único (identificador)
- Un tipo de entidad (p. ej., "persona", "organización", "evento")
- Una lista de observaciones
Ejemplo:
{
"name": "John_Smith",
"entityType": "person",
"observations": ["Speaks fluent Spanish"]
}
Relaciones
Las relaciones definen conexiones dirigidas entre entidades. Siempre se almacenan en voz activa y describen cómo interactúan o se relacionan las entidades entre sí.
Ejemplo:
{
"from": "John_Smith",
"to": "Anthropic",
"relationType": "works_at"
}
Observaciones
Las observaciones son piezas discretas de información sobre una entidad. Son:
- Se almacenan como cadenas de texto
- Se adjuntan a entidades específicas
- Se pueden añadir o eliminar de forma independiente
- Deben ser atómicas (un dato por observación)
Ejemplo:
{
"entityName": "John_Smith",
"observations": [
"Speaks fluent Spanish",
"Graduated in 2019",
"Prefers morning meetings"
]
}
API
Herramientas
-
create_entities
- Crea múltiples entidades nuevas en el grafo de conocimiento
- Entrada:
entities(matriz de objetos)- Cada objeto contiene:
name(string): Identificador de la entidadentityType(string): Clasificación de tipoobservations(string[]): Observaciones asociadas
- Cada objeto contiene:
- Ignora entidades con nombres existentes
-
create_relations
- Crea múltiples relaciones nuevas entre entidades
- Entrada:
relations(matriz de objetos)- Cada objeto contiene:
from(string): Nombre de la entidad de origento(string): Nombre de la entidad de destinorelationType(string): Tipo de relación en voz activa
- Cada objeto contiene:
- Omite relaciones duplicadas
-
add_observations
- Añade nuevas observaciones a entidades existentes
- Entrada:
observations(matriz de objetos)- Cada objeto contiene:
entityName(string): Entidad de destinocontents(string[]): Nuevas observaciones a añadir
- Cada objeto contiene:
- Devuelve las observaciones añadidas por entidad
- Falla si la entidad no existe
-
delete_entities
- Elimina entidades y sus relaciones
- Entrada:
entityNames(string[]) - Eliminación en cascada de las relaciones asociadas
- Operación silenciosa si la entidad no existe
-
delete_observations
- Elimina observaciones específicas de entidades
- Entrada:
deletions(matriz de objetos)- Cada objeto contiene:
entityName(string): Entidad de destinoobservations(string[]): Observaciones a eliminar
- Cada objeto contiene:
- Operación silenciosa si la observación no existe
-
delete_relations
- Elimina relaciones específicas del grafo
- Entrada:
relations(matriz de objetos)- Cada objeto contiene:
from(string): Nombre de la entidad de origento(string): Nombre de la entidad de destinorelationType(string): Tipo de relación
- Cada objeto contiene:
- Operación silenciosa si la relación no existe
-
read_graph
- Lee el grafo de conocimiento completo
- No requiere entrada
- Devuelve la estructura completa del grafo con todas las entidades y relaciones
-
search_nodes
- Realiza una búsqueda semántica difusa de nodos en el grafo de conocimiento utilizando Fuse.js
- Entrada:
query(string) - Busca en:
- Nombres de entidades
- Tipos de entidades
- Contenido de observaciones
- Devuelve una matriz de resultados de búsqueda, cada uno con:
entity: El objeto de entidad coincidentescore: Puntuación de confianza de 0.0 a 1.0 (cuanto más alta, mejor)
- Utiliza coincidencia difusa con:
- Umbral: 0.6 (0.0 = coincidencia perfecta, 1.0 = coincide con cualquier cosa)
- Longitud mínima de caracteres de coincidencia: 2
- Coincidencia independiente de la ubicación
-
open_nodes
- Recupera nodos específicos por nombre
- Entrada:
names(string[]) - Devuelve:
- Entidades solicitadas
- Relaciones entre las entidades solicitadas
- Omite silenciosamente los nodos inexistentes
Uso con Claude Desktop
Configuración
Añade esto a tu claude_desktop_config.json:
NPX
{
"mcpServers": {
"memory": {
"command": "npx",
"args": [
"-y",
"github:flrngel/fuzzy-memory-mcp#main"
]
}
}
}
NPX con configuración personalizada
El servidor se puede configurar utilizando las siguientes variables de entorno:
{
"mcpServers": {
"memory": {
"command": "npx",
"args": [
"-y",
"github:flrngel/fuzzy-memory-mcp#main"
],
"env": {
"MEMORY_FILE_PATH": "/path/to/custom/memory.json"
}
}
}
}
MEMORY_FILE_PATH: Ruta al archivo JSON de almacenamiento de memoria (por defecto:memory.jsonen el directorio del servidor)
Instrucciones de instalación en VS Code
Para una instalación rápida, utiliza uno de los botones de instalación con un clic que aparecen a continuación:
Para la instalación manual, añade el siguiente bloque JSON a tu archivo de Configuración de Usuario (JSON) en VS Code. Puedes hacerlo pulsando Ctrl + Shift + P y escribiendo Preferences: Open Settings (JSON).
Opcionalmente, puedes añadirlo a un archivo llamado .vscode/mcp.json en tu espacio de trabajo. Esto te permitirá compartir la configuración con otras personas.
Ten en cuenta que la clave
mcpno es necesaria en el archivo.vscode/mcp.json.
NPX
{
"mcp": {
"servers": {
"memory": {
"command": "npx",
"args": [
"-y",
"github:flrngel/fuzzy-memory-mcp#main"
]
}
}
}
}
Prompt del sistema
El prompt para utilizar la memoria depende del caso de uso. Cambiar el prompt ayudará al modelo a determinar la frecuencia y los tipos de recuerdos creados.
Aquí tienes un ejemplo de prompt para la personalización del chat. Podrías utilizar este prompt en el campo "Instrucciones personalizadas" de un Proyecto de Claude.ai.
Follow these steps for each interaction:
1. User Identification:
- You should assume that you are interacting with default_user
- If you have not identified default_user, proactively try to do so.
2. Memory Retrieval:
- Always begin your chat by saying only "Remembering..." and retrieve all relevant information from your knowledge graph
- Always refer to your knowledge graph as your "memory"
3. Memory
- While conversing with the user, be attentive to any new information that falls into these categories:
a) Basic Identity (age, gender, location, job title, education level, etc.)
b) Behaviors (interests, habits, etc.)
c) Preferences (communication style, preferred language, etc.)
d) Goals (goals, targets, aspirations, etc.)
e) Relationships (personal and professional relationships up to 3 degrees of separation)
4. Memory Update:
- If any new information was gathered during the interaction, update your memory as follows:
a) Create entities for recurring organizations, people, and significant events
b) Connect them to the current entities using relations
b) Store facts about them as observations
Compilación y Desarrollo
Requisitos previos
- Node.js y npm
- Docker (para compilar la imagen de Docker)
Desarrollo local
Si has clonado este repositorio y quieres ejecutar el servidor localmente para desarrollo:
- Instala las dependencias (esto incluirá
fuse.jspara la búsqueda difusa):npm install - Compila y ejecuta el servidor:
npm start
Compilación de la imagen de Docker
El Dockerfile se encarga de instalar todas las dependencias necesarias.
docker build -t mcp/memory .
Licencia
Este servidor MCP está licenciado bajo la Licencia MIT. Esto significa que eres libre de usar, modificar y distribuir el software, sujeto a los términos y condiciones de la Licencia MIT. Para más detalles, consulta el archivo LICENSE en el repositorio del proyecto.