AI-MemoryHub MCP Server
This MCP server provides deterministic, Markdown-backed long-term memory management for AI agents.
Write or update event packages: create/overwrite Markdown memory files with metadata and a rebuilt SQLite index.
Search memories: retrieve Top-K candidate event packages by keyword matching over IDs, titles, aliases, tags, and summaries.
Search anchor-level details: find specific sub-events or story beats inside longer memory packages.
Read targeted sections: fetch only a matching heading section from a memory file to save context.
Link memories: create bidirectional relationships between two event packages.
Rebuild the index: regenerate the SQLite index from all Markdown front-matter when needed.
Ingest raw text: run an ingestion pipeline that splits text into structured memory packages and links them when possible.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@AI-MemoryHub MCP Server remember: switched to event-driven architecture for project X"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
AI Memory Hub (AI-MemoryHub)
A zero-dependency, model-agnostic long-term memory system for AI Agents: Markdown body as the authoritative source + a thin SQLite index, using deterministic retrieval instead of vector RAG, leaving "understanding" to the outer AI while the engine only does retrieval and abstention. Built on the CEMA (Cognitive Event-driven Memory Architecture) concept.
Personal project, independently developed via vibe coding: architecture and requirements designed by myself, code implemented with AI assistance.
Project Introduction
AI Memory Hub (AI-MemoryHub) splits "long-term memory" into two layers:
Backend body (authoritative source): Each memory is a Markdown file with YAML front-matter, storing all semantic content. Never participates in retrieval; fetched on demand by ID (i.e., "forgotten cold storage").
Frontend index (thin SQLite table): Stores
id / title / summary / aliases / tags / linked / anchors / created / updated+features(sub-entity variant normalization) + four elementsperson / event_date / location / topic, fully rebuildable from the front-matter of all.mdfiles. Retrieval happens only here; the body is fetched only after a unique ID is hit.
This design is called CEMA (thin frontend index + backend body, strict 1:1 between front and back, index fully rebuildable from body) — stateless retrieval, cheap storage that never forgets, and it sheds the operational weight of traditional memory systems (no vector infrastructure, no nightly LLM pipelines, agents write directly).
Designed with zero third-party dependencies (Python standard library only), it can interface with any AI large-model API; the understanding layer is handled by any AI client / Agent / paid LLM.
Naming convention: In this document, "AI Memory Hub (AI-MemoryHub)" is the project's official name; "HMA" specifically refers to its underlying architecture, Hybrid Memory Architecture. Identifiers in code such as the
hmapackage name, MCP server name, andHMA_LLMenvironment variable remain unchanged.
Core Features
Event-based memory: Events are the only carrier; no classification into short/long-term or episodic/semantic
Strict front/back separation: thin SQLite index + Markdown body; index fully rebuildable from front-matter
No forgetting, full retention: no importance scoring, no forgetting curve; judgment is left to retrieval time
Deterministic recall against vector guesswork: zero vectors / zero embeddings; F-stage sub-entity variant normalization + C+A chapter-level disambiguation + READ body retrieval + loop queries
Tag-as-Mod package-level mounting: copy/delete a folder under
memory= mount/unmount a piece of cognitionModel-agnostic: universal LLM adapter — Claude today, GPT tomorrow, local Ollama later, no code changes needed
Query contract enforcement: the MCP boundary validates every retrieval with QueryEnvelope checks (missing
keywords/modeis rejected outright)
Architecture philosophy, retrieval taxonomy, and solution approaches are in the design documents under
memory/项目/AIMH-design-journal/; the MCP tool list, engine API, retrieval mechanism, adapters, design invariants, and benchmark methodology all converge into技术参考.md. This document only covers "what it is / how to run it."
Related MCP server: CP Memory
Project Structure
memory/is the single authoritative store of AI Memory Hub (AI-MemoryHub). Each memory package = one.mdevent file (##heading tree + YAML front-matter) + an in-packageindex.db(thin index cache, fully rebuildable from.mdfront-matter; deleting it loses no data).
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.mdExecution Flow
Installation
pip install -e . # 提供 hma-mcp / hma 两个命令pyproject.toml declares zero runtime dependencies (standard library only). No vector libraries or external services needed.
Three Usage Modes
1. Command line (manual / scripts)
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 server (connect any AI client) ⭐ Recommended
python -m hma.server --root memory
# 或 entry point: hma-mcp --root memoryJSON-RPC 2.0 over stdio, exposing 8 tools (corresponding to the three-level retrieval funnel L1→L2→L3 + write/link/rebuild/ingest):
Tool | Purpose |
| Passively structured write of one event package (overwrites if id exists) |
| L1 package-level deterministic retrieval, returns Top-K candidates (hit IDs) |
| L2 chapter-level anchor retrieval, precisely locates a round/section by |
| Unified recall disambiguation entry: clarifies when multiple entities, otherwise returns Top-K; supports multi-hop + abstention gate |
| L3 body retrieval: reads only that |
| Bidirectionally links two event packages |
| Fully rebuilds the index from |
| Active ingestion: user pastes text, AI runs the full pipeline (see below) |
Any MCP client such as Claude Desktop / Codex / Cline / WorkBuddy just needs a config snippet:
{
"mcpServers": {
"aimh": {
"command": "python",
"args": ["-m", "hma.server", "--root", "/path/to/.memory"]
}
}
}WorkBuddy plug-and-play deployment: the repo ships a one-click deployment script that copies the launcher into the WorkBuddy config directory, merges and writes out ~/.workbuddy/mcp.json (only touches the aimh connector, preserves everything else, auto-detects the python version, no hardcoded paths), and registers the ~/.hma_home pointer:
python scripts/core/deploy_mcp.py # 部署(幂等,可重跑)
python scripts/core/deploy_mcp.py --dry-run # 只预览将写出的配置After deployment, click "Trust" in the WorkBuddy connector management page to activate the aimh connector, and the mcp__aimh__* tools appear in a new window.
⚠️ After modifying
server.py, you need to disable→enable / re-Trust the connector for the long-running process to load the new code.
3. As a library (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)Writing and Ingestion
Active ingestion (memory_ingest) — the user pastes text, the AI executes the full pipeline: reads existing package summaries for link discovery → splits into event packages per CEMA cohesion + volume gates → generates metadata for each package → writes the .md authoritative source + upserts the index → establishes bidirectional links with existing/new packages. When no LLM API is configured, it degrades to single-package heuristics; the tool always works.
# 有 LLM:AI 自动拆分+关联
echo "周会:放弃 RAG,改事件驱动;下周三前完成 MCP 评审。" \
| python -m hma.cli --root memory ingest --scope wb
# 无 LLM / 不想调模型:单包兜底
echo "随手记一条想法" | python -m hma.cli --root memory ingest --no-llmZero-cost path (Agent as the understanding layer): when no key is configured, let the current session Agent act as the understanding layer (load the aimh-ingest skill), with the deterministic engine doing the persistence — isomorphic and swappable with the paid LLM path. When the text type is uncertain, first load the aimh-intake meta-routing skill for classification decisions, then chain-load the corresponding skill (oc-dossier / aimh-ingest / aimh-project / memory-import) to persist; never write any memory/ files yourself.
Paid/local path: setting HMA_LLM (with the corresponding key/endpoint) automatically switches to the real LLM via llm_adapter, no code changes needed; LLM call failures automatically fall back to heuristics.
Timeline: Single-Day Record Packages (daylog)
The main memory store is organized by topic rather than timeline; daylog adds an orthogonal timeline without breaking the topic principle:
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 d2Time is a filter key, not a weight (locating = deterministic comparison of the date embedded in the id, no recency weighting). Vague time expressions ("the day before yesterday / last Wednesday") are resolved by the Agent into ISO dates before calling commands.
Context Compression Archiving (Circadian Rhythm · Agent as the Understanding Layer)
When the context window is nearly full, overflow content that has been fully discussed, not yet persisted, but may be needed later is judged for placement by the Agent + condensed into a summary, then deterministically written via 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 "<一句话>"]Iron rule: compression = additive cold summary; the authoritative original text is never altered. Only when new information truly conflicts with an authoritative event is it overwritten, with an auditable trail appended.
Migrating External Memories
migrate_wb_memory / migrate_claude_memory / migrate_gemini_memory / migrate_codex_memory under scripts/core/ migrate each AI client's native long-term memory into AIMH, installing a retrievable CEMA frontend index:
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 其他Full list of migration scripts and philosophy: see
技术参考.md§8.
Advanced Retrieval (scope / abstention / multi-query / enumeration)
Several enhancement mechanisms at write and read time, detailed in 技术参考.md §7:
Focused
scope: passing a directory path recalls only that subtree, shielding against cross-subtree interference (29 packages → 11 packages); narrows the scope only, does not replace abstention.Abstention layer
allow_abstain: insufficient coverage / out-of-domain queries explicitly return abstention to avoid fabrication (landed in V1.0, on by default).Multi-query
sub_queries: the AI provides a list of sub-questions at once; the engine deterministically fans out and merges, no separate round trips.Enumeration
enumerate: lists all packages in the scope subtree (not Top-K ranked).Multi-hop
multihop: BFS expansion along curatedlinkededges from write time to widen the cluster, filling relational/structural blind spots (opt-in).
All retrieval-type MCP calls are bound by the QueryEnvelope contract (q/keywords/mode required; missing ones are rejected with ENVELOPE_VIOLATION).
Current Status
Project status (2026-08-20): Due to exhaustion of LLM resources (free model quotas), this project is formally concluded and the development phase has ended. Code, documentation, and benchmark data remain in their current state; pending items (such as the full LoCoMo benchmark run) can be resumed at any time when resources become available.
Positioning: zero-dependency reference implementation + personal philosophy testbed — engineering validation of event-based memory, front/back separation, no-forgetting, anti-vector-guesswork design under zero dependencies, plus integration of the four-element recall retrieval, the F+C+A+READ three-stage anchor pipeline, and LoCoMo / MemoryStress benchmark evaluation.
Philosophies delivered: event-based memory · strict front/back separation · no-forgetting full retention · anti-vector deterministic recall · Tag-as-Mod package-level mounting · cross-window offline integration (circadian rhythm).
Engineering status:
Zero third-party runtime dependencies (Python standard library only)
MCP server exposes 8 tools (write / query / query_anchors / resolve / read_section / link / rebuild / ingest)
Four-element recall retrieval (person / event_date / location / topic) is a first-class field, soft-weighted at read time
Anchor-level retrieval upgraded to the F+C+A+READ three-stage pipeline (production engine closed-loop)
Abstention layer V1.0 landed (four gates +
corpus_missing_entityhard rejection,allow_abstainon by default)QueryEnvelope contract landed (MCP boundary enforces
q/keywords/mode, multi-query fan-outsub_queries, enumerationlist_all_in_scope)Skills as plug-and-play client + resident proactive trigger skill (aimh-always)
Benchmark evaluation (real data closed-loop verified):
LoCoMo 1540 questions: hit@30 ≈ 99.6% / recall@30 ≈ 99.5% / hit@5 89.7–92%
MemoryStress 300 questions:
baseline77% /B_gold89.7%
Full methodology (including red lines: OMEGA 38.3% not comparable, TrueMemory 93% as alignment target) in
技术参考.md§9.
Known gaps:
In-window real-time live-document integration reset (integrating fragments into existing body text mid-conversation) cannot be fully implemented under the current Transformer architecture; deferred to non-TF architectures (persistent-state SSM/Mamba-like, or true AGI)
MCP connector requires clicking "Trust" in the client to activate
Direct engine API calls bypass the QueryEnvelope constraint at the MCP boundary (expected isolation; test scripts going through the API are unaffected)
Architectural trade-off (capability ceiling at the AI layer): CEMA concentrates understanding (reduction / mode judgment / keyword extraction / sub_queries splitting / linked curation) on the AI layer, with the engine doing only deterministic execution. The benefit is a minimal, debuggable engine that gets smarter for free as AI improves; the cost is that AIMH's quality ceiling = the paired AI's intelligence ceiling — a weak AI degrades it into "a pretty file cabinet occasionally used wrong." Three buffers (envelope hard validation / write-time curation amortization / abstention gate fallback) turn "AI can be dumb" into "controllable and correctable," but do not eliminate that ceiling. See "Mathematical and Linguistic-Philosophical Thoughts on Recall Disambiguation" §11.5.
License
MIT
Available Tools
7 toolsmemory_ingestA
主动收录:用户提供一段原始文本,AI 执行完整管线——理解并拆分为凝聚的事件包、生成结构化元数据、写入 .md 权威源 + 索引、与现有/新建包建立关联。模型由通用适配器决定(模型无关)。未配置 LLM API 时退化为单包启发式。
Inputs: text (required), model, scope, provider, +1 more.
memory_linkA
双向关联两个事件包(更新两者 front-matter 的 linked 字段)。
Inputs: a (required), b (required).
memory_queryA
确定性无状态检索:在 id/title/alias/tag/summary 上做关键词匹配,返回按确定性规则排序的 Top-K 候选(命中唯一 ID)。不依赖热度/权重。
Inputs: q (required), top_k.
memory_query_anchorsA
锚点层细粒度召回:在事件包的 anchors 子事件锚点上做关键词匹配,返回命中的子事件(包ID + 锚点标题 + 摘要 + 定位 + 分数)。用于故事包/长正文按剧情节点召回——当 memory_query 命中率低时,anchors 往往能把内容词召回(如「幽影核心」「圣保罗之焰」「纽约之战」)。
Inputs: q (required), top_k.
memory_read_sectionA
按小标题精准读取事件包正文的某一段(而非整包),节省上下文窗口。配合 memory_query_anchors 使用:先 query_anchors 拿到命中的 locator,再用本工具按 locator 取该段正文。heading 为正文里 ## / ### 小标题的片段(包含匹配),可直接用 locator 值。
Inputs: id (required), heading (required).
memory_rebuildA
从所有 .md 的 front-matter 全量重建 index.db。索引损坏时调用——.md 是权威源,重建不丢数据。
Inputs: no named parameters.
memory_writeA
写/改一个事件包:原子写 .md(权威源)+ 确定性 upsert 索引。id 存在则覆盖更新。tags/aliases/linked 为字符串数组。
Inputs: id (required), body, tags, title, +5 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
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.
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.
With 7 tools, the server is well-scoped. Each tool addresses a specific need for managing memory events without unnecessary bloat or deficiency.
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.
Related MCP Connectors
Persistent memory for AI agents across Claude, ChatGPT and any MCP client.
One memory, every AI. A shared, user-owned markdown memory your AI clients read and write over MCP.
Persistent memory, knowledge graph, task management and more for AI agents via MCP.
Persistent, inspectable memory for AI agents with lineage, correction, and a hosted MCP endpoint.
Related MCP Servers
- AlicenseBqualityBmaintenancePersonal multi-LLM memory repository using Markdown as source of truth, SQLite FTS5 for retrieval, and MCP tools for search, context, and write proposals.74Apache 2.0
- AlicenseCqualityBmaintenanceLocal-first, governable long-term memory for AI agents. Provides SQLite-backed storage, cross-session recall, and traceable memory corrections through a standard MCP interface.4026 PyPI1MIT
- AlicenseAqualityBmaintenanceProvides AI agents with a local, private Markdown-based memory vault and SQLite search. Enables agents to search, read, list, and traverse linked knowledge pages via MCP with zero external runtime dependencies.79MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents to maintain lossless, queryable long-term project memory through local SQLite storage, bi-temporal history, hybrid retrieval, and Git-backed Markdown mirrors, exposed via MCP tools and resources.123 npm1Apache 2.0