Skip to main content
Glama
mcp-knowledge-graph

mcp-knowledge-graph

mcp-knowledge-graph

Сервер памяти графа знаний

Улучшенная реализация постоянной памяти с использованием локального графа знаний с настраиваемым --memory-path .

Это позволяет моделям ИИ запоминать информацию о пользователе в чатах. Это работает с любой моделью ИИ, которая поддерживает протокол контекста модели (MCP) или возможности вызова функций.

[!ПРИМЕЧАНИЕ] Это ответвление оригинального сервера памяти , и оно не предназначено для использования метода установки эфемерной памяти npx.

Имя сервера

mcp-knowledge-graph

экран-имени-сервера

функция чтения

Related MCP server: Knowledge Graph Memory Server

Основные концепции

Сущности

Сущности являются основными узлами в графе знаний. Каждая сущность имеет:

  • Уникальное имя (идентификатор)

  • Тип сущности (например, «лицо», «организация», «событие»)

  • Список наблюдений

Пример:

{
  "name": "John_Smith",
  "entityType": "person",
  "observations": ["Speaks fluent Spanish"]
}

Отношения

Отношения определяют направленные связи между сущностями. Они всегда хранятся в активном залоге и описывают, как сущности взаимодействуют или относятся друг к другу.

Пример:

{
  "from": "John_Smith",
  "to": "ExampleCorp",
  "relationType": "works_at"
}

Наблюдения

Наблюдения — это отдельные фрагменты информации о сущности. Они:

  • Сохраняется как строки

  • Прикреплено к определенным субъектам

  • Могут быть добавлены или удалены независимо друг от друга.

  • Должен быть атомарным (один факт на наблюдение)

Пример:

{
  "entityName": "John_Smith",
  "observations": [
    "Speaks fluent Spanish",
    "Graduated in 2019",
    "Prefers morning meetings"
  ]
}

API

Инструменты

  • создать_сущности

    • Создайте несколько новых сущностей в графе знаний

    • Входные данные: entities (массив объектов)

      • Каждый объект содержит:

        • name (строка): Идентификатор сущности

        • entityType (строка): Классификация типов

        • observations (string[]): Связанные наблюдения

    • Игнорирует сущности с существующими именами

  • создать_отношения

    • Создать несколько новых отношений между сущностями

    • Вход: relations (массив объектов)

      • Каждый объект содержит:

        • from (string): Имя исходной сущности

        • to (строка): Имя целевого объекта

        • relationType (строка): Тип отношений в активном залоге

    • Пропускает дублирующиеся отношения

  • добавить_наблюдения

    • Добавить новые наблюдения к существующим сущностям

    • Вход: observations (массив объектов)

      • Каждый объект содержит:

        • entityName (строка): Целевая сущность

        • contents (string[]): Новые наблюдения для добавления

    • Возвращает добавленные наблюдения для каждой сущности

    • Не удается, если объект не существует

  • удалить_сущности

    • Удалить сущности и их связи

    • Ввод: entityNames (string[])

    • Каскадное удаление связанных отношений

    • Тихая операция, если объект не существует

  • удалить_наблюдения

    • Удалить определенные наблюдения из сущностей

    • Вход: deletions (массив объектов)

      • Каждый объект содержит:

        • entityName (строка): Целевая сущность

        • observations (string[]): Наблюдения для удаления

    • Бесшумная работа, если нет наблюдения

  • удалить_отношения

    • Удалить определенные отношения из графика

    • Вход: relations (массив объектов)

      • Каждый объект содержит:

        • from (string): Имя исходной сущности

        • to (строка): Имя целевого объекта

        • relationType (строка): Тип отношения

    • Тихая операция, если связь не существует

  • читать_граф

    • Прочитать всю схему знаний

    • Ввод не требуется

    • Возвращает полную структуру графа со всеми сущностями и отношениями

  • поисковые_узлы

    • Поиск узлов на основе запроса

    • Ввод: query (строка)

    • Поиск по:

      • Имена сущностей

      • Типы сущностей

      • Содержание наблюдения

    • Возвращает соответствующие сущности и их отношения

  • открытые_узлы

    • Извлечь определенные узлы по имени

    • Ввод: names (string[])

    • Возврат:

      • Запрошенные сущности

      • Отношения между запрашиваемыми субъектами

    • Пропускает несуществующие узлы без уведомления

Использование с платформами, совместимыми с MCP

Этот сервер можно использовать с любой платформой искусственного интеллекта, которая поддерживает протокол контекста модели (MCP) или возможности вызова функций, включая Claude, GPT, Llama и другие.

Настройка с помощью Claude Desktop

Добавьте это в ваш claude_desktop_config.json:

{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-knowledge-graph",
        "--memory-path",
        "/Users/shaneholloman/Dropbox/shane/db/memory.jsonl"
      ],
      "autoapprove": [
        "create_entities",
        "create_relations",
        "add_observations",
        "delete_entities",
        "delete_observations",
        "delete_relations",
        "read_graph",
        "search_nodes",
        "open_nodes"
      ]
    },
  }
}

Настройка с другими платформами ИИ

Любая платформа ИИ, поддерживающая вызов функций или стандарт MCP, может подключиться к этому серверу. Конкретная конфигурация будет зависеть от платформы, но сервер предоставляет стандартные инструменты через интерфейс MCP.

Пользовательский путь памяти

Вы можете указать собственный путь для файла памяти:

{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-knowledge-graph",
        "--memory-path",
        "/Users/shaneholloman/Dropbox/shane/db/memory.jsonl"
      ],
      "autoapprove": [
        "create_entities",
        "create_relations",
        "add_observations",
        "delete_entities",
        "delete_observations",
        "delete_relations",
        "read_graph",
        "search_nodes",
        "open_nodes"
      ]
    },
  }
}

Если путь не указан, по умолчанию будет использоваться файл memory.jsonl в установочном каталоге сервера.

Системная подсказка

Запрос на использование памяти зависит от варианта использования и используемой вами модели ИИ. Изменение запроса поможет модели определить частоту и типы создаваемых воспоминаний.

Вот пример подсказки для персонализации чата, которую можно адаптировать для любой модели ИИ. Для пользователей Claude вы можете использовать эту подсказку в поле "Custom Instructions" проекта 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 Gathering:
   - 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
     c) Store facts about them as observations

Интеграция с другими моделями ИИ

Этот сервер реализует стандарт Model Context Protocol (MCP), что делает его совместимым с любой моделью ИИ, которая поддерживает вызов функций. Структура графа знаний и API не зависят от модели, что позволяет осуществлять гибкую интеграцию с различными платформами ИИ.

Для интеграции с другими моделями:

  1. Настройте модель для доступа к серверу MCP

  2. Убедитесь, что модель может выполнять вызовы функций к открытым инструментам.

  3. Адаптируйте системную подсказку к формату инструкций конкретной модели

  4. Используйте одни и те же операции графа знаний независимо от модели

Лицензия

Этот сервер MCP лицензирован по лицензии MIT. Это означает, что вы можете свободно использовать, изменять и распространять программное обеспечение в соответствии с условиями лицензии MIT. Для получения более подробной информации см. файл LICENSE в репозитории проекта.

Available Tools

10 tools
aim_memory_add_factsA

Add new facts to an existing memory. Use this to append information to something already stored.

IMPORTANT: Memory must already exist - use aim_memory_store first. Throws error if not found.

RETURNS: Array of {entityName, addedObservations} showing what was added (duplicates are ignored).

DATABASE: Adds to entities in the specified 'context' database, or master database if not specified.

EXAMPLES:

  • aim_memory_add_facts({observations: [{entityName: "John", contents: ["Lives in Seattle", "Works in tech"]}]})

  • aim_memory_add_facts({context: "work", observations: [{entityName: "Q4_Project", contents: ["Behind schedule", "Need more resources"]}]})

Inputs: observations (required), context, location.

aim_memory_forgetA

Forget memories. Removes memories and their associated links.

DATABASE SELECTION: Entities are deleted from the specified database's knowledge graph.

LOCATION OVERRIDE: Use the 'location' parameter to force deletion from 'project' (.aim directory) or 'global' (configured directory). Leave blank for auto-detection.

EXAMPLES:

  • Master database (default): aim_memory_forget({entityNames: ["OldProject"]})

  • Work database: aim_memory_forget({context: "work", entityNames: ["CompletedTask", "CancelledMeeting"]})

  • Master database in global location: aim_memory_forget({location: "global", entityNames: ["OldProject"]})

  • Personal database in project location: aim_memory_forget({context: "personal", location: "project", entityNames: ["ExpiredReminder"]})

Inputs: entityNames (required), context, location.

aim_memory_getA

Retrieve specific memories by exact name. Use this when you know exactly what you're looking for.

VS aim_memory_search: Use aim_memory_get for exact name lookup. Use aim_memory_search for fuzzy matching or when you don't know exact names.

RETURNS: Requested entities and relations between them. Non-existent names are silently ignored.

FORMAT OPTIONS:

  • "json" (default): Structured JSON for programmatic use

  • "pretty": Human-readable text format

EXAMPLES:

  • aim_memory_get({names: ["John", "TechConf2024"]}) - JSON format

  • aim_memory_get({names: ["Shane"], format: "pretty"}) - Human-readable

  • aim_memory_get({context: "work", names: ["Q4_Project"], format: "pretty"})

Inputs: names (required), context, location, format.

aim_memory_list_storesA

List all available memory databases and show current storage location.

DATABASE TYPES:

  • "default": The master database (memory.jsonl) - used when no context is specified

  • Named databases: Created via context parameter (e.g., "work" -> memory-work.jsonl)

RETURNS: {project_databases: [...], global_databases: [...], current_location: "..."}

  • project_databases: Databases in .aim directory (if project detected)

  • global_databases: Databases in global --memory-path directory

  • current_location: Where operations will default to

Use this to discover what databases exist before querying them.

EXAMPLES:

  • aim_memory_list_stores() - Shows all available databases and current storage location

Inputs: no named parameters.

aim_memory_read_allA

Read all memories in a database. Returns every stored memory and their links.

FORMAT OPTIONS:

  • "json" (default): Structured JSON for programmatic use

  • "pretty": Human-readable text format

DATABASE: Reads from the specified 'context' database, or master database if not specified.

EXAMPLES:

  • aim_memory_read_all({}) - JSON format

  • aim_memory_read_all({format: "pretty"}) - Human-readable

  • aim_memory_read_all({context: "work", format: "pretty"}) - Work database, pretty

Inputs: context, location, format.

aim_memory_remove_factsA

Remove specific facts from a memory. Keeps the memory but removes selected observations.

DATABASE SELECTION: Observations are deleted from entities within the specified database's knowledge graph.

LOCATION OVERRIDE: Use the 'location' parameter to force deletion from 'project' (.aim directory) or 'global' (configured directory). Leave blank for auto-detection.

EXAMPLES:

  • Master database (default): aim_memory_remove_facts({deletions: [{entityName: "John", observations: ["Outdated info"]}]})

  • Work database: aim_memory_remove_facts({context: "work", deletions: [{entityName: "Project", observations: ["Old deadline"]}]})

  • Master database in global location: aim_memory_remove_facts({location: "global", deletions: [{entityName: "John", observations: ["Outdated info"]}]})

  • Health database in project location: aim_memory_remove_facts({context: "health", location: "project", deletions: [{entityName: "Exercise", observations: ["Injured knee"]}]})

Inputs: deletions (required), context, location.

aim_memory_storeA

Store new memories. Use this to remember people, projects, concepts, or any information worth persisting.

AIM (AI Memory) provides persistent memory for AI assistants. The 'aim_memory_' prefix groups all memory tools together.

WHAT'S STORED: Memories have a name, type (person/project/concept/etc.), and observations (facts about them).

DATABASES: Use the 'context' parameter to organize memories into separate graphs:

  • Leave blank: Uses the master database (default for general information)

  • Any name: Creates/uses a named database ('work', 'personal', 'health', 'research', etc.)

  • New databases are created automatically - no setup required

  • IMPORTANT: Use consistent, simple names - prefer 'work' over 'work-stuff'

STORAGE LOCATIONS: Files are stored as JSONL (e.g., memory.jsonl, memory-work.jsonl):

  • Project-local: .aim directory in project root (auto-detected if exists)

  • Global: User's configured --memory-path directory

  • Use 'location' parameter to override: 'project' or 'global'

RETURNS: Array of created entities.

EXAMPLES:

  • Master database (default): aim_memory_store({entities: [{name: "John", entityType: "person", observations: ["Met at conference"]}]})

  • Work database: aim_memory_store({context: "work", entities: [{name: "Q4_Project", entityType: "project", observations: ["Due December 2024"]}]})

  • Master database in global location: aim_memory_store({location: "global", entities: [{name: "John", entityType: "person", observations: ["Met at conference"]}]})

  • Work database in project location: aim_memory_store({context: "work", location: "project", entities: [{name: "Q4_Project", entityType: "project", observations: ["Due December 2024"]}]})

Inputs: entities (required), context, location.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 10 tools

    Disambiguation5/5

    Each tool has a distinct action—store, retrieve, search, list, link, unlink, etc.—with no overlapping purposes. The descriptions clearly differentiate similar tools like get vs search and read_all vs list_stores.

    Naming Consistency5/5

    All tools use the consistent prefix 'aim_memory_' followed by a clear snake_case action verb (store, add_facts, get, search, read_all, list_stores, forget, remove_facts, link, unlink). No mixing of styles.

    Tool Count5/5

    10 tools cover the essential operations for a knowledge graph memory system—CRUD for entities and relations, plus search and listing. This is well-scoped without being excessive or sparse.

    Completeness4/5

    The tool set covers creation, retrieval, search, listing, linking, and deletion of entities and facts. Missing is a direct update for entity names or types (requires forget+re-store), but this is a minor gap given the add/remove facts functionality.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers