Skip to main content
Glama
Traceless-zero

AI-MemoryHub MCP Server

AI记忆中枢(AI-MemoryHub)

Система долговременной памяти для AI-агентов с нулевыми зависимостями и без привязки к модели: Markdown-текст как авторитетный источник + тонкий SQLite-индекс, детерминированный поиск вместо векторного RAG. «Понимание» отдаётся внешнему AI, движок занимается только поиском и отказом от ответа. Построена на концепции CEMA (Cognitive Event-driven Memory Architecture, когнитивно-событийная архитектура памяти).

Личный проект, независимая разработка в стиле vibe coding: архитектура и проектирование требований выполнены мной, код написан с помощью AI.


Описание проекта

AI记忆中枢(AI-MemoryHub)разделяет «долговременную память» на два уровня:

  • Фоновый текст (авторитетный источник): каждое воспоминание — это Markdown-файл с YAML front-matter, содержащий всё семантическое содержимое. Он никогда не участвует в поиске и извлекается по ID по мере необходимости (то есть «забытое холодное хранилище»).

  • Интерфейсный индекс (тонкая таблица SQLite): хранит id / title / summary / aliases / tags / linked / anchors / created / updated + features (нормализация вариантов сущностей) + четыре элемента person / event_date / location / topic и может быть полностью пересобран из front-matter всех .md. Поиск происходит только здесь; текст извлекается только после попадания в уникальный ID.

Эта архитектура называется CEMA (тонкий интерфейсный индекс + фоновый текст, строгое соотношение 1:1 между передним и задним планом, индекс полностью пересобирается из текста) — поиск без состояния, дешёвое хранение без забывания, и она снимает эксплуатационную нагрузку традиционных систем памяти (без векторной инфраструктуры, без ночных LLM-конвейеров, прямая запись агентом).

Спроектирована с нулевыми сторонними зависимостями (только стандартная библиотека Python), может подключаться к API любой большой AI-модели; слой понимания берёт на себя любой из вариантов: AI-клиент / агент / платная LLM.

Соглашение об именовании: в этом документе «AI记忆中枢(AI-MemoryHub)」 — официальное название проекта; «HMA» обозначает его базовую архитектуру Hybrid Memory Architecture (гибридная архитектура памяти). Идентификаторы в коде, такие как имя пакета hma, имя MCP-сервера, переменная окружения HMA_LLM, остаются неизменными.

Ключевые особенности

  • Событийная память: событие — единственный носитель, без классификации на кратко-/долгосрочную, эпизодическую/семантическую

  • Строгое разделение переднего и заднего плана: тонкий SQLite-индекс + Markdown-текст, индекс полностью пересобирается из front-matter

  • Без забывания, полное сохранение: нет оценки важности, нет кривой забывания, решение остаётся на момент поиска

  • Детерминированный поиск вместо векторных догадок: ноль векторов/ноль эмбеддингов; нормализация вариантов сущностей на F-stage + устранение неоднозначности на уровне глав C+A + чтение текста через READ + циклические запросы

  • Tag как Mod: пакетная установка/удаление: копирование/удаление папки в memory = установка/удаление одного когнитивного блока

  • Без привязки к модели: универсальный LLM-адаптер — сегодня Claude, завтра GPT, послезавтра локальный Ollama, без изменения кода

  • Принудительный контракт запросов: на границе MCP каждая операция поиска проверяется через QueryEnvelope (отсутствие keywords/mode отклоняется сразу)

Философия архитектуры, классификация поиска и подходы к решению — в проектных документах в memory/项目/AIMH-design-journal/; перечень MCP-инструментов, API движка, механизмы поиска, адаптеры, инварианты проектирования, методика бенчмарков — всё сведено в 技术参考.md. Этот документ описывает только «что это / как запустить».


Related MCP server: mcp-ltm

Структура проекта

memory/ — это единое авторитетное хранилище AI记忆中枢(AI-MemoryHub). Каждый пакет памяти = один .md-файл события (дерево заголовков ## + YAML front-matter) + index.db внутри пакета (тонкий кэш индекса, который можно полностью пересобрать из front-matter .md; удаление не приводит к потере данных).

AIMH/
├── hma/                          # 引擎核心(零运行时依赖,仅标准库)
│   ├── hma_core.py             # Memory 类:write/query/query_anchors/resolve_query/read_section/link/rebuild/orchestrate/list_all_in_scope/ingest + derive_anchors/query_features/recall_multihop
│   ├── envelope.py             # QueryEnvelope 校验层(MCP 边界强制)
│   ├── cli.py                  # 命令行入口
│   ├── server.py               # MCP server(stdio JSON-RPC,8 工具)
│   ├── engine/                # 分支接口 / CLI(dispatch + @register + handlers)
│   ├── ingest.py              # AI 收录管线
│   ├── daylog.py / tree.py / llm_adapter.py
├── scripts/core/               # 独立确定性脚本(rebuild_index / relocate / migrate_*_memory / compact / deploy_mcp …)
├── skills/                      # 技能(项目级副本,与用户级 ~/.workbuddy/skills 双副本)
├── memory/                      # 权威记忆库(单一真相)
├── 一键更新记忆索引.exe          # 手动重建索引小程序(双击即用,零 AI)
├── pyproject.toml               # 零运行时依赖声明
└── README.md

Порядок выполнения

Установка

pip install -e .          # 提供 hma-mcp / hma 两个命令

pyproject.toml объявляет нулевые зависимости времени выполнения (только стандартная библиотека). Не требуются никакие векторные библиотеки или внешние сервисы.

Три способа использования

1. Командная строка (вручную / скрипты)

python -m hma.cli --root memory write \
  --id proj-rag --title "放弃 RAG 主记忆" --summary "改事件驱动分层" \
  --tags project,decision --aliases "分层记忆" --body "# ...\n正文"

python -m hma.cli --root memory query "分层记忆" --top-k 5
python -m hma.cli --root memory link proj-rag todo-mcp
python -m hma.cli --root memory show  proj-rag
python -m hma.cli --root memory list
python -m hma.cli --root memory rebuild      # 删了 index.db 也能恢复

2. MCP-сервер (подключение к любому AI-клиенту) ⭐ рекомендуется

python -m hma.server --root memory
# 或 entry point: hma-mcp --root memory

JSON-RPC 2.0 поверх stdio, предоставляет 8 инструментов (соответствуют трёхуровневой воронке поиска L1→L2→L3 + запись/связывание/пересборка/приём):

Инструмент

Назначение

memory_write

Пассивная структурированная запись одного пакета события (перезаписывает, если id существует)

memory_query

L1 детерминированный поиск на уровне пакетов, возвращает Top-K кандидатов (попадание по ID)

memory_query_anchors

L2 поиск по якорям на уровне глав, точное позиционирование раунда/секции по заголовку ## (возвращает locator)

memory_resolve

Единая точка входа для поиска и устранения неоднозначности: при нескольких сущностях уточняет, иначе возвращает Top-K; поддерживает многошаговый поиск + шлюз отказа

memory_read_section

L3 получение текста: по (id, heading) читает только этот раздел ##, без избыточности

memory_link

Двунаправленная связь двух пакетов события

memory_rebuild

Полная пересборка индекса из .md (.md — авторитетный источник, данные не теряются)

memory_ingest

Активный приём: пользователь вставляет текст, AI выполняет полный конвейер (см. ниже)

Любой MCP-клиент, такой как Claude Desktop / Codex / Cline / WorkBuddy, — достаточно добавить фрагмент конфигурации:

{
  "mcpServers": {
      "aimh": {
        "command": "python",
        "args": ["-m", "hma.server", "--root", "/path/to/.memory"]
      }
  }
}

WorkBuddy: развёртывание plug-and-play: в репозитории есть скрипт развёртывания в один клик, который копирует лаунчер в каталог конфигурации WorkBuddy, объединяет и записывает ~/.workbuddy/mcp.json (трогает только коннектор aimh, сохраняет остальные, автоматически определяет версию python, не прописывает пути жёстко) и регистрирует указатель ~/.hma_home:

python scripts/core/deploy_mcp.py            # 部署(幂等,可重跑)
python scripts/core/deploy_mcp.py --dry-run  # 只预览将写出的配置

После развёртывания на странице управления коннекторами WorkBuddy нажмите «Доверять», чтобы активировать коннектор aimh; в новом окне появятся инструменты mcp__aimh__*.

⚠️ После изменения server.py нужно в коннекторе выполнить отключить→включить / повторно Trust, чтобы долгоживущий процесс загрузил новый код.

3. Как библиотека (Python import)

from hma.hma_core import Memory
m = Memory("memory")
m.write(id="x", title="X", summary="s", tags=["t"], body="# X\n正文")
for rid, title, summary, score in m.query("x"):
    print(rid, score)

Запись и приём

Активный приём (memory_ingest) — пользователь вставляет текст, AI выполняет полный конвейер: читает сводки существующих пакетов для обнаружения связей → разбивает на пакеты событий по критериям когезии CEMA + шлюзу объёма → генерирует метаданные для каждого пакета → записывает в авторитетный источник .md + upsert индекса → устанавливает двунаправленные связи с существующими/новыми пакетами. Если LLM API не настроен, деградирует до эвристики одного пакета; инструмент всегда доступен.

# 有 LLM:AI 自动拆分+关联
echo "周会:放弃 RAG,改事件驱动;下周三前完成 MCP 评审。" \
  | python -m hma.cli --root memory ingest --scope wb

# 无 LLM / 不想调模型:单包兜底
echo "随手记一条想法" | python -m hma.cli --root memory ingest --no-llm

Путь с нулевой стоимостью (агент как слой понимания): если key не настроен, агент текущей сессии выступает слоем понимания (загружает навык aimh-ingest), а детерминированный движок сохраняет данные — этот путь изоморфен платному LLM-пути и взаимозаменяем. Если тип текста неопределён, сначала загружается мета-роутер-навык aimh-intake для решения о классификации, затем по цепочке загружаются соответствующие навыки oc-dossier / aimh-ingest / aimh-project / memory-import для сохранения; сам он не пишет никаких файлов в memory/.

Платный/локальный путь: установите HMA_LLM (и настройте соответствующие key/endpoint) — автоматически переключится на реальную LLM через llm_adapter, без изменения кода; при сбое вызова LLM автоматически откатится к эвристике.

Хронология: пакеты дневных записей (daylog)

Основное хранилище памяти организовано по темам, а не по хронологии; daylog добавляет ортогональную временную ось, не нарушая тематический принцип:

python -m hma.engine daylog add "一段叙事:这天发生的事" \
    --linked 主题包id --tags 关键词1,关键词2 [--date 2026-07-25]
python -m hma.engine daylog show 2026-07-25            # 全天
python -m hma.engine daylog show 2026-07-25 --q 关键词  # 精准搜寻
python -m hma.engine daylog range --start d1 --end d2

Время — это ключ фильтрации, а не вес (локализация = детерминированное сравнение даты, встроенной в id, без взвешивания по свежести). Нечёткие временные выражения («позавчера/в прошлую среду») агент разбирает в ISO-даты, после чего вызывает команду.

Сжатие и архивирование контекста (циркадный ритм · агент как слой понимания)

Когда окно контекста почти заполнено, избыточное содержимое, которое уже обсуждено, ещё не сохранено в хранилище, но может понадобиться позже, передаётся агенту: он определяет место назначения + генерирует конденсированную сводку, и детерминированная запись выполняется через scripts/core/compact.py:

python scripts/core/compact.py \
    --root memory --sink <daylog|cache|progress> \
    --summary "<冷凝摘要>" --source "<溢出来源>" \
    [--date YYYY-MM-DD] [--id <eid> --title "<标题>"] [--project <pid>] \
    [--linked a,b] [--tags x,y] [--conflict-event <id> --conflict-intro "<一句话>"]

Железное правило: сжатие = аддитивное холодное резюме, авторитетный исходный текст не меняется ни на слово; перезапись допускается только при реальном конфликте новой информации с неким авторитетным событием, и при этом добавляется аудируемый trail.

Миграция внешней памяти

Скрипты migrate_wb_memory / migrate_claude_memory / migrate_gemini_memory / migrate_codex_memory в scripts/core/ переносят встроенную долговременную память различных AI-клиентов в AIMH, устанавливая доступный для поиска интерфейсный индекс CEMA:

python scripts/core/migrate_wb_memory.py     --wb-dir ".workbuddy/memory" --root memory/项目/AIMH-design-journal
python scripts/core/migrate_claude_memory.py  --root memory --namespace 其他
python scripts/core/migrate_gemini_memory.py  --root memory --namespace 其他
python scripts/core/migrate_codex_memory.py   --root memory --namespace 其他

Полный список скриптов миграции и философия — в 技术参考.md §8.

Продвинутый поиск (scope / отказ / подзапросы / перечисление)

Несколько уровней усиления при записи и чтении — подробнее в 技术参考.md §7:

  • Фокус scope: передача пути к каталогу возвращает только это поддерево, блокируя помехи между поддеревьями (29 пакетов → 11 пакетов); только сужает область, не заменяет отказ.

  • Слой отказа allow_abstain: при недостаточном покрытии/запросах вне области явно возвращается отказ, чтобы избежать выдумывания (реализовано в V1.0, включено по умолчанию).

  • Подзапросы sub_queries: AI выдаёт список подзапросов за один раз, движок детерминированно разворачивает и объединяет, без отдельных обращений.

  • Перечисление enumerate: выводит все пакеты в поддереве scope (не Top-K сортировка).

  • Многошаговость multihop: BFS-расширение кластера по курируемым при записи рёбрам linked, восполняет слепые зоны связей/структуры (opt-in).

Все поисковые MCP-вызовы подчиняются контракту QueryEnvelope (q/keywords/mode обязательны; при отсутствии — отклонение с ENVELOPE_VIOLATION).


Текущее состояние

Статус проекта (2026-08-20): из-за исчерпания LLM-ресурсов (квоты бесплатных моделей) проект официально завершён, этап разработки окончен. Код, документация и бенчмарк-данные остаются в текущем состоянии; отложенные задачи (например, полный прогон LoCoMo) могут быть возобновлены в любой момент при наличии доступных ресурсов.

Позиционирование: эталонная реализация с нулевыми зависимостями + личный полигон для философии — инженерно проверены в условиях нулевых зависимостей такие решения, как событийная память, разделение переднего и заднего плана, отсутствие забывания, отказ от векторных догадок; также подключены четыре элемента поиска, трёхэтапный конвейер якорей F+C+A+READ, бенчмарки LoCoMo / MemoryStress.

Реализованная философия: событийная память · строгое разделение переднего и заднего плана · полное сохранение без забывания · детерминированный поиск без векторных догадок · пакетная установка/удаление Tag как Mod · межоконная офлайн-интеграция (циркадный ритм).

Инженерное состояние:

  • Нулевые сторонние зависимости времени выполнения (только стандартная библиотека Python)

  • MCP-сервер предоставляет 8 инструментов (write / query / query_anchors / resolve / read_section / link / rebuild / ingest)

  • Четыре элемента поиска (person / event_date / location / topic) стали полями первого класса, с мягким взвешиванием на этапе чтения

  • Поиск на уровне якорей обновлён до трёхэтапной схемы F+C+A+READ (производственный движок замкнут)

  • Слой отказа V1.0 реализован (четыре шлюза + жёсткий отказ corpus_missing_entity, allow_abstain включён по умолчанию)

  • Контракт QueryEnvelope реализован (на границе MCP обязательны q/keywords/mode, веер подзапросов sub_queries, перечисление list_all_in_scope)

  • Навыки как подключаемые клиенты + постоянный навык активного запуска (aimh-always)

Бенчмарки (реальный цикл данных пройден):

  • LoCoMo 1540 вопросов: hit@30 ≈ 99.6% / recall@30 ≈ 99.5% / hit@5 89.7–92%

  • MemoryStress 300 вопросов: baseline 77% / B_gold 89.7%

Полная методика (включая красные линии: OMEGA 38.3% не подлежит сопоставлению, TrueMemory 93% как целевой ориентир) — в 技术参考.md §9.

Известные пробелы:

  • Полноценная версия интеграции живого документа в реальном времени внутри окна (интеграция фрагментов в существующий текст прямо во время диалога) невозможна в текущей архитектуре Transformer; остаётся на будущее для не-TF архитектур (персистентные состояния типа SSM/Mamba или настоящий AGI)

  • MCP-коннектор нужно активировать нажатием «Доверять» в клиенте

  • Прямые вызовы API движка обходят ограничения QueryEnvelope на границе MCP (ожидаемая изоляция; тестовые скрипты, работающие через API, не затрагиваются)

  • Архитектурный компромисс (потолок возможностей — на уровне AI): CEMA концентрирует понимание (редукция/определение mode/извлечение keywords/разбиение sub_queries/курирование linked) на уровне AI, движок выполняет только детерминированные операции. Выгода: движок минимален, отлаживаем, бесплатно улучшается с развитием AI; цена: верхняя граница качества AIMH = верхняя граница интеллекта парного AI — если AI слаб, система вырождается в «красивый файловый шкаф, который иногда используют неправильно». Три буфера (жёсткая проверка конверта/амортизация курирования при записи/подстраховка шлюзом отказа) превращают «AI может быть глупым» в «контролируемо и исправимо», но не устраняют этот потолок. Подробнее в «Математические и лингвофилософские соображения о поиске и устранении неоднозначности», §11.5.

Лицензия

MIT

Available Tools

7 tools
memory_ingestA

主动收录:用户提供一段原始文本,AI 执行完整管线——理解并拆分为凝聚的事件包、生成结构化元数据、写入 .md 权威源 + 索引、与现有/新建包建立关联。模型由通用适配器决定(模型无关)。未配置 LLM API 时退化为单包启发式。

ParametersJSON Schema
NameRequiredDescriptionDefault
textYes待收录的原始文本
modelNo可选,覆盖默认模型名
scopeNo作用域标签(如 user_global / workspace_x),会加进每个新包的 tags
providerNo可选,覆盖默认 LLM 厂商:openai / anthropic
auto_linkNo是否自动建立关联,默认 true

TDQS

A4.4/5.0
Behavior5/5

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

With no annotations provided, the description fully discloses behavioral aspects: it performs multiple steps (splitting, metadata generation, writing to .md and index, linking), is model-agnostic, and falls back to a heuristic when no LLM API is configured. This is comprehensive and avoids surprises.

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 two concise sentences that front-load the purpose and cover key aspects without redundancy. Every sentence adds value, including fallback behavior and model-agnostic property.

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

Completeness4/5

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

The description thoroughly covers input handling and internal behavior but omits any mention of return values or output format. Given the absence of an output schema, the agent is left without information on what the tool returns, which is a minor gap.

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 input schema covers 100% of parameters with descriptions, so the description does not need to add parameter details. It provides overall pipeline context but no additional parameter-level semantics beyond what the schema offers, meeting the baseline expectation.

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

Purpose5/5

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

The description clearly states the tool's function: accepting raw text and executing a full pipeline to split into event packets, generate metadata, write to authoritative source with indexing, and establish links. It distinguishes from sibling tools like memory_write (which likely writes a single packet) and memory_link (which creates associations) by describing a more comprehensive ingestion process.

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

Usage Guidelines4/5

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

The description implicitly indicates usage for ingesting raw text into the memory system, but does not explicitly state when to use this over alternatives or provide exclusion criteria. The context from sibling tools makes it clear this is for initial ingestion versus querying or linking, but explicit guidance is missing.

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

memory_queryA

确定性无状态检索:在 id/title/alias/tag/summary 上做关键词匹配,返回按确定性规则排序的 Top-K 候选(命中唯一 ID)。不依赖热度/权重。

ParametersJSON Schema
NameRequiredDescriptionDefault
qYes检索关键词
top_kNo返回条数,默认 5

TDQS

A4.2/5.0
Behavior4/5

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

With no annotations, description discloses statelessness, determinism, matching fields, sorting rules, and non-reliance on weights. It does not mention side effects or rate limits, but provides adequate behavioral context.

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?

Description is a single concise sentence with no redundant information, front-loading the core action and key characteristics.

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

Completeness4/5

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

For a simple query tool with 2 parameters and no output schema, the description covers purpose, matching fields, sorting, and behavior. It could mention the return format explicitly but is otherwise complete.

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

Parameters4/5

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

Schema coverage is 100% with descriptions for both parameters. The description adds value by specifying the fields searched and sorting criteria beyond the schema's parameter descriptions.

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

Purpose5/5

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

Description clearly states it is a deterministic stateless retrieval tool for keyword matching on id/title/alias/tag/summary, and distinguishes itself from siblings by noting it does not rely on popularity/weights.

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

Usage Guidelines3/5

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

Description implies use for deterministic keyword matching without popularity bias, but does not explicitly state when to use this tool versus siblings like memory_query_anchors or memory_read_section.

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

memory_query_anchorsA

锚点层细粒度召回:在事件包的 anchors 子事件锚点上做关键词匹配,返回命中的子事件(包ID + 锚点标题 + 摘要 + 定位 + 分数)。用于故事包/长正文按剧情节点召回——当 memory_query 命中率低时,anchors 往往能把内容词召回(如「幽影核心」「圣保罗之焰」「纽约之战」)。

ParametersJSON Schema
NameRequiredDescriptionDefault
qYes检索关键词(剧情/事件/特征词)
top_kNo返回条数,默认 5

TDQS

A4.2/5.0
Behavior3/5

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

With no annotations provided, the description carries the full burden. It explains the matching behavior and return fields, but does not disclose side effects, authorization needs, or limitations such as whether it is read-only or if it modifies data.

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 three concise sentences, with no fluff. The key information (what, how, when) is front-loaded and efficiently communicated.

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

Completeness4/5

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

For a simple tool with two parameters and no output schema, the description is fairly complete. It explains what the tool does, what it returns, and its typical use case. No major gaps are present.

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

Parameters4/5

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

Schema description coverage is 100%, but the description adds context: the tool matches on anchor sub-events within story packages, clarifying the domain of the 'q' parameter. This goes beyond the schema descriptions.

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

Purpose5/5

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

The description clearly states the tool's function: fine-grained recall on anchor sub-events via keyword matching, returning specific fields (package ID, anchor title, summary, location, score). It also distinguishes itself from siblings by mentioning its use for story packages/long texts and when memory_query has low hit rate.

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

Usage Guidelines4/5

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

The description explicitly says to use this tool when memory_query has low hit rate, providing a clear usage scenario. It implies alternatives (memory_query) but does not explicitly state when not to use it.

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

memory_read_sectionA

按小标题精准读取事件包正文的某一段(而非整包),节省上下文窗口。配合 memory_query_anchors 使用:先 query_anchors 拿到命中的 locator,再用本工具按 locator 取该段正文。heading 为正文里 ## / ### 小标题的片段(包含匹配),可直接用 locator 值。

ParametersJSON Schema
NameRequiredDescriptionDefault
idYes事件包 ID
headingYes小标题片段(##/### 标题的包含匹配,可用 query_anchors 返回的 locator)

TDQS

A4.6/5.0
Behavior4/5

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

No annotations provided, so description carries full burden. It explains reading by heading and use of locator. Implies read-only operation, but not explicitly stated. No contradictions.

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?

Two sentences in Chinese, front-loaded with purpose, then usage. No extraneous information. Efficient.

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

Completeness4/5

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

Simple tool with 2 required params and no output schema. Description covers usage pattern and parameter meaning, mentions context saving. Not 5 because missing behavior on missing heading, but adequate.

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

Parameters4/5

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

Schema has 100% coverage, so baseline 3. Description adds meaning: heading is a subtitle fragment and can be locator from query_anchors. Adds value beyond schema.

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

Purpose5/5

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

Description states it reads a specific section of an event package body by subtitle, saving context window. Distinguishes from siblings like memory_query_anchors (which finds locators) and memory_query (likely retrieves full package). Verb '读取' and resource are specific.

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

Usage Guidelines5/5

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

Explicitly instructs to use with memory_query_anchors: first query_anchors to get locator, then this tool with locator. Provides clear when-to-use and usage pattern.

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

memory_rebuildA

从所有 .md 的 front-matter 全量重建 index.db。索引损坏时调用——.md 是权威源,重建不丢数据。

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.4/5.0
Behavior4/5

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

With no annotations, the description carries the full burden. It states that .md is authoritative and rebuild doesn't lose data, which reassures about safety. However, it doesn't detail whether existing index data is overwritten or merged, or if any permissions are needed.

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 two short sentences in Chinese, extremely concise. It front-loads the action and condition, with no wasted words.

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

Completeness4/5

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

Given no parameters and no output schema, the description covers purpose and usage condition adequately. It could mention the effect on other tools (e.g., index becomes current) but that's not critical.

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

Parameters4/5

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

There are zero parameters, so schema coverage is 100% by default. The description adds no parameter details, but that's acceptable as no parameters exist. Baseline of 4 is appropriate.

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

Purpose5/5

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

The description clearly states the tool's purpose: rebuilding index.db from all .md front-matter. It specifies the authoritative source (.md) and that data is not lost, distinguishing it from siblings like memory_write or memory_query.

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

Usage Guidelines4/5

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

The description explicitly says 'call when index is corrupted', providing a clear usage condition. It implies not to use it for normal operations, though it doesn't list alternative tools or when not to use it.

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

memory_writeA

写/改一个事件包:原子写 .md(权威源)+ 确定性 upsert 索引。id 存在则覆盖更新。tags/aliases/linked 为字符串数组。

ParametersJSON Schema
NameRequiredDescriptionDefault
idYes事件包唯一 ID(文件名)
bodyNoMarkdown 正文
tagsNo标签;trivial 表示琐碎内容(检索降权)
titleNo标题
linkedNo关联的其他事件包 ID
aliasesNo别名/同义词,用于检索命中
createdNo创建日期 YYYY-MM-DD(可选)
summaryNo一句话摘要
updatedNo更新日期 YYYY-MM-DD(可选)

TDQS

A3.7/5.0
Behavior3/5

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

With no annotations, the description carries the full burden. It discloses atomic write, upsert, and overwrite behavior, but lacks details on auth, rate limits, failure modes, or concurrency. Basic behavioral info is present but not comprehensive.

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?

Two sentences, no wasted words. The description is front-loaded with the core action and efficiently covers key behavior.

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

Completeness3/5

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

Given no output schema, the description does not explain return values. It also omits usage of optional body, trivial tag implications, and idempotency. Adequate but incomplete for a tool with 9 parameters.

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?

All parameters have schema descriptions (100% coverage). The tool description does not add significant meaning beyond the schema; it merely confirms that tags/aliases/linked are string arrays. Baseline of 3 is appropriate.

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

Purpose5/5

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

The description clearly states the tool writes/modifies an event package with atomic write and upsert. It uses specific verbs and resource, and distinguishes from sibling tools like memory_query (query) and memory_read_section (read).

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

Usage Guidelines3/5

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

The description implies this is the primary write tool but does not explicitly state when to use it vs alternatives like memory_ingest. No when-not-to-use guidance is provided.

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. Dates show when Glama detected each change.

  1. 7 tool updatesv0.1.0
    • First observedmemory_ingest
    • First observedmemory_link
    • First observedmemory_query
    • First observedmemory_query_anchors
    • First observedmemory_read_section
    • First observedmemory_rebuild
    • First observedmemory_write

TDQS

A4.1/5.0
Disambiguation5/5

All seven tools have clearly distinct purposes: writing/updating events, querying, linking, anchor-level search, section reading, index rebuilding, and intelligent ingestion. No overlap in functionality.

Naming Consistency5/5

All tools follow a consistent 'memory_' prefix with a verb_noun pattern (e.g., memory_write, memory_query, memory_link). The naming is predictable and systematic.

Tool Count5/5

With 7 tools, the server is well-scoped. Each tool addresses a specific need for managing memory events without unnecessary bloat or deficiency.

Completeness3/5

The set covers writing, querying, linking, section reading, and maintenance. However, it lacks an explicit deletion tool and a way to retrieve full event packages, which are notable gaps for a complete lifecycle.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    B
    maintenance
    A local-first shared memory layer for MCP-aware agents like Claude, Codex, and Hermes, enabling persistent memory across chats and clients via Markdown files and SQLite FTS.
    6
    2
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides persistent long-term memory for AI assistants with tag-based retrieval, wiki-style linking, and source references, storing memories as markdown files with SQLite index.
    1
    MIT
  • A
    license
    B
    quality
    A
    maintenance
    Personal multi-LLM memory repository using Markdown as source of truth, SQLite FTS5 for retrieval, and MCP tools for search, context, and write proposals.
    74
    Apache 2.0
  • A
    license
    A
    quality
    B
    maintenance
    MCP server for persistent, cross-session, local-first memory for AI agents, storing memories as Markdown files with SQLite indexing for hybrid search.
    24
    Apache 2.0

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Traceless-zero/AI-MemoryHub'

If you have feedback or need assistance with the MCP directory API, please join our Discord server