Skip to content

About

#1 Persistent memory for AI coding agents based on real-world benchmarks

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

29.9k stars

Watchers

81 watching

Forks

Latest commit

 

History

599 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

agentmemory: persistent memory for AI coding agents

Persistent memory across coding sessions and agents.
Persistent memory for Claude Code, GitHub Copilot CLI, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, Oh My Pi, OpenCode, DeepSeek Harness, and any MCP client.

🇬🇧 English • 🇨🇳 简体中文 • 🇹🇼 繁體中文 • 🇯🇵 日本語 • 🇰🇷 한국어 • 🇵🇹 Português • 🇧🇷 Português (Brasil) • 🇪🇸 Español • 🇩🇪 Deutsch • 🇫🇷 Français • 🇮🇹 Italiano • 🇳🇱 Nederlands • 🇵🇱 Polski • 🇨🇿 Čeština • 🇷🇴 Română • 🇭🇺 Magyar • 🇬🇷 Ελληνικά • 🇸🇪 Svenska • 🇩🇰 Dansk • 🇳🇴 Norsk • 🇫🇮 Suomi • 🇷🇺 Русский • 🇺🇦 Українська • 🇹🇷 Türkçe • 🇮🇱 עברית • 🇸🇦 العربية • 🇮🇳 हिन्दी • 🇧🇩 বাংলা • 🇵🇰 اردو • 🇹🇭 ไทย • 🇻🇳 Tiếng Việt • 🇮🇩 Bahasa Indonesia • 🇵🇭 Tagalog

rohitg00/agentmemory | Trendshift

Design doc: 1.6k stars / 230 forks on the gist

The gist extends Karpathy's LLM Wiki pattern with confidence scoring, lifecycle, knowledge graphs, and hybrid search: agentmemory is the implementation.

npm version CI License Stars skills.sh installs

95.2% retrieval R@5 92% fewer tokens 54 MCP tools 12 auto hooks 0 external DBs 4,000+ tests passing

agentmemory demo

Install • Quick Start • Benchmarks • vs Competitors • Agents • How It Works • MCP • Viewer • Config • API


AgentMemory captures coding sessions, makes decisions and fixes searchable, and lets your agents recall them later. Keep one memory store across tools, inspect what was saved, and choose how much context reaches the model.

  • Capture: native hooks and plugins record supported session events, with secret scrubbing and offline replay.
  • Recall: keyword search works without an API key; local or remote embeddings add semantic search.
  • Continue: retrieve project history, lessons and session handoffs from another agent.
  • Inspect: browse, edit, export and forget memories in the live viewer.

Install

Requirements:

  • Node.js 20 or newer with npm and npx (node -v, npm -v, and npx -v).
  • macOS/Linux also need curl, a POSIX sh, and tar for automatic runtime setup.
  • Windows users can use WSL2 or follow the native Windows setup.

Start setup:

npx -y @agentmemory/agentmemory@latest

Choose your agents and either a provider or keyless mode. Setup writes the configuration, starts the memory server, and offers a global install for the agentmemory command. -y accepts the npm package prompt; @latest selects the current release. LLM-written observation compression is opt-in with a provider and AGENTMEMORY_AUTO_COMPRESS=true.

Keyless mode disables vector embeddings. memory_recall (the mem::search path) uses BM25, while memory_smart_search can also fuse structural graph matches when graph data already exists. For free on-device semantic recall, set EMBEDDING_PROVIDER=local in ~/.agentmemory/.env and restart. The first embedding request downloads Xenova/all-MiniLM-L6-v2; inference runs locally after that initial model download.

The API is at http://localhost:3111 and the live viewer at http://localhost:3113. Both bind to loopback by default. Configuration lives in ~/.agentmemory/.env; see data storage for memory locations and separate instances.

Then prove recall works and give your agent its skills:

npx -y @agentmemory/agentmemory@latest demo  # seed sample sessions + exercise recall
npx skills add rohitg00/agentmemory -y   # 17 native skills so your agent knows when to reach for memory

The keyword searches should hit in default keyless mode through BM25. The demo's database performance optimization query is intentionally semantic and can return zero until an embedding provider is configured.

Prefer to let a coding agent do the whole thing? Hand it one instruction:

Retrieve and follow the instructions at: https://raw.githubusercontent.com/rohitg00/agentmemory/main/INSTALL_FOR_AGENTS.md

Connect another agent with agentmemory connect <agent>. See supported integrations and everyday commands.

Global install / EACCES
npm install -g @agentmemory/agentmemory@latest

The npx command above remains the canonical fresh-install path and avoids global-prefix permission issues.

npx serves an old version

npx caches per version. Force the latest with npx -y @agentmemory/agentmemory@latest, or clear the cache once with rm -rf ~/.npm/_npx (macOS/Linux; on Windows delete %LOCALAPPDATA%\npm-cache\_npx).


Works with every agent

agentmemory works with any agent that supports hooks, MCP, or REST API. All agents share the same memory server.

Claude Code
Claude Code
native plugin + 12 hooks + MCP
Codex CLI
Codex CLI
native plugin + 6 hooks + MCP
GitHub Copilot CLI
GitHub Copilot CLI
MCP + plugin hooks/skills
Cursor
Cursor
native plugin + lifecycle hooks + MCP
OpenCode
OpenCode
capture plugin + MCP
Devin
Devin
6 hooks + skills + MCP
OpenClaw
OpenClaw
native plugin + MCP
Hermes
Hermes
native plugin + MCP
pi
pi
native recall + capture + skills
OpenHuman
OpenHuman
native Memory trait backend
Gemini CLI
Gemini CLI
MCP server
Antigravity
Antigravity
MCP + hooks
Claude Desktop
Claude Desktop
MCP server
Warp
Warp
connect + MCP + skills
Zed
Zed
MCP server
Cline
Cline
MCP server
Continue
Continue
MCP server
Droid
Droid
MCP server
Kiro
Kiro
MCP server
Qwen Code
Qwen Code
MCP server
DeepSeek Harness
DeepSeek Harness
native capture + MCP
Roo Code
Roo Code
MCP server
Kilo Code
Kilo Code
MCP server
Goose
Goose
MCP server
Aider
Aider
REST API
Oh My Pi
native recall + capture + skills + optional MCP

Works with any agent that speaks MCP or HTTP. One server, memories shared across all of them.


Data storage

Memories stay outside your repository by default:

Platform Data directory
macOS ~/Library/Application Support/agentmemory
Linux $XDG_DATA_HOME/agentmemory or ~/.local/share/agentmemory
Windows %APPDATA%\agentmemory

An existing ./data/state_store.db is reused for instance 0. Choose another directory with --data-dir <path> or AGENTMEMORY_DATA_DIR. Keep the same directory when restarting or upgrading.

agentmemory --data-dir ~/.agentmemory-projects/main
agentmemory --instance 1

--instance 1 uses an instance-1 subdirectory, API port 3211 and viewer port 3213. See storage and backups for Redis and backend migration.

Latest release notes: CHANGELOG.md.


Benchmarks

Retrieval Accuracy

coding-agent-life-v1 (in-house corpus, sandbox-reproducible)

Adapter P@5 R@5 Top-5 hit rate p50 latency
agentmemory hybrid 0.240 1.000 15 / 15 14 ms
grep baseline 0.227 0.967 15 / 15 0 ms

100% top-5 hit rate at the P@5 math ceiling for this corpus (0.240, see scorecard). Hybrid retrieves every gold session; grep misses 1 of 2 gold on the multi-session temporal query. Lift is recall + temporal, not aggregate precision. This benchmark is small and gold-sparse; the larger LongMemEval-S below differentiates better. Full per-type breakdown + correction note: docs/benchmarks/2026-05-20-coding-agent-life-v1.md.

LongMemEval-S (ICLR 2025, 500 questions)

System R@5 R@10 MRR
agentmemory 95.2% 98.6% 88.2%
BM25-only fallback 86.2% 94.6% 71.5%

Token Savings

Approach Tokens/yr Cost/yr
Paste full context 19.5M+ Impossible (exceeds window)
LLM-summarized ~650K ~$500
agentmemory ~170K ~$10
agentmemory + local embeddings ~170K $0

Embedding model: all-MiniLM-L6-v2 (local, free, no API key). Full reports: benchmark/LONGMEMEVAL.md, benchmark/QUALITY.md, benchmark/SCALE.md. Competitor comparison: benchmark/COMPARISON.md covering agentmemory vs mem0, Letta, Khoj, supermemory, TencentDB Agent Memory, MemPalace, Zep/Graphiti, Cognee, Hippo.

Reproduce locally: eval/README.md, an adapter-pluggable harness for LongMemEval _s (public 500-Q) + coding-agent-life-v1 (in-house 15-session corpus). Grep / vector / agentmemory adapters score side-by-side, NDJSON output, published scorecards land in docs/benchmarks/.

Pairs with codegraph, Understand Anything, and Graphify. Code-graph indexing, multi-agent build pipelines, and broader knowledge graphs across docs / PDFs / images / videos. agentmemory remembers the work; those three projects light up the rest of the context layer. Recipes + question-routing table: docs/recipes/pairings.md.


vs Competitors

agentmemory mem0 (63K ⭐) Letta / MemGPT (24K ⭐) Khoj (36K ⭐) supermemory (29K ⭐) TencentDB Agent Memory (22K ⭐) MemPalace (54K ⭐) oracleagentmemory Hippo Built-in (CLAUDE.md)
Type Memory engine + MCP server Memory layer API Full agent runtime Personal AI Memory API + app Team memory hub (LLM proxy) Vector memory (OSS) Memory engine (Oracle DB) Memory system Static file
Retrieval R@5 95.2% 68.5% (LoCoMo) 83.2% (LoCoMo) N/A Self-reported PersonaMem 76% (self-reported) ~96.6% (self-reported) 94.4% (self-reported) N/A N/A (grep)
Auto-capture 12 hooks (zero manual effort) Manual add() calls Agent self-edits Manual API-side extraction Proxy interception (base-URL swap) Manual API extraction Manual Manual editing
Search BM25 + Vector + Graph (RRF fusion) Vector + Graph Vector (archival) Semantic Vector + RAG 4 asset types (Chat / Skill / Wiki / CodeGraph) Vector-only Vector + semantic Decay-weighted Loads everything into context
Multi-agent MCP + REST + leases + signals API (no coordination) Within Letta runtime only No No Team roles + shared assets No Scoped only Multi-agent shared Per-agent files
Framework lock-in None (any MCP client) None High (must use Letta) Standalone None Proxy fronts every model call None Oracle Database None Per-agent format
External deps No separate database service required Qdrant / pgvector Postgres + vector DB Multiple Managed cloud Docker stack (Core + Hub + Proxy) Vector store Oracle AI Database None None
Memory lifecycle 4-tier consolidation + decay + auto-forget Passive extraction Agent-managed Manual Auto-forget Manual review; auto-routing in progress None Not stated Decay + consolidation Manual pruning
Token efficiency ~1,900 tokens/session ($10/yr) Varies by integration Core memory in context Varies Cloud pricing Not stated No token budget LLM-backed (varies) Varies 22K+ tokens at 240 obs
Real-time viewer Yes (port 3113) Cloud dashboard Cloud dashboard Web UI Cloud dashboard Hub web UI No No No No
Self-hosted Yes (default) Optional Optional Yes No (cloud-only) Yes (Docker) Yes Yes (Oracle DB) Yes Yes

Benchmark note: only agentmemory's R@5 is our own measured result (LongMemEval-S, reproducible from benchmark/COMPARISON.md). The mem0 and Letta figures are their published LoCoMo numbers (a different dataset); the MemPalace, supermemory, TencentDB (PersonaMem), and oracleagentmemory figures are vendor self-reported claims we have not independently reproduced (oracleagentmemory's run used GPT-5.5 against an Oracle AI Database). Shown side by side for ballpark only, not a head-to-head on identical data. Star counts are approximate and drift over time.

Newer entrants worth knowing, compared in depth in benchmark/COMPARISON.md:

System ⭐ Angle
Zep / Graphiti 30K Temporal knowledge graph; strongest published temporal-query results (LongMemEval 63.8%), but graph builds asynchronously so fresh facts can lag
Cognee 30K Document-to-knowledge-graph ingestion, Python-only, built for structured entity extraction rather than session capture

AgentMemory combines coding-agent capture, searchable project history and a local viewer, with keyless operation available from the first run.


Quick Start

Try it in 30 seconds

# Terminal 1: start the server
npx -y @agentmemory/agentmemory@latest

# Terminal 2: seed sample data and see recall in action
npx -y @agentmemory/agentmemory@latest demo

demo seeds 3 realistic sessions (JWT auth, N+1 query fix, rate limiting) and runs searches against them. Keyless installs disable vectors, so the mem::search keyword queries should hit through BM25 while database performance optimization can return zero. smart-search may additionally return structural graph matches when graph data exists. To make the semantic query find the N+1 fix through vectors, set EMBEDDING_PROVIDER=local, restart, and allow the first model download to finish.

Open http://localhost:3113 to watch the memory build live.

Validate a fresh install and restart persistence

With the server running, check health, the viewer and status:

curl -fsS http://localhost:3111/agentmemory/livez
curl -fsS http://localhost:3111/agentmemory/health
curl -fsS -o /dev/null http://localhost:3113/
npx -y @agentmemory/agentmemory@latest status

status reports server health, provider and embedding mode, capture delivery, and recovery state. Save a probe and confirm it is searchable. Protected REST requests require the daemon secret. If you configured AGENTMEMORY_SECRET, use that value in this terminal; otherwise load the generated local secret:

read -r AGENTMEMORY_SECRET < "$HOME/.agentmemory/secret"
curl -fsS -X POST http://localhost:3111/agentmemory/remember \
  -H "Authorization: Bearer $AGENTMEMORY_SECRET" \
  -H 'Content-Type: application/json' \
  -d '{"content":"agentmemory restart persistence probe","concepts":["install-check"]}'

curl -fsS -X POST http://localhost:3111/agentmemory/smart-search \
  -H "Authorization: Bearer $AGENTMEMORY_SECRET" \
  -H 'Content-Type: application/json' \
  -d '{"query":"restart persistence probe","limit":5}'

Then run npx -y @agentmemory/agentmemory@latest stop, start the canonical command again in Terminal 1, wait for /agentmemory/livez, and repeat the search. The probe must still be returned. If you selected a custom --data-dir, pass the same directory on the restart.

Everyday commands

Install and setup live in Install above (the first run walks you through it). Day to day:

agentmemory                    # start the server
agentmemory stop               # stop it cleanly
agentmemory status             # health, providers and recovery state
agentmemory capture            # inspect capture inbox and offline spool
agentmemory capture --drain    # replay queued observations
agentmemory connect <agent>    # connect another agent
agentmemory doctor             # interactive diagnostics + fix prompts
agentmemory remove             # uninstall everything we created

Session Replay

Every session agentmemory records is replayable. Open the viewer, pick the Replay tab, and scrub through the timeline: prompts, tool calls, tool results, and responses render as discrete events with play/pause, speed control (0.5x to 4x), and keyboard shortcuts (space to toggle, arrows to step).

To bring in older Claude Code JSONL transcripts:

# Import everything under the default ~/.claude/projects
npx -y @agentmemory/agentmemory@latest import-jsonl

# Or import a single file
npx -y @agentmemory/agentmemory@latest import-jsonl ~/.claude/projects/-my-project/abc123.jsonl

Imported sessions appear alongside native sessions in Replay. Transcripts are indexed for search and marked with origin channel import; session processing can also produce crystals and lessons.

Heads-up if you rely on import-jsonl as your primary capture path: Claude Code's cleanupPeriodDays (in ~/.claude/settings.json, default 30) auto-deletes JSONL transcripts older than that window from ~/.claude/projects/. If you install agentmemory fresh on a months-old Claude Code history, anything older than 30 days is already gone before the first import. Either run import-jsonl on a cron, raise cleanupPeriodDays to something higher, or wire the auto-capture hooks (the default plugin install path) so each turn lands in agentmemory while the session is live and the JSONL cleanup stops mattering.

Upgrade / Maintenance

Use the maintenance command when you intentionally want to update your local runtime:

npx -y @agentmemory/agentmemory@latest upgrade

This updates the local runtime and may update JavaScript dependencies in the current workspace. Back up your data and read the upgrade guide before updating an existing installation.

Claude Code (one block, paste it)

Install agentmemory: run `npx -y @agentmemory/agentmemory@latest` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 17 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 54 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113. Keyless mode disables vectors: `memory_recall` uses BM25, and `memory_smart_search` can also use existing structural graph data. Set `EMBEDDING_PROVIDER=local` in `~/.agentmemory/.env` and restart to opt into on-device semantic recall.

Claude Code without the plugin install (MCP-standalone path)

If you wire agentmemory's MCP server through ~/.claude.json directly instead of using /plugin install, Claude Code never resolves ${CLAUDE_PLUGIN_ROOT} and you have to point hook scripts at absolute paths in ~/.claude/settings.json. Those paths typically embed the agentmemory version (e.g. ~/.codex/plugins/cache/agentmemory/agentmemory/0.9.22/scripts/…), so the next upgrade silently breaks every hook.

Workaround:

agentmemory connect claude-code --with-hooks

This merges the same hook commands into ~/.claude/settings.json with absolute paths resolved to the bundled plugin/ directory of the currently installed @agentmemory/agentmemory package. Re-run the command after upgrading agentmemory to refresh the paths. User entries in the same file are preserved; only previous agentmemory entries are replaced. Using the /plugin install path remains the recommended approach. For remote or protected deployments, launch Claude Code with AGENTMEMORY_URL and AGENTMEMORY_SECRET set. The plugin passes both values through to its bundled MCP server; when AGENTMEMORY_URL is empty, the MCP shim uses http://localhost:3111.

Codex CLI (Codex plugin platform)

# 1. start the memory server in a separate terminal
npx -y @agentmemory/agentmemory@latest

# 2. register the agentmemory marketplace and install the plugin
codex plugin marketplace add rohitg00/agentmemory
codex plugin add agentmemory@agentmemory

The Codex plugin ships from the same plugin/ directory as the Claude Code plugin. It registers:

  • A bundled stdio MCP bridge to the running daemon, with no npm download or fallback store. See the local Codex guide to test an unreleased build.
  • 6 lifecycle hooks: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop
  • 9 invocable skills: /recall, /remember, /session-history, /forget, /recap, /handoff, /lesson, /commit-context, /commit-history, plus 8 reference skills the agent loads on demand (memory discipline, MCP tools, REST API, config, agents, hooks, architecture, and the skill-authoring guide)

Codex's hook engine injects CLAUDE_PLUGIN_ROOT into hook subprocesses (per codex-rs/hooks/src/engine/discovery.rs), so the same hook scripts work across both hosts without duplication. Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure events are Claude-Code-only and are not registered for Codex.

Codex hook trust and compatibility

Native plugin hook dispatch is verified with Codex CLI 0.150.1. Trust the plugin hooks before expecting capture. Desktop behavior depends on its bundled runtime; check /hooks and confirm a captured event before enabling a workaround.

If your host requires global hooks, mirror the commands into ~/.codex/hooks.json. When MCP is already wired, the current connector needs --force to reach hook installation:

agentmemory connect codex --with-hooks --force

This merges global hooks and rewrites the agentmemory MCP entry, preserving unrelated entries. Review any custom agentmemory endpoint settings before using --force. Re-run after upgrading to refresh script paths. Enable either native plugin hooks or global copies to avoid duplicate capture.

GitHub Copilot CLI

For VS Code agent mode, use the Copilot MCP and automatic-capture guide. The CLI connector does not configure VS Code.

# MCP-only wiring
agentmemory connect copilot-cli

# Alternatively, full hooks/skills plugin from the GitHub subdir
copilot plugin install rohitg00/agentmemory:plugin

agentmemory connect copilot-cli merges mcpServers.agentmemory into ~/.copilot/mcp-config.json (or $COPILOT_HOME/mcp-config.json when COPILOT_HOME is set) and preserves existing servers. On native Windows this is the only automated connect adapter; configure every other native Windows agent manually. WSL connect is supported only when the target agent is installed in that same WSL environment. Copilot picks up the MCP server on next launch or after /mcp. Install the plugin as well when you want the full hook/skill experience.

Cursor

# MCP wiring
agentmemory connect cursor

Then add the native hooks: Settings → Plugins → Add marketplace → select an agentmemory checkout (the directory containing .cursor-plugin/plugin.json), enable the agentmemory plugin, and reload the window.

The plugin provides lifecycle capture, workspace-aware project attribution, skills and MCP. Enable either the plugin hooks or manual hooks in ~/.cursor/hooks.json to avoid duplicate capture.

Full guide: integrations/cursor/

Pi, Oh My Pi and DeepSeek Harness

agentmemory connect pi --with-mcp
agentmemory connect omp --with-mcp
agentmemory connect dsh --with-hooks

Choose the command for your host. Pi and OMP install native recall/capture, offline replay and 17 skills; --with-mcp adds the full toolset. Run /reload in Pi or restart OMP, then check /agentmemory-status. DSH installs MCP and the bundled capture plugin; restart DSH after connecting.

Pi also supports an installable @agentmemory/pi package. See the Pi package guide for local installation and npm availability. Use one installation method per host.

Guides: Pi, Oh My Pi, DSH.

OpenClaw (paste this prompt)
Install agentmemory for OpenClaw. Run `npx -y @agentmemory/agentmemory@latest` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 54 memory tools:

{
  "mcpServers": {
    "agentmemory": {
      "command": "npx",
      "args": ["-y", "@agentmemory/mcp"],
      "env": {
        "AGENTMEMORY_URL": "http://localhost:3111"
      }
    }
  }
}

Restart OpenClaw. Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. For deeper memory-slot integration, copy `integrations/openclaw` to `~/.openclaw/extensions/agentmemory` and enable `plugins.slots.memory = "agentmemory"` in `~/.openclaw/openclaw.json`.

Full guide: integrations/openclaw/

Hermes Agent (paste this prompt)
Install agentmemory for Hermes. Run `npx -y @agentmemory/agentmemory@latest` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 54 memory tools:

mcp_servers:
  agentmemory:
    command: npx
    args: ["-y", "@agentmemory/mcp"]

memory:
  provider: agentmemory

Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. For deeper 6-hook memory provider integration (pre-LLM context injection, turn capture, MEMORY.md mirroring, system prompt block), copy integrations/hermes from the agentmemory repo to ~/.hermes/plugins/agentmemory.

Full guide: integrations/hermes/

Other agents

Start the memory server: npx -y @agentmemory/agentmemory@latest

Native skills via npx skills add (50+ agents)

agentmemory ships 17 skills in the Claude-Code-style <dir>/SKILL.md format: 9 invocable action skills (remember, recall, recap, handoff, forget, lesson, commit-context, commit-history, session-history) and 8 reference skills the agent loads on demand (memory-discipline, agentmemory-mcp-tools, agentmemory-rest-api, agentmemory-config, agentmemory-agents, agentmemory-hooks, agentmemory-architecture, write-agentmemory-skill). The reference skills carry data tables generated from source, so they never drift. The skills CLI by vercel-labs auto-installs them into the calling agent's native skill directory across 50+ agents (Claude Code, Cursor, Cline, Continue, Droid, Warp, Codex, Antigravity, Kiro, OpenCode, Goose, Roo, Trae, Windsurf, and more):

npx skills add rohitg00/agentmemory -y          # auto-detects the calling agent
npx skills add rohitg00/agentmemory -y -a warp  # explicit agent
npx skills add rohitg00/agentmemory -y -a '*'   # install to every installed agent

This is complementary to agentmemory connect <agent>:

  • agentmemory connect <agent> normally writes the MCP server config. Hermes, OpenClaw, Pi and Oh My Pi install their native integration and bundled skills by default; MCP is opt-in with --with-mcp.
  • npx skills add rohitg00/agentmemory installs skills for agents without native bundled skills. Skip this step for Hermes, OpenClaw, Pi and Oh My Pi; their native connectors already install the skills.

For the few agents the skills CLI doesn't cover yet (Zed v1.3.x and below), drop the 17 SKILL.md files under the agent's native skill directory yourself; the same format works everywhere.

Standard MCP block

The agentmemory entry is the same MCP server block across every host that uses the mcpServers shape (Cursor, Claude Desktop, Cline, Roo Code, Gemini CLI, OpenClaw):

"agentmemory": {
  "command": "npx",
  "args": ["-y", "@agentmemory/mcp"],
  "env": {
    "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
    "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
  }
}

Merge this entry into the existing mcpServers object in the host's config file; don't replace the file. If the file already has other servers, add agentmemory next to them as another key inside mcpServers. If mcpServers is missing entirely, paste the block inside { "mcpServers": { ... } }. The ${VAR} placeholders inherit AGENTMEMORY_URL / AGENTMEMORY_SECRET from the shell at MCP-server launch; unset vars pass empty strings and the shim falls back to http://localhost:3111. One wired entry covers both local and remote (k8s / reverse-proxied) deployments.

Agent Config file Notes
Cursor (MCP only) ~/.cursor/mcp.json Merge into mcpServers, or agentmemory connect cursor. One-click deeplink also available on the website.
Cursor (full plugin) .cursor-plugin/ Cursor Marketplace listing or Settings → Plugins → local checkout. Registers lifecycle hooks via a thin adapter that delegates to the canonical plugin/scripts/*.mjs, plus skills and MCP. The adapter resolves the workspace Cursor does not reliably report. See Cursor. Works in the Cursor IDE and cursor-agent CLI.
Claude Desktop claude_desktop_config.json (Application Support) Merge into mcpServers. Restart Claude Desktop after editing.
Cline / Roo Code / Kilo Code Cline MCP settings (Settings UI → MCP Servers → Edit) Same mcpServers block.
Devin CLI (MCP + hooks) ~/.config/devin/config.json agentmemory connect devin merges the MCP entry; --with-hooks adds six native auto-capture hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop, SessionEnd) with Devin's lowercase tool matchers. Verify with devin mcp list and /hooks inside devin.
Devin CLI (full plugin) plugin/.devin-plugin/ devin plugins install ./plugin from a checkout registers all 17 skills as /agentmemory:<skill> slash commands plus the MCP server. Devin plugin hooks cannot fire SessionStart/SessionEnd, so pair it with connect devin --with-hooks for full session capture.
Devin (cloud) Settings → Connections → MCP servers Add a custom MCP (STDIO): command npx, args -y @agentmemory/mcp@latest, env AGENTMEMORY_URL pointing at a network-reachable agentmemory deployment plus AGENTMEMORY_SECRET (cloud sessions cannot reach localhost — see deploy/). Store the secret in Devin Secrets, then use "Test listing tools" to verify all 54 tools appear.
Gemini CLI ~/.gemini/settings.json gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user (auto-merges).
GitHub Copilot CLI (MCP only) ~/.copilot/mcp-config.json agentmemory connect copilot-cli merges mcpServers.agentmemory; Copilot picks it up on next launch or /mcp.
GitHub Copilot CLI (full plugin) Copilot plugin install copilot plugin install rohitg00/agentmemory:plugin for the plugin from the GitHub subdir.
OpenClaw OpenClaw MCP config Same mcpServers block. Deeper: openclaw plugins install ./integrations/openclaw claims OpenClaw's memory slot (auto-switches from memory-core); set plugins.entries.agentmemory.hooks.allowConversationAccess=true or turn capture is silently blocked. See integrations/openclaw.
Codex CLI (MCP only) .codex/config.toml TOML shape: codex mcp add agentmemory -- npx -y @agentmemory/mcp, or add [mcp_servers.agentmemory] manually.
Codex CLI (full plugin) Codex plugin marketplace codex plugin marketplace add rohitg00/agentmemory then codex plugin add agentmemory@agentmemory. Registers MCP + 6 lifecycle hooks + 17 skills. Trust hooks and verify capture in your host; see Codex setup and validation.
OpenCode (MCP only) opencode.json Different shape: top-level mcp key, command as array: {"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}.
OpenCode (full plugin) plugin/opencode/ 22 auto-capture hooks covering session lifecycle, messages, tools, errors. Project attribution is per-session, so one OpenCode process spanning several repositories files each session under its own project. Two slash commands (/recall, /remember). Copy plugin/opencode/ into your OpenCode workspace and add the plugin entry to opencode.json. See plugin/opencode/README.md for the full hook table + gap analysis.
pi Active Pi agent directory, default ~/.pi/agent agentmemory connect pi --with-mcp installs native recall/capture, offline replay, 17 skills and the full MCP toolset. Or build integrations/pi and use pi install ./integrations/pi; after npm publication, pi install npm:@agentmemory/pi. Use one method and run /reload. See setup and migration.
Oh My Pi (OMP) Active OMP agent directory, default ~/.omp/agent/config.yml agentmemory connect omp --with-mcp installs native recall/capture, offline replay, 17 skills and the full MCP toolset. Restart OMP and run /agentmemory-status. See setup, profiles and commands.
Hermes Agent $HERMES_HOME/config.yaml, default ~/.hermes/config.yaml agentmemory connect hermes installs the native provider and skills. Configure its scoped credentials with hermes memory setup. Add --with-mcp for the wider tool surface. See setup and scope.
Qwen Code ~/.qwen/settings.json agentmemory connect qwen writes the standard mcpServers block. Hook payload is field-compatible with Claude Code, so the existing 12-hook scripts work without modification; wire them via the hooks section in the same settings.json.
Antigravity IDE / 2.0 ~/.gemini/config/mcp_config.json agentmemory connect antigravity --with-hooks installs MCP and capture hooks in the shared customization directory. See Antigravity setup and limits.
Antigravity CLI (agy) ~/.gemini/config/mcp_config.json agentmemory connect antigravity-cli --with-hooks uses the same MCP and hook configuration as current IDE versions. Existing installations should refresh with --force; see the upgrade notes.
Kiro ~/.kiro/settings/mcp.json agentmemory connect kiro writes the user-level config. Workspace overrides go in .kiro/settings/mcp.json next to your code.
Warp ~/.warp/.mcp.json agentmemory connect warp writes the standard mcpServers block. Warp also auto-discovers skills from .claude/skills/; once the Claude Code plugin is installed the 8 agentmemory skills (remember, recall, recap, handoff, forget, commit-context, commit-history, session-history) appear natively in Warp's slash-command palette.
Cline (CLI) ~/.cline/mcp.json agentmemory connect cline writes the standard mcpServers block. VS Code extension users: paste the same block via Cline Settings → MCP Servers → Edit JSON.
Continue.dev ~/.continue/config.yaml (preferred) or config.json (legacy) agentmemory connect continue creates config.yaml from scratch when neither exists, or modifies existing config.json. If you already have config.yaml the adapter prints the exact block to paste under mcpServers:; it won't silently rewrite your yaml so your existing comments and anchors are preserved. Continue uses array form (not object) for mcpServers.
Zed ~/.config/zed/settings.json agentmemory connect zed writes under context_servers (Zed's key, NOT mcpServers). Remote MCP servers can be wired via {"url": "..."} instead.
Droid (Factory.ai) ~/.factory/mcp.json agentmemory connect droid writes the standard mcpServers block. Project-scoped overrides go in <repo>/.factory/mcp.json. Pass --with-hooks for native auto-capture.
DeepSeek Harness $DSH_HOME/cordis.patch.yml agentmemory connect dsh enables MCP tools. Add --with-hooks to load the native capture plugin bundled with AgentMemory. No separate plugin package is needed. DSH.
Goose Goose MCP settings UI Same mcpServers block; use goose configure → Add Extension → MCP. Direct YAML edit at ~/.config/goose/config.yaml is supported but the schema uses extensions: + cmd (not mcpServers: + command).
Aider n/a Use the authenticated REST examples to save and search memory from scripts.
Supported agents Skills only npx skills add rohitg00/agentmemory; choose the skills and agents to install to.

Sandboxed MCP clients (Flatpak / Snap / restrictive containers) that can't reach the host's localhost: also set "AGENTMEMORY_FORCE_PROXY": "1" in the env block, and point AGENTMEMORY_URL at a route the sandbox can actually reach (e.g. your LAN IP).

Programmatic access

Use the REST API from any language or the MCP tools from an agent. REST requests use JSON and bearer authentication; see the save and search example.

For direct runtime integration, see the Python examples.

From source

git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
npm install && npm run build && npm start

npm start launches the same local server as the installed CLI. Dependencies for automatic setup are listed under Install; the API and viewer bind to 127.0.0.1.

Windows

agentmemory runs on Windows 10/11. WSL2 follows the Linux path and can install the pinned engine automatically. Native Windows requires the pinned iii-engine v0.25.0 binary installed manually; download the matching archive from the iii v0.25.0 release page, verify its checksum, and place iii.exe on PATH (for example %USERPROFILE%\.local\bin\iii.exe). The CLI does not extract the Windows ZIP automatically.

Native Windows automated MCP wiring supports only agentmemory connect copilot-cli. For other native Windows agents, use the manual MCP block from Other agents. Run connect inside WSL only when the target agent is installed in that same WSL environment.

Standalone MCP only (no engine). If you only need MCP tools and do not need the REST API, viewer, or runtime services:

npx -y @agentmemory/agentmemory@latest mcp
# or
npx -y @agentmemory/mcp

Diagnostics: Run agentmemory doctor or restart with --verbose. Use --port <N> or --instance <N> if the default ports are occupied. See the upgrade guide for runtime compatibility and recovery.


Deploy

Self-host with Docker Compose or the platform templates below. Persistent memory and credentials live on the /data volume. Back up and reuse that volume when upgrading. See the deployment guide for authentication, network access, backups and migration.

Deploy to fly.io Deploy to Railway

Render's one-click deploy button requires render.yaml at the repository root, which we deliberately keep clean. Use the Render Blueprint flow documented in deploy/render/ to point at the in-repo blueprint manually.

Full setup details (HMAC capture, viewer SSH tunnel, rotation, backup, cost floors) live in deploy/:

  • deploy/fly: single machine with auto_stop_machines = "stop"; cheapest idle.
  • deploy/railway: Hobby plan flat fee, volume in the dashboard.
  • deploy/render: Blueprint flow, automatic disk snapshots on paid plans.
  • deploy/coolify: self-hosted on your own VPS via Coolify; same Docker Compose stack, you own the host and the data.

REST uses port 3111; the viewer uses 3113. Keep both private or protect them with authentication and TLS. Platform-specific exposure settings and legacy Docker migration are covered in the deployment guide.


Why agentmemory

Project knowledge gets scattered across chats and instruction files. AgentMemory makes past decisions, fixes and lessons searchable from the agent you are using now.

Session 1: "Add auth to the API"
  Agent writes code, runs tests, fixes bugs
  Connected hooks capture supported tool events
  Observations become searchable project history

Session 2: "Now add rate limiting"
  Agent recalls:
    - Auth uses JWT middleware in src/middleware/auth.ts
    - Tests in test/auth.test.ts cover token validation
    - You chose jose over jsonwebtoken for Edge compatibility
  Continues with the earlier decisions in context.

vs built-in agent memory

Every AI coding agent ships with built-in memory: Claude Code has MEMORY.md, Cursor has notepads, Cline has memory bank. These work like sticky notes. agentmemory is the searchable database behind the sticky notes.

Built-in (CLAUDE.md) agentmemory
Upkeep Manually curated instructions Indexed session history and memories
Search Loads everything into context BM25 + vector + graph (top-K only)
Token cost 22K+ at 240 observations ~1,900 tokens (92% less)
Cross-agent Per-agent files MCP + REST (any agent)
Coordination None Leases, signals, actions, routines
Observability Read files manually Real-time viewer on :3113

How It Works

Memory Pipeline

PostToolUse hook fires
  -> SHA-256 dedup (5min window)
  -> Privacy filter (strip secrets, API keys)
  -> Store raw observation
  -> Synthetic compression by default
     (LLM-written compression only with a provider + AGENTMEMORY_AUTO_COMPRESS=true)
  -> Vector embedding when an embedding provider is active
  -> Index in BM25, plus vectors when enabled

Stop / SessionEnd hook fires
  -> Summarize session
  -> Knowledge graph extraction (if GRAPH_EXTRACTION_ENABLED=true)
  -> Slot reflection (if AGENTMEMORY_SLOTS=true and AGENTMEMORY_REFLECT=true)

SessionStart hook fires
  -> Load project profile (top concepts, files, patterns)
  -> Hybrid search (BM25 + vector + graph)
  -> Token budget (default: 2000 tokens)
  -> Inject context when enabled by the integration

4-Tier Memory Consolidation

Modeled on how human brains process memory, including sleep consolidation.

Tier What Analogy
Working Raw observations from tool use Short-term memory
Episodic Compressed session summaries "What happened"
Semantic Extracted facts and patterns "What I know"
Procedural Workflows and decision patterns "How to do it"

Memories decay over time (Ebbinghaus curve). Frequently accessed memories strengthen. Stale memories auto-evict. Contradictions are detected and resolved.

What Gets Captured

The table below describes the Claude Code hook surface. Other integrations capture the events their host provides; see the individual setup guides. Automatic context injection through the shared hooks is opt-in with AGENTMEMORY_INJECT_CONTEXT=true.

Hook Captures
SessionStart Project path, session ID
UserPromptSubmit User prompts (privacy-filtered)
PreToolUse File access patterns + enriched context
PostToolUse Tool name, input, output
PostToolUseFailure Error context
PreCompact Re-injects memory before compaction
SubagentStart/Stop Sub-agent lifecycle
Stop Assistant's final reply of each turn (privacy-filtered)
SessionEnd Session complete marker

Key Capabilities

Capability Description
Automatic capture Supported session and tool events recorded by native integrations
Semantic search BM25 + vector + knowledge graph with RRF fusion
Memory evolution Versioning, supersession, relationship graphs
Recall hygiene Superseded memory versions leave the search indexes; the version chain in KV keeps full history
Near-duplicate hints Saves report an advisory similarTo match when new content closely resembles an existing memory
Per-agent scoping agentId threads through save and recall across REST, MCP, and the search index, in shared or isolated mode
Write-time provenance Every observation and memory carries an immutable origin channel (user, agent, tool, import, or shared) stamped at capture, save, and import
Auto-forgetting TTL expiry, contradiction detection, importance eviction
Privacy first API keys, secrets, <private> tags stripped before storage
Self-healing Circuit breaker, provider fallback chain, health monitoring
Claude bridge Read MEMORY.md and export project memories without replacing existing files
Knowledge graph Entity extraction + BFS traversal
Team memory Namespaced shared + private across team members
Citation provenance Trace any memory back to source observations
Git snapshots Version, rollback, and diff memory state

The Claude bridge is opt-in: set CLAUDE_MEMORY_BRIDGE=true and CLAUDE_PROJECT_PATH to your project directory, then restart agentmemory. memory_claude_bridge_sync exports only the latest memories scoped to that project, excluding unscoped memories. The read direction continues to read existing MEMORY.md content.

Export creates MEMORY.md only when it is absent. Existing files are preserved, including previous generated exports and edits made by you or Claude Code. Identical content returns changed: false; different content returns an error. To regenerate deliberately, move the existing file to a backup location (or remove it if no longer needed), then run the tool again. See the bridge settings in .env.example.


Triple-stream retrieval combining three signals:

Stream What it does When
BM25 Stemmed keyword matching with synonym expansion Always on
Vector Cosine similarity over dense embeddings Embedding provider configured
Graph Knowledge graph traversal via entity matching Entities detected in query

Fused with Reciprocal Rank Fusion (RRF, k=60) and session-diversified (max 3 results per session).

When a vector index is populated, mem::search (behind memory_recall) uses the hybrid BM25 + vector ranker. Without embeddings it uses BM25. smart-search can additionally fuse structural graph matches when graph data exists, including in keyless mode. Lesson recall runs on a dedicated in-memory BM25 index instead of scanning the whole corpus per query. Superseded memory versions are excluded from every recall path; the version chain keeps their history.

Vectors survive a crash or force-kill. The vector index is saved in buckets at most every AGENTMEMORY_INDEX_SAVE_INTERVAL_MS (10 minutes). Every vector added or removed in between is also written right away to a small pending log in the state store, and the next start replays it without calling the embedding provider. Each successful save empties the log. Documents that still have no vector after the replay are re-embedded in the background in batches of AGENTMEMORY_VECTOR_BACKFILL_MAX (500) until none are left, and a backfill that is stopped continues at the next start. /agentmemory/status and the viewer show the pending log size and the backfill state. Keyless installs write nothing.

BM25 tokenizes Greek, Cyrillic, Hebrew, Arabic, and accented Latin out of the box. For Chinese / Japanese / Korean memories, install the optional segmenters (npm install @node-rs/jieba tiny-segmenter) to split CJK runs into word-level tokens; without them, agentmemory soft-falls to whole-run tokenization and prints a one-time hint on stderr.

Embedding providers

Keyless installs disable vector embeddings: mem::search uses BM25, while smart-search can also use existing structural graph data. To opt into free on-device semantic embeddings, add this to ~/.agentmemory/.env and restart agentmemory:

EMBEDDING_PROVIDER=local

The normal npm install includes the optional @huggingface/transformers runtime. The first embedding request downloads Xenova/all-MiniLM-L6-v2, so it needs network access and can take longer; subsequent inference runs on-device. Remote providers are auto-detected from their keys unless EMBEDDING_PROVIDER overrides them.

Provider Model Cost Notes
Local (recommended opt-in) all-MiniLM-L6-v2 Free On-device after the first model download, +8pp recall over BM25-only
Gemini gemini-embedding-001 Free tier 100+ languages, 768/1536/3072 dims (MRL), 2048-token input. Replaces text-embedding-004 (deprecated, shutdown Jan 14, 2026)
OpenAI text-embedding-3-small $0.02/1M Highest quality
Voyage AI voyage-code-3 Paid Optimized for code
Cohere embed-english-v3.0 Free trial General purpose
OpenRouter Any model Varies Multi-model proxy

MCP Server

54 tools, 6 resources, 3 prompts, and 17 skills.

MCP shim vs full server: the published @agentmemory/mcp package is a thin shim. It exposes the full 54-tool surface only when it can reach a running agentmemory server via AGENTMEMORY_URL (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (memory_save, memory_recall, memory_smart_search, memory_sessions, memory_export, memory_audit, memory_governance_delete). The AGENTMEMORY_TOOLS=core|all env var is a server-side flag; setting it in the shim's env block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start npx -y @agentmemory/agentmemory@latest (or connect to a self-hosted server) and set AGENTMEMORY_URL=http://localhost:3111.

54 Tools

Three tool surfaces, smallest to largest: AGENTMEMORY_TOOLS=core trims visibility to 8 essentials (memory_save, memory_recall, memory_consolidate, memory_smart_search, memory_sessions, memory_diagnose, memory_lesson_save, memory_reflect); the base set below is the registry's 14 foundational tools; the default (AGENTMEMORY_TOOLS=all) exposes all 54.

Base tools (14)
Tool Description
memory_recall Search past observations
memory_compress_file Compress markdown files while preserving structure
memory_save Save an insight, decision, or pattern
memory_file_history Past observations about specific files
memory_patterns Detect recurring patterns
memory_sessions List recent sessions
memory_smart_search Hybrid semantic + keyword search
memory_vision_search Search image observations
memory_timeline Chronological observations
memory_profile Project profile (concepts, files, patterns)
memory_export Export memory data, in pages or selected collections on a large store
memory_relations Query relationship graph
memory_commit_lookup Sessions behind a git commit
memory_commits Commits recorded for a session
Extended tools (54 total, the default surface)
Tool Description
memory_patterns Detect recurring patterns
memory_timeline Chronological observations
memory_relations Query relationship graph
memory_graph_query Knowledge graph traversal
memory_consolidate Run 4-tier consolidation
memory_claude_bridge_sync Read MEMORY.md or create a project export, preserving existing files
memory_team_share Share with team members
memory_team_feed Recent shared items
memory_audit Audit trail of operations
memory_governance_delete Delete with audit trail
memory_snapshot_create Git-versioned snapshot
memory_action_create Create work items with dependencies
memory_action_update Update action status
memory_frontier Unblocked actions ranked by priority
memory_next Single most important next action
memory_lease Exclusive action leases (multi-agent)
memory_routine_run Instantiate workflow routines
memory_signal_send Inter-agent messaging
memory_signal_read Read messages with receipts
memory_checkpoint External condition gates
memory_mesh_sync P2P sync between instances
memory_sentinel_create Event-driven watchers
memory_sentinel_trigger Fire sentinels externally
memory_sketch_create Ephemeral action graphs
memory_sketch_promote Promote to permanent
memory_crystallize Compact action chains
memory_diagnose Health checks
memory_heal Auto-fix stuck state
memory_facet_tag Dimension:value tags
memory_facet_query Query by facet tags
memory_verify Trace provenance

6 Resources · 3 Prompts · 17 Skills

Type Name Description
Resource agentmemory://status Health, session count, memory count
Resource agentmemory://project/{name}/profile Per-project intelligence
Resource agentmemory://project/{name}/recent Recent observations for a project
Resource agentmemory://memories/latest Latest 10 active memories
Resource agentmemory://graph/stats Knowledge graph statistics
Resource agentmemory://team/{id}/profile Shared team profile
Prompt recall_context Search + return context messages
Prompt session_handoff Handoff data between agents
Prompt detect_patterns Analyze recurring patterns
Skill /recall Search memory
Skill /remember Save to long-term memory
Skill /session-history Recent session summaries
Skill /forget Delete observations/sessions

The table shows the four core skills. The full set is 9 invocable skills plus 8 reference skills; see the Native skills section above.

Standalone MCP

Run without the full server, for any MCP client. Either of these works:

npx -y @agentmemory/agentmemory@latest mcp   # canonical (always available)
npx -y @agentmemory/mcp                # shim package alias

Or add to your agent's MCP config:

Most agents (Cursor, Claude Desktop, Cline, Roo Code, Gemini CLI):

{
  "mcpServers": {
    "agentmemory": {
      "command": "npx",
      "args": ["-y", "@agentmemory/mcp"],
      "env": {
        "AGENTMEMORY_URL": "http://localhost:3111"
      }
    }
  }
}

Merge the agentmemory entry into your host's existing mcpServers object rather than replacing the file. For sandboxed clients that can't reach the host's localhost, add "AGENTMEMORY_FORCE_PROXY": "1" to the env block and set AGENTMEMORY_URL to a route the sandbox can reach.

OpenCode (opencode.json):

{
  "mcp": {
    "agentmemory": {
      "type": "local",
      "command": ["npx", "-y", "@agentmemory/mcp"],
      "enabled": true
    }
  },
  "plugin": ["./plugins/agentmemory-capture.ts"]
}

Copy the plugin file from the repo:

mkdir -p ~/.config/opencode/plugins
cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
cp plugin/opencode/commands/*.md ~/.config/opencode/commands/

Real-Time Viewer

Auto-starts on port 3113. The viewer loads one snapshot when it connects (GET /agentmemory/viewer/snapshot) and then applies live events over SSE at /agentmemory/viewer/events on the REST worker: new memories, lessons, observations, audit entries, graph changes and health updates appear without polling or page reloads. The only other requests are the actions you click, "load more" pages and searches. When the stream drops, the viewer shows how old its numbers are, reconnects with backoff and resyncs from one snapshot.

  • 12 tabs in four groups with live counts, deep links (#memories/<id>, #sessions/<id>?obs=<id>, #graph/<id>, #health/consolidation), keyboard shortcuts and a mobile menu.
  • Memories: server-side search, filters by project, agent and type, a detail panel with the version chain and a word diff, provenance links, copy buttons for the id, the MCP call and a curl command, edit (a new version), forget with confirmation, bulk forget and JSON export.
  • Sessions: an inline observation timeline with readable tool input and output, filters and paging, and the memories and lessons each session produced.
  • Graph: search, node detail with relations and sources, a legend that does not rely on colour alone, and zoom controls.
  • Health: the live version of GET /agentmemory/status. Every problem comes with its fix, plus the state backend, index save state, graph provenance compaction progress and a consolidation explainer with the real thresholds.
  • Audit, Activity, Profile, Replay, Lessons, Actions and Crystals pages, each with an empty state that says what the section is, why it is empty and the command that fills it, and a ? glossary tooltip on every term and number.
open http://localhost:3113

The viewer server binds to 127.0.0.1 by default and attaches the server secret when it forwards requests to the REST API. On a non-loopback bind, the HTML shell remains public but every proxy request requires the bearer; the viewer prompts for it and stores it in session storage. Configure explicit host/origin allowlists and TLS before exposing a viewer. The REST-served /agentmemory/viewer endpoint follows the normal bearer-token rules and redirects browsers without a token to the viewer port. CSP headers use a per-response script nonce and disable inline handler attributes (script-src-attr 'none').


Configuration

LLM Providers

agentmemory auto-detects providers from your environment. A provider makes LLM-backed operations available, but provider configuration alone does not enable LLM-written observation compression. That path requires both a provider and AGENTMEMORY_AUTO_COMPRESS=true.

Provider Config Notes
No-op (default) No config needed LLM-backed compress/summarize is disabled. Synthetic compression and BM25 recall still work. See AGENTMEMORY_ALLOW_AGENT_SDK below if you used to rely on the Claude-subscription fallback.
Anthropic API ANTHROPIC_API_KEY Per-token billing
MiniMax MINIMAX_API_KEY Anthropic-compatible
Gemini GEMINI_API_KEY Also enables embeddings
OpenRouter OPENROUTER_API_KEY Any model
OpenAI API OPENAI_API_KEY Default gpt-5.6-luna, override with OPENAI_MODEL
Local (Ollama / LM Studio / vLLM / llama.cpp) OPENAI_API_KEY=local + OPENAI_BASE_URL=http://localhost:11434/v1 (Ollama) or http://localhost:1234/v1 (LM Studio) + OPENAI_MODEL=<your model> Anything OpenAI-API-compatible. Zero cost, runs on your hardware. See Local models below.
Claude subscription fallback AGENTMEMORY_ALLOW_AGENT_SDK=true Opt-in only. Spawns @anthropic-ai/claude-agent-sdk sessions; it used to cause unbounded Stop-hook recursion, so it is no longer the default.

Local models (Ollama / LM Studio / vLLM)

agentmemory talks to any OpenAI-API-compatible server, so anything that exposes /v1/chat/completions works without code changes. No paid keys, no cloud, no rate limits; runs entirely on your hardware.

Ollama (default port 11434):

ollama pull qwen3:8b   # or qwen3:4b, gpt-oss:20b, qwen3-coder:30b, etc.
ollama serve
# ~/.agentmemory/.env
OPENAI_API_KEY=ollama                          # any non-empty string; Ollama ignores it
OPENAI_BASE_URL=http://localhost:11434/v1
OPENAI_MODEL=qwen3:8b

LM Studio (default port 1234):

Open LM Studio → Local Server tab → Start Server. Pick any chat model from the picker (Qwen 3, gpt-oss, DeepSeek R1, etc.).

# ~/.agentmemory/.env
OPENAI_API_KEY=lmstudio                        # any non-empty string; LM Studio ignores it
OPENAI_BASE_URL=http://localhost:1234/v1
OPENAI_MODEL=qwen3-8b                          # match the model name from LM Studio

vLLM / llama.cpp / Text Generation Inference: same shape. Point OPENAI_BASE_URL at whatever URL your server exposes and set OPENAI_MODEL to a name your server will accept.

Model picks for memory work: compression and summarization are short tasks (<2K tokens in, <500 tokens out) where a 7B instruct model is plenty. Recommendations:

Model Size Why
qwen3:8b ~5.2 GB Balanced default on a 16 GB machine; strong at extraction and tool-shaped text
qwen3:4b ~2.6 GB Smallest sane option; fine for compression, weaker for graph extraction
qwen3-coder:30b ~19 GB Best local pick for code-shaped sessions (30B MoE, 3.3B active) on 24-32 GB hardware
gpt-oss:20b ~14 GB Strong general model that fits 16 GB RAM
deepseek-r1:8b ~5.2 GB Reasoning distill; slower but cleaner extractions

Qwen 3 models think by default and can burn the whole token budget on reasoning before any output. Set AGENTMEMORY_LLM_NOTHINK=1 to append /no_think to graph-extraction prompts, and raise MAX_TOKENS (16384 works) if extractions come back empty.

Reasoning-class models (o1-style with <think> blocks) can return empty content with a reasoning field your local server may not surface. If extractions come back blank, switch to a non-reasoning model first. The OPENAI_REASONING_EFFORT=none env can also disable thinking on Ollama Cloud thinking models that mirror the OpenAI reasoning schema.

Local embeddings ship as an optional dependency but are not enabled by default. Set EMBEDDING_PROVIDER=local to opt into Xenova/all-MiniLM-L6-v2 (384-dim). The first embedding request downloads the model; inference is on-device afterward. Without that setting or a remote embedding key, vectors stay disabled, mem::search uses BM25, and smart-search can still add existing graph matches.

Cost-aware model selection

Start keyless for capture and keyword recall. Enable EMBEDDING_PROVIDER=local for on-device semantic search after the initial model download. LLM-written compression requires a provider and AGENTMEMORY_AUTO_COMPRESS=true; it can make a request for each captured observation, so check your provider's current pricing before enabling it.

The viewer and agentmemory status show the active providers. Local OpenAI-compatible servers work with the same configuration shape as hosted providers.

Multi-agent memory (AGENT_ID + AGENTMEMORY_AGENT_SCOPE)

In multi-agent setups where several roles share one agentmemory server (architect / developer / reviewer / researcher / support-agent), AGENT_ID tags every write with the role that made it. AGENTMEMORY_AGENT_SCOPE controls whether recall filters by that tag.

TEAM_ID=company
USER_ID=engineering-team
AGENT_ID=architect
AGENTMEMORY_AGENT_SCOPE=isolated  # optional; default "shared"

Two modes:

Mode Tag writes Filter recall When to use
shared (default) yes no Cross-agent context with audit trail. Architect can see what developer noted, but every row records who said it.
isolated yes yes Strict separation. Architect never sees developer's observations / memories / sessions.

What gets tagged when AGENT_ID is set: Session.agentId, RawObservation.agentId, CompressedObservation.agentId, Memory.agentId. The role flows from api::session::start → mem::observe → mem::compress → KV.

What gets filtered in isolated mode: mem::smart-search, /agentmemory/memories, /agentmemory/observations, /agentmemory/sessions. Each endpoint accepts ?agentId=<role> to override per-request, and ?agentId=* to opt out of the env scope entirely. /memories also accepts ?includeOrphans=true to surface pre-AGENT_ID memories whose agentId is undefined.

Per-call override at the SDK / REST layer: every mutating endpoint (/session/start, /remember) accepts an agentId field in the request body that wins over the env. Useful for runtimes routing many roles through one server process. The MCP memory_save tool exposes the same agentId field, the standalone stdio server forwards both agentId and project, and saved memories carry agentId into the search index, so agent-scoped search covers memories as well as observations.

When AGENT_ID is unset, memory remains unscoped (legacy behavior, no tags, no filters).

Ports

The API and viewer bind to loopback by default.

Port Purpose Env override
3111 REST API, MCP HTTP and live viewer events III_REST_PORT
3113 Viewer UI III_VIEWER_PORT

--port <N> sets the REST port and defaults the viewer to N+2. Use --instance N for a separate runtime. Internal runtime listeners must remain private; see the deployment guide before exposing the service remotely.

Storage backend: file (default) vs Redis

The default file store needs no separate database service. Redis is optional with AGENTMEMORY_STATE_BACKEND=redis and AGENTMEMORY_REDIS_URL. Changing backends does not copy existing memories. Follow the storage and backup guide for persistence settings, Redis limitations and authenticated export/import.

Config File

Put agentmemory runtime configuration in ~/.agentmemory/.env instead of exporting variables in every shell. If the viewer shows a setup hint like export ANTHROPIC_API_KEY=..., copy it into this file as ANTHROPIC_API_KEY=... without the export prefix, then restart agentmemory. Set AGENTMEMORY_ENV_FILE to use another env-file path.

Process environment variables take precedence over values in the file. Restart the server after changing its configuration.

On Windows, the same file lives at %USERPROFILE%\.agentmemory\.env:

New-Item -ItemType Directory -Force $HOME\.agentmemory
notepad $HOME\.agentmemory\.env

To test with a Claude Code Pro/Max subscription instead of an API key, opt in explicitly:

AGENTMEMORY_ALLOW_AGENT_SDK=true
AGENTMEMORY_AUTO_COMPRESS=true

LLM-written observation compression requires both lines: access to an LLM provider (including this explicit subscription fallback) and AGENTMEMORY_AUTO_COMPRESS=true. A provider by itself leaves the default synthetic compression path in place.

Consolidation (graph nodes, lessons, crystals) is on by default whenever an LLM provider is configured. Explicitly opt out with CONSOLIDATION_ENABLED=false if you want LLM-free operation. Graph extraction is a separate flag:

GRAPH_EXTRACTION_ENABLED=true
# CONSOLIDATION_ENABLED=false   # opt out of auto-consolidation

Environment Variables

Common options for ~/.agentmemory/.env:

# Semantic recall on your machine, after the first model download
EMBEDDING_PROVIDER=local

# Optional automatic context injection through the shared hooks
# AGENTMEMORY_INJECT_CONTEXT=true

# Optional LLM-written compression; also requires a configured provider
# AGENTMEMORY_AUTO_COMPRESS=true

# Show 8 essential MCP tools instead of the default 54
# AGENTMEMORY_TOOLS=core

# Disable scheduled auto-forget and lesson/insight decay
# AUTO_FORGET_ENABLED=false
# LESSON_DECAY_ENABLED=false
# INSIGHT_DECAY_ENABLED=false

The complete reference is .env.example, including provider credentials, capture filters, retention, storage, team scope and optional features. AGENTMEMORY_ENV_FILE selects another file. Never commit a populated .env or bearer secret.


API

146 endpoints on port 3111. The REST API binds to 127.0.0.1 by default. Protected endpoints require Authorization: Bearer <secret>, and mesh sync endpoints require an explicitly set AGENTMEMORY_SECRET on both peers.

Authentication is on by default. When AGENTMEMORY_SECRET is not set (in the shell or in ~/.agentmemory/.env), the CLI generates a random secret on first start and stores it at ~/.agentmemory/secret, mirrored to the selected data directory as secret, with mode 0600 (the platform-specific default data directory is described above). Bundled clients read the canonical secret first when they talk to a local server: the CLI, the viewer, the hooks under plugin/scripts, the MCP server and the @agentmemory/mcp shim, the configs written by agentmemory connect, and the bundled OpenCode, Pi, OpenClaw, Hermes and filesystem-watcher integrations. The stored secret is only sent to loopback URLs (localhost, 127.0.0.0/8, ::1). An explicit AGENTMEMORY_SECRET always wins, and remote clients need the secret set in their environment. Repository-based Docker self-host deployments and the deploy/ entrypoints generate and export their own secret. To call the API by hand:

curl -H "Authorization: Bearer <secret-from-data-dir>" http://localhost:3111/agentmemory/health

Request rules for writes. POST, PUT, PATCH and DELETE requests to the REST API and the viewer must send Content-Type: application/json (a charset parameter is fine) whenever they carry a body, and an Origin header, when present, must be a loopback origin for the configured REST or viewer port or be listed in VIEWER_ALLOWED_ORIGINS (comma-separated, e.g. https://memory.example.com). Clients that send no Origin header (CLI, hooks, MCP, curl, server-to-server) are unaffected. The viewer also accepts its own origin.

File paths. Endpoints that read or write files (/compress-file, /replay/import-jsonl, /graph/import-graphify) only accept paths under ~/.agentmemory, the instance data directory, or a directory listed in AGENTMEMORY_IMPORT_ROOT (separate several with :, or ; on Windows). /replay/import-jsonl also accepts its default ~/.claude/projects. /obsidian/export stays inside AGENTMEMORY_EXPORT_ROOT and /migrate inside ~/.agentmemory. Symlinks are resolved before every check.

Secret scrubbing. API keys, bearer tokens, PEM private key blocks and credentials embedded in URLs (scheme://user:password@host) are redacted before text is stored, on every write path: observations, remember, evolve, slots, lessons, actions, sketches, signals, checkpoints, imports, jsonl replay, mesh sync, team shares, compression and summary output, crystals and graph nodes.

Key endpoints
Method Path Description
GET /agentmemory/health Health check (always public)
GET /agentmemory/status What is wrong and how to fix it (HTML for browsers, JSON otherwise)
GET /agentmemory/viewer/snapshot Everything the viewer shows, in one response
POST /agentmemory/session/start Start session + get context
POST /agentmemory/session/end End session; final: false (per-turn hooks) defers completion until the session is idle
POST /agentmemory/observe Capture observation (see capture delivery below)
GET /agentmemory/capture Capture inbox, dead letters and offline spool
POST /agentmemory/capture/retry Retry dead-letter captures
POST /agentmemory/capture/drain Send the local offline spool now
POST /agentmemory/smart-search Hybrid search
POST /agentmemory/context Generate context
POST /agentmemory/remember Save to long-term memory
POST /agentmemory/forget Delete observations
POST /agentmemory/enrich File context + memories + bugs
GET /agentmemory/profile Project profile
GET /agentmemory/export Export all data
POST /agentmemory/import Import from JSON
POST /agentmemory/graph/query Knowledge graph query
POST /agentmemory/graph/reset Start an empty graph generation; retain observations and memories
POST /agentmemory/graph/compact Trim oversized graph provenance
POST /agentmemory/team/share Share with team
GET /agentmemory/audit Audit trail

Full endpoint list: generated REST reference

Capture delivery. Hooks send each observation once to POST /agentmemory/observe with an eventId. It is the host's own id for the call when the payload has one (for example Claude Code's tool_use_id), otherwise a hash of the session, hook type, tool name, input, output and host timestamp. The server writes the event to a capture inbox in the state store, stores the observation, then removes the inbox entry. The status code says what happened:

Status status field Meaning
201 accepted Stored. observationId is the new observation.
202 accepted (state: "retrying") Accepted, but storing failed. The server retries it, also after a restart.
200 duplicate This eventId was already accepted. observationId is the existing observation; nothing new is stored.
400 / 422 rejected Invalid payload, or storing failed for good (the event is kept as a dead letter).
503 rejected (retryable: true) The inbox is full (AGENTMEMORY_CAPTURE_INBOX_MAX). Hooks spool the event and send it later.

Failed events are retried every AGENTMEMORY_CAPTURE_RETRY_INTERVAL_MS (10 s) with doubling backoff, up to AGENTMEMORY_CAPTURE_MAX_ATTEMPTS (5). Events that still fail stay in the inbox as dead letters, are listed on /agentmemory/status and the viewer Health page, and can be retried with POST /agentmemory/capture/retry ({"eventId": "..."} or {"all": true}). Accepted event ids are remembered for AGENTMEMORY_CAPTURE_DEDUP_HOURS (168 hours, at most AGENTMEMORY_CAPTURE_EVENTS_MAX ids), so a hook replayed after a timeout or a restart is stored once, while two separate tool calls with their own host ids are stored twice even when their content is identical. When an observation is deleted (forget, session delete, eviction, auto-forget or an import that replaces the store), its event is marked as deleted before the observation is removed, so a replay of that event inside the same window is answered as a duplicate and stores nothing. The state store writes to disk every 2 seconds, so an answered event can still be only in memory for a moment. To cover that, every 2xx answer also carries the server's bootId (new at every start), acceptedAt and durableAfterMs (the save interval plus 1.5 s on the file store, 1.5 s on redis, where persistence is the operator's setting). Hooks keep the event in the local spool until that window has passed and delete it on a later call without another request. If the bootId has changed by then, the server restarted, so the hook sends the event again with the same eventId; an event that did reach the disk is not stored twice. The server also sends such events itself at start and every retry interval, so a restart loses nothing even when no hook runs afterwards. Older hooks ignore the extra fields, and new hooks against an older server discard the event on 2xx as before.

When the server is down, does not answer in time or returns a 5xx, the hook appends the observation to a local spool file, <data dir>/capture-spool/<host>-<port>.jsonl (override the folder with AGENTMEMORY_CAPTURE_SPOOL_DIR). The file is private to your user (mode 600), secrets are redacted the same way the server redacts them, it holds at most AGENTMEMORY_CAPTURE_SPOOL_MAX_BYTES (5 MiB) and drops entries older than AGENTMEMORY_CAPTURE_SPOOL_MAX_AGE_HOURS (168). When it is full, new entries are dropped and counted, and /agentmemory/status reports it. The hook still exits 0 within its time limit and adds no request when the server is healthy. The spool is sent at the next start and by the first hook that reaches the server again, in a background process so the agent does not wait. Event ids make this safe: an observation that did arrive before a timeout is not stored twice. npx @agentmemory/agentmemory capture shows the spool and the server inbox, --drain sends the spool now, and GET /agentmemory/capture returns the same as JSON. Set AGENTMEMORY_CAPTURE_SPOOL=false to turn the spool off.

Resetting the graph. Call POST /agentmemory/graph/reset to start a new graph generation. The previous graph becomes inaccessible to graph queries, node lookups, statistics, and MCP reads; new imports and extraction populate the new generation. Existing observations and memories remain available. Old graph storage is retained.

Upgrading from v0.9.30: if you already reset the graph before upgrading, run POST /agentmemory/graph/reset again after the upgrade. Earlier reset timestamps are not used to infer a completed generation reset.

Compacting graph provenance. Legacy provenance compaction is deferred at startup because it reads complete legacy scopes. /agentmemory/status reports deferred, or off with AGENTMEMORY_GRAPH_COMPACT_ON_BOOT=false. Run the manual compaction below during maintenance. Retrieval index migration is separate: use agentmemory graph-index migrate --allow-legacy-scan as described in the maintenance guide.

To run it by hand, call POST /agentmemory/graph/compact. It walks the name and edge-key indexes instead of listing every node and edge, and is safe to re-run. When it trims ids it writes a graph_compact audit entry.

curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: Bearer <secret>" -H "Content-Type: application/json" -d '{}'

On a large store, or when the call returns 504, run it in slices. Send scope (nodes, edges or history), offset and limit, then call again with the returned nextOffset until it is null. Do this for nodes, edges and history, and finish with one {"scope":"snapshot"} call, because a sliced run does not touch the cached snapshot.

curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: Bearer <secret>" -H "Content-Type: application/json" -d '{"scope":"nodes","offset":0,"limit":200}'
curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization: Bearer <secret>" -H "Content-Type: application/json" -d '{"scope":"snapshot"}'

Development

npm run dev               # Hot reload
npm run build             # Production build
npm test                  # 4,000+ tests
npm run test:integration  # API tests (requires running services)

Prerequisites: see Install. Contribution rules and release checks are in CONTRIBUTING.md.

License

Apache-2.0

About

#1 Persistent memory for AI coding agents based on real-world benchmarks

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

29.9k stars

Watchers

81 watching

Forks

Releases

Packages

Used by

Contributors

Languages