Knowledge Graph Memory Server
Permite memória para Claude usando um grafo de conhecimento com busca semântica difusa e armazenamento persistente.
Documentação
Knowledge Graph Memory Server (do site oficial aprimorado com Fuzzy Search)
Uma implementação básica de memória persistente usando um grafo de conhecimento local. Isso permite que o Claude lembre informações sobre o usuário entre conversas. Esta versão foi aprimorada com fuse.js para fornecer capacidades de busca difusa e semântica.
Prompt de instrução. (Adicione isto ao seu CLAUDE.md ou qualquer outro 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.
Conceitos Principais
Entidades
Entidades são os nós primários no grafo de conhecimento. Cada entidade possui:
- Um nome único (identificador)
- Um tipo de entidade (ex.: "pessoa", "organização", "evento")
- Uma lista de observações
Exemplo:
{
"name": "John_Smith",
"entityType": "person",
"observations": ["Speaks fluent Spanish"]
}
Relações
Relações definem conexões direcionadas entre entidades. Elas são sempre armazenadas em voz ativa e descrevem como as entidades interagem ou se relacionam entre si.
Exemplo:
{
"from": "John_Smith",
"to": "Anthropic",
"relationType": "works_at"
}
Observações
Observações são informações discretas sobre uma entidade. Elas são:
- Armazenadas como strings
- Anexadas a entidades específicas
- Podem ser adicionadas ou removidas independentemente
- Devem ser atômicas (um fato por observação)
Exemplo:
{
"entityName": "John_Smith",
"observations": [
"Speaks fluent Spanish",
"Graduated in 2019",
"Prefers morning meetings"
]
}
API
Ferramentas
-
create_entities
- Cria múltiplas novas entidades no grafo de conhecimento
- Entrada:
entities(array de objetos)- Cada objeto contém:
name(string): Identificador da entidadeentityType(string): Classificação de tipoobservations(string[]): Observações associadas
- Cada objeto contém:
- Ignora entidades com nomes existentes
-
create_relations
- Cria múltiplas novas relações entre entidades
- Entrada:
relations(array de objetos)- Cada objeto contém:
from(string): Nome da entidade de origemto(string): Nome da entidade de destinorelationType(string): Tipo de relacionamento em voz ativa
- Cada objeto contém:
- Ignora relações duplicadas
-
add_observations
- Adiciona novas observações a entidades existentes
- Entrada:
observations(array de objetos)- Cada objeto contém:
entityName(string): Entidade de destinocontents(string[]): Novas observações a adicionar
- Cada objeto contém:
- Retorna as observações adicionadas por entidade
- Falha se a entidade não existir
-
delete_entities
- Remove entidades e suas relações
- Entrada:
entityNames(string[]) - Exclusão em cascata das relações associadas
- Operação silenciosa se a entidade não existir
-
delete_observations
- Remove observações específicas de entidades
- Entrada:
deletions(array de objetos)- Cada objeto contém:
entityName(string): Entidade de destinoobservations(string[]): Observações a remover
- Cada objeto contém:
- Operação silenciosa se a observação não existir
-
delete_relations
- Remove relações específicas do grafo
- Entrada:
relations(array de objetos)- Cada objeto contém:
from(string): Nome da entidade de origemto(string): Nome da entidade de destinorelationType(string): Tipo de relacionamento
- Cada objeto contém:
- Operação silenciosa se a relação não existir
-
read_graph
- Lê o grafo de conhecimento inteiro
- Nenhuma entrada necessária
- Retorna a estrutura completa do grafo com todas as entidades e relações
-
search_nodes
- Realiza uma busca semântica difusa por nós no grafo de conhecimento usando Fuse.js
- Entrada:
query(string) - Busca em:
- Nomes de entidades
- Tipos de entidades
- Conteúdo das observações
- Retorna um array de resultados de busca, cada um contendo:
entity: O objeto de entidade correspondentescore: Pontuação de confiança de 0.0 a 1.0 (quanto maior, melhor)
- Usa correspondência difusa com:
- Limite: 0.6 (0.0 = correspondência perfeita, 1.0 = corresponde a qualquer coisa)
- Comprimento mínimo de caracteres para correspondência: 2
- Correspondência independente de localização
-
open_nodes
- Recupera nós específicos pelo nome
- Entrada:
names(string[]) - Retorna:
- Entidades solicitadas
- Relações entre as entidades solicitadas
- Ignora silenciosamente nós inexistentes
Uso com Claude Desktop
Configuração
Adicione isto ao seu arquivo claude_desktop_config.json:
NPX
{
"mcpServers": {
"memory": {
"command": "npx",
"args": [
"-y",
"github:flrngel/fuzzy-memory-mcp#main"
]
}
}
}
NPX com configuração personalizada
O servidor pode ser configurado usando as seguintes variáveis de ambiente:
{
"mcpServers": {
"memory": {
"command": "npx",
"args": [
"-y",
"github:flrngel/fuzzy-memory-mcp#main"
],
"env": {
"MEMORY_FILE_PATH": "/path/to/custom/memory.json"
}
}
}
}
MEMORY_FILE_PATH: Caminho para o arquivo JSON de armazenamento de memória (padrão:memory.jsonno diretório do servidor)
Instruções de Instalação no VS Code
Para instalação rápida, use um dos botões de instalação com um clique abaixo:
Para instalação manual, adicione o seguinte bloco JSON ao seu arquivo User Settings (JSON) no VS Code. Você pode fazer isso pressionando Ctrl + Shift + P e digitando Preferences: Open Settings (JSON).
Opcionalmente, você pode adicioná-lo a um arquivo chamado .vscode/mcp.json no seu workspace. Isso permitirá que você compartilhe a configuração com outras pessoas.
Observe que a chave
mcpnão é necessária no arquivo.vscode/mcp.json.
NPX
{
"mcp": {
"servers": {
"memory": {
"command": "npx",
"args": [
"-y",
"github:flrngel/fuzzy-memory-mcp#main"
]
}
}
}
}
Prompt do Sistema
O prompt para utilizar a memória depende do caso de uso. Alterar o prompt ajuda o modelo a determinar a frequência e os tipos de memórias criadas.
Aqui está um exemplo de prompt para personalização de chat. Você pode usar este prompt no campo "Custom Instructions" de um Projeto 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
Compilação e Desenvolvimento
Pré-requisitos
- Node.js e npm
- Docker (para compilar a imagem Docker)
Desenvolvimento Local
Se você clonou este repositório e deseja executar o servidor localmente para desenvolvimento:
- Instale as dependências (isso incluirá
fuse.jspara busca difusa):npm install - Compile e execute o servidor:
npm start
Compilando a Imagem Docker
O Dockerfile cuida da instalação de todas as dependências necessárias.
docker build -t mcp/memory .
Licença
Este servidor MCP é licenciado sob a Licença MIT. Isso significa que você é livre para usar, modificar e distribuir o software, sujeito aos termos e condições da Licença MIT. Para mais detalhes, consulte o arquivo LICENSE no repositório do projeto.