Skip to main content
Glama

Файловый MCP-сервер для памяти агента

mcp-agent-memory MCP server

MCP-сервер, который предоставляет доступ к agent-memory-daemon любому MCP-совместимому клиенту — Kiro (CLI и IDE), Claude Desktop, Cursor и другим.

Демон выполняет мыслительные операции (консолидация + извлечение); этот сервер является легким мостом к файловой системе, чтобы агенты могли читать, добавлять и искать информацию в памяти через протокол Model Context Protocol.

Как это работает

 ┌──────────────┐     MCP/stdio     ┌────────────────────┐     filesystem      ┌────────────────────────┐
 │ Kiro / Claude│ ◄───────────────► │ mcp-server-memory  │ ◄─────────────────► │ agent-memory-daemon    │
 │   / Cursor   │                   │  (this package)    │   ~/.agent-memory/   │  (runs in background)  │
 └──────────────┘                   └────────────────────┘                     └────────────────────────┘
  • MCP-сервер читает/записывает файлы в директории ~/.agent-memory/

  • Демон отслеживает ту же директорию и выполняет проходы консолидации и извлечения

  • Они никогда не взаимодействуют друг с другом напрямую — файловая система является контрактом

Related MCP server: Recall

Доступные инструменты

Инструмент

Назначение

memory_read

Загрузка индекса MEMORY.md (и опционально файлов тем) в контекст агента

memory_append_session

Запись сводки сессии, из которой демон позже извлечет воспоминания

memory_search

Поиск подстроки в файлах памяти

memory_daemon_status

Проверка работы демона консолидации (только для macOS LaunchAgent)

Установка

npm install -g mcp-agent-memory

Быстрый старт (интерактивный мастер настройки)

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

mcp-agent-memory --setup

Он задает шесть вопросов:

  1. Директория памяти — где находится .agent-memory/ (по умолчанию ~/.agent-memory)

  2. Установить демон консолидации? — выберите "no" для режима только MCP (агенты могут читать/писать/искать в памяти, но без автоматической консолидации)

  3. LLM-бэкенд — bedrock, openai или kiro (пропускается, если вы отказались от демона)

  4. Настройки консолидации — min_hours, min_sessions, интервал извлечения, макс. количество символов

  5. Режим запуска — standalone (запуск вручную) или launchagent (автозапуск при входе в систему, только для macOS)

  6. Директория логов + TTL — куда сохранять логи и сколько дней их хранить (0 = навсегда)

  7. Регистрация клиентов — автоматическая регистрация MCP-сервера в конфигурациях Kiro, Claude Desktop и/или Cursor (существующие записи MCP сохраняются)

При выборе бэкенда kiro мастер также копирует облегченного агента в ~/.kiro/agents/memconsolidate.json, что сокращает использование токенов примерно в 7 раз (см. Kiro backend).

При выборе launchagent мастер проверяет, установлен ли agent-memory-daemon (и предлагает выполнить npm install -g, если нет), а затем регистрирует и запускает plist.

Справочник CLI

mcp-agent-memory                       # run as an MCP server (normal mode — clients spawn it)
mcp-agent-memory --setup               # first-time interactive setup
mcp-agent-memory --configure           # re-run most steps; can add/remove the daemon later
mcp-agent-memory --remove              # interactive uninstall (backup memory, clean configs)

# macOS LaunchAgent control:
mcp-agent-memory --daemon status       # is the daemon running?
mcp-agent-memory --daemon start        # load and start
mcp-agent-memory --daemon stop         # unload (keeps the plist)
mcp-agent-memory --daemon restart      # stop + start
mcp-agent-memory --daemon remove       # unload and delete the plist

--remove сохраняет другие записи в конфигурациях MCP клиентов — удаляется только ключ memory. По умолчанию создается резервная копия ~/.agent-memory/ в директории с временной меткой .bak-*, чтобы вы могли восстановить свои консолидированные воспоминания.

Ручная установка

Если вы предпочитаете пропустить мастер настройки, вот как это сделать вручную.

Установка демона (опционально)

MCP-сервер работает автономно — он просто читает и записывает файлы в ~/.agent-memory/. Воспоминания сохраняются, но они не будут консолидироваться или извлекаться из сессий, пока вы не добавите демон.

npm install -g agent-memory-daemon

# copy the example config
mkdir -p ~/.agent-memory
cp examples/memconsolidate.toml ~/.agent-memory/memconsolidate.toml

# start the daemon
agent-memory-daemon start ~/.agent-memory/memconsolidate.toml

См. examples/memconsolidate.toml для готовой конфигурации, соответствующей структуре директорий, которую ожидает этот MCP-сервер.

Запуск демона при входе в систему (macOS)

Вместо ручного запуска демона зарегистрируйте его как LaunchAgent:

./scripts/daemon.sh start          # install plist, load it, start at login
./scripts/daemon.sh status         # check if it's running
./scripts/daemon.sh stop           # unload (keeps the plist)
./scripts/daemon.sh remove         # unload and delete the plist

Передайте путь к пользовательской конфигурации в качестве второго аргумента: ./scripts/daemon.sh start /path/to/config.toml. Логи сохраняются в ~/.agent-memory/logs/daemon.{out,err}.log. remove оставляет ваши файлы конфигурации и памяти нетронутыми.

Использование Kiro в качестве LLM-бэкенда

Если у вас есть кредиты Kiro, вы можете запускать демон через kiro-cli вместо оплаты вызовов API Bedrock или OpenAI. Это требует agent-memory-daemon ≥ 2.7 (ветка feat/kiro-backend), которая добавляет бэкенд kiro.

[llm_backend]
name = "kiro"
# optional overrides:
# binary = "/custom/path/to/kiro-cli"
# agent = "memconsolidate"          # set to "" to use Kiro's default session context (not recommended)
# model = "claude-sonnet-4-20250514"
# timeoutMs = 300000

Используйте облегченного агента, чтобы сократить использование токенов примерно в 7 раз. По умолчанию каждый вызов kiro-cli chat загружает полный системный промпт Kiro плюс схему каждого MCP-инструмента из вашей глобальной конфигурации — примерно 12–18 тыс. дополнительных входных токенов на вызов. Создайте минимального агента, который пропускает всё это:

cp examples/kiro-agent-memconsolidate.json ~/.kiro/agents/memconsolidate.json

Бэкенд Kiro автоматически передает --agent memconsolidate, поэтому дополнительная настройка не требуется. Измерено на простом промпте: 0.01 кредита с облегченным агентом против 0.07 кредита с настройками по умолчанию (при том же качестве вывода).

См. examples/kiro-agent-memconsolidate.json — у агента установлены mcpServers: {}, tools: [] и useLegacyMcpJson: false, поэтому он не наследует ничего из вашей глобальной конфигурации Kiro.

Настройка клиентов вручную

Мастера --setup и --configure делают это за вас. Этот раздел предназначен для пользователей, которые хотят настроить всё вручную.

Kiro (CLI и IDE)

Отредактируйте ~/.kiro/settings/mcp.json:

{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": ["-y", "mcp-agent-memory"],
      "env": {
        "MEMORY_DIRECTORY": "~/.agent-memory/memory",
        "SESSION_DIRECTORY": "~/.agent-memory/sessions"
      },
      "disabled": false,
      "timeout": 30000
    }
  }
}

Затем спросите Kiro: "Read my memory index." или "Remember this: I prefer pnpm over npm."

Claude Desktop

Отредактируйте ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) или %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": ["-y", "mcp-agent-memory"],
      "env": {
        "MEMORY_DIRECTORY": "~/.agent-memory/memory",
        "SESSION_DIRECTORY": "~/.agent-memory/sessions"
      }
    }
  }
}

Перезапустите Claude Desktop. Инструменты memory_* появятся.

Cursor

Добавьте в ~/.cursor/mcp.json тот же блок сервера.

Переменные окружения

Переменная

По умолчанию

Описание

MEMORY_DIRECTORY

~/.agent-memory/memory

Где демон хранит консолидированные файлы памяти

SESSION_DIRECTORY

~/.agent-memory/sessions

Где сохраняются сводки сессий, написанные агентом

Оба пути должны совпадать с теми, что используются в конфигурации вашего agent-memory-daemon.

Рекомендуемый промпт для агента

Попросите агента вызывать memory_read в начале разговора и memory_append_session в конце. Пример правила управления для Kiro (~/.kiro/steering/memory.md):

At the start of every session, call memory_read (no arguments) to load my memory
index. Only pass `topics` when the task genuinely needs the full content of a
specific topic file.

When you learn something durable about me, my projects, or my preferences, call
memory_append_session with a concise markdown summary. Target 300-800 tokens,
use structured headers and bullets (not prose), and focus on durable findings
and decisions — not play-by-play. Verbose summaries cost more during the
daemon's consolidation pass.

Советы по использованию токенов

У каждого из трех инструментов свой профиль затрат. Несколько практик помогут снизить счета за инференс и консолидацию:

  • memory_read без аргументов возвращает только индекс MEMORY.md (обычно <1 КБ). Предпочитайте этот вариант topics, если вам не нужно полное содержимое.

  • memory_search основан на поиске подстрок и возвращает ≤3 совпадающих строк на файл — это дешевле, чем загрузка целых файлов тем.

  • memory_append_session ничего не стоит во время вызова, но каждая сессия обрабатывается LLM демона во время консолидации. Делайте сводки краткими и структурированными.

  • Периодически консолидируйте или удаляйте старые файлы тем. Запустите mcp-agent-memory --configure — теперь он предупреждает, если ваша директория памяти превышает 25 файлов или 200 КБ.

  • Удаление сессий после извлечения выполняется демоном, а не MCP-сервером. См. конфигурацию agent-memory-daemon для параметров архивации или удаления сессий после их обработки (это предотвращает бесконечное повторное сканирование старых сессий демоном).

Лицензия

MIT

Available Tools

4 tools
memory_append_sessionA

Append a session summary to the sessions directory. The daemon will later extract durable memories from it. Call this at the end of meaningful exchanges. Keep summaries focused on durable findings and decisions (target 300-800 tokens), not play-by-play — longer summaries cost more during consolidation.

ParametersJSON Schema
NameRequiredDescriptionDefault
contentYesMarkdown-formatted session summary. Use structured headers and bullets for better extraction; avoid verbose prose.
sourceNoOrigin tag, e.g., "kiro", "claude-desktop"

TDQS

A4.5/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 discloses that the daemon will later extract memories and that longer summaries incur higher cost. This adds useful behavioral context beyond the simple append.

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?

Three compact sentences, each serves a purpose: action, timing, and content guidelines. No redundancy, front-loaded with core function.

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

Completeness5/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 provides complete guidance: what, when, how, and cost implications. No gaps.

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% description coverage, but description adds significant value by advising on summary focus, token target (300-800), and avoiding verbose prose. This guides the agent beyond schema definitions.

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 'Append a session summary to the sessions directory' with a specific verb and resource. It distinguishes from sibling read tools (memory_read, memory_search) by being a write operation.

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?

Explicitly advises 'Call this at the end of meaningful exchanges' and provides guidelines on summary length and content. No exclusion criteria or alternatives mentioned, but context is clear.

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

memory_daemon_statusA

Check whether the memory consolidation daemon is running. Reports if the daemon is not installed or not available on this platform.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4.2/5.0
Behavior4/5

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

Since no annotations are provided, the description carries the full burden. It discloses that the tool reports if the daemon is not installed or not available, indicating it can return multiple status outcomes. No contradictions with annotations (none provided).

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 core purpose is front-loaded in the first sentence, and the second adds extra detail concisely.

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 the tool's purpose effectively. It explains what the tool does and the possible outcomes (daemon running, not installed, not available). No obvious gaps.

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?

The tool has zero parameters and schema description coverage is 100% (trivially). The description does not need to add parameter information. Baseline for 0 params is 4.

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 the tool checks the running status of the memory consolidation daemon, and also reports if the daemon is not installed or not available on the platform. This distinguishes it from sibling tools (memory_append_session, memory_read, memory_search) which perform different memory operations.

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 usage context (checking daemon status) but does not explicitly state when to use this tool versus alternatives. No exclusions or alternatives are mentioned, though sibling tools have different purposes.

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

memory_readA

Read the agent memory index (MEMORY.md) and optionally specific topic files. Call with no arguments to load only the lightweight index (cheap). Pass topics only when you need the full content of a specific topic file.

ParametersJSON Schema
NameRequiredDescriptionDefault
topicsNoOptional topic file names to load in full (e.g., ["preferences", "projects"]). Omit to return the index only.

TDQS

A4.6/5.0
Behavior4/5

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

No annotations are provided, so the description must disclose behavior. It reveals that calling without arguments is 'cheap' (lightweight), implying topic file retrieval is more expensive. This adds useful context beyond the schema, though it could further clarify error handling or return format.

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, front-loaded with the core purpose, then a follow-up sentence with usage details. No filler or redundancy.

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 read tool with one optional parameter, the description covers the main usage. However, without an output schema, it lacks details on the return format (e.g., structure of the index or topic file content). This is a minor gap.

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%, but the description adds meaning: it explains that the topics parameter triggers full content retrieval, while omitting it returns the index. This informs the agent of the parameter's purpose beyond data typing.

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 'Read the agent memory index (MEMORY.md) and optionally specific topic files.' It identifies the action (read) and resource (memory index/topic files), and distinguishes from siblings by specifying the no-arguments vs. topics usage.

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?

Explicit guidance: 'Call with no arguments to load only the lightweight index (cheap). Pass topics only when you need the full content of a specific topic file.' This tells the agent when to use each mode, effectively differentiating between lightweight and full retrieval.

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.

  1. 2 tool updatesv1.0.3
    • Addedmemory_daemon_status
    • Changedmemory_search1 field changed
      • addedInput schema / properties / query / description
        Added value: +"Substring to search for across all memory files (case-insensitive)"
  2. 3 tool updatesv1.0.0
    • First observedmemory_append_session
    • First observedmemory_read
    • First observedmemory_search

TDQS

A4.2/5.0

Scored across 4 tools

Disambiguation5/5

Each tool serves a distinct purpose: appending sessions, checking daemon status, reading memory index, and searching. No overlaps or ambiguities.

Naming Consistency5/5

All tools follow a consistent pattern: 'memory_' prefix followed by a descriptive verb or verb_noun (append_session, daemon_status, read, search). Naming is predictable and clear.

Tool Count5/5

With 4 tools, the surface is concise and well-scoped for a memory management server. Each tool addresses a core operation without redundancy.

Completeness4/5

The tools cover essential operations (append, read, search, status). Missing update/delete might be a minor gap, but the memory consolidation daemon likely handles lifecycle, making this acceptable.

Maintenance

ActivityNo data
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Open-source MCP memory server for AI agents — persistent, searchable, tiered memory across sessions. Works over stdio (Cursor, Claude Desktop) or HTTP+SSE. MIT licensed.
    8
    MIT
  • A
    license
    A
    quality
    B
    maintenance
    Gives your AI persistent memory across conversations. Stores facts automatically, finds them by meaning using hybrid search with query expansion, and organizes everything into topics without manual tagging.
    18
    1
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    @memofs/mcp-server lets AI coding agents (Claude Code, Claude Desktop, Codex, Cursor, opencode, Gemini CLI, GitHub Copilot, Zed, and any other MCP client) securely read and write MemoFS memory through standard Model Context Protocol tools.
    6
    MIT