| name | agentmemory-persistent-memory |
| description | Add persistent memory to AI coding agents using agentmemory - remembers context, preferences, and decisions across sessions |
| triggers | ["set up persistent memory for this project","remember my coding preferences and architecture decisions","configure agentmemory to track our conversations","add memory to this AI agent","install agentmemory and connect it","help the agent remember what we discussed before","set up cross-session memory","configure memory persistence for Claude/Cursor"] |
agentmemory-persistent-memory
Skill by ara.so — AI Agent Skills collection.
agentmemory provides persistent memory for AI coding agents (Claude Code, Cursor, Gemini CLI, Codex, etc.) so they remember architecture decisions, preferences, bugs, and context across sessions. Built on the iii engine, it achieves 95.2% retrieval accuracy (R@5) and reduces token usage by 92% compared to pasting full context.
What It Does
- Cross-session memory: Agent remembers previous conversations, decisions, and code patterns
- Zero setup: No external databases, runs locally
- Works everywhere: MCP server + native plugins for Claude Code, Codex, OpenClaw, Hermes, Cursor, and more
- Hybrid search: Combines embeddings + BM25 for accurate retrieval
- Auto-capture: 12 hooks automatically store context from agent actions
- Real-time viewer: Web UI to inspect and manage memories at http://localhost:3112
Installation
Global Installation (Recommended)
npm install -g @agentmemory/agentmemory
agentmemory
npx (No Install)
npx @agentmemory/agentmemory
npx -y @agentmemory/agentmemory@latest
Project-Level Installation
{
"dependencies": {
"@agentmemory/agentmemory": "^0.9.16"
}
}
import { AgentMemory } from '@agentmemory/agentmemory';
const memory = new AgentMemory({
port: 3111,
dataDir: './data/memory'
});
await memory.start();
Quick Start
1. Start the Server
agentmemory
Output:
✓ agentmemory server running on http://localhost:3111
✓ Real-time viewer at http://localhost:3112
✓ MCP server ready for agent connections
2. Connect Your Agent
agentmemory connect claude-code
agentmemory connect codex
agentmemory connect cursor
agentmemory connect gemini-cli
agentmemory connect mcp
3. Demo Mode (Optional)
agentmemory demo
Agent-Specific Setup
Claude Code
Native plugin with 12 auto-hooks:
agentmemory connect claude-code
Creates ~/.claude-code/plugins/agentmemory.json:
{
"name": "agentmemory",
"memoryServer": "http://localhost:3111",
"hooks": {
"onStart": true,
"onCommand": true,
"onFileEdit": true,
"onSearch": true,
"onError": true,
"onDecision": true
}
}
Cursor (via MCP)
agentmemory connect cursor
Adds to ~/Library/Application Support/Cursor/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json:
{
"mcpServers": {
"agentmemory": {
"command": "npx",
"args": ["-y", "@agentmemory/agentmemory", "mcp"],
"env": {
"AGENTMEMORY_URL": "http://localhost:3111"
}
}
}
}
Claude Desktop
Edit ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"agentmemory": {
"command": "npx",
"args": ["-y", "@agentmemory/agentmemory", "mcp"]
}
}
}
Codex CLI
agentmemory connect codex
Creates ~/.codex/plugins/agentmemory.js:
module.exports = {
name: 'agentmemory',
memoryServer: 'http://localhost:3111',
hooks: ['onStart', 'onCommand', 'onFileEdit', 'onSearch', 'onError', 'onDecision']
};
Core API Usage
TypeScript/JavaScript
import { AgentMemory } from '@agentmemory/agentmemory';
const memory = new AgentMemory({
port: 3111,
dataDir: './data/memory',
embeddingModel: 'all-MiniLM-L6-v2',
enableViewer: true,
viewerPort: 3112
});
await memory.start();
await memory.store({
sessionId: 'session-001',
content: 'User prefers JWT auth with jose library for Edge compatibility',
type: 'preference',
tags: ['auth', 'jwt', 'edge'],
confidence: 0.95
});
const results = await memory.search({
query: 'authentication setup',
sessionId: 'session-001',
limit: 5
});
console.log(results);
memory.({
: ,
: ,
: ,
: ,
: [
,
,
]
});
context = memory.();
.(context.);
REST API
curl -X POST http://localhost:3111/api/memory/store \
-H "Content-Type: application/json" \
-d '{
"sessionId": "session-001",
"content": "User prefers TypeScript strict mode",
"type": "preference",
"tags": ["typescript", "config"],
"confidence": 0.9
}'
curl -X POST http://localhost:3111/api/memory/search \
-H "Content-Type: application/json" \
-d '{
"query": "typescript configuration",
"sessionId": "session-001",
"limit": 5
}'
curl http://localhost:3111/api/memory/session/session-001
curl -X DELETE http://localhost:3111/api/memory/delete/mem_abc123xyz
curl http://localhost:3111/health
MCP Server (Model Context Protocol)
agentmemory exposes 51 MCP tools for agent integration:
Available Tools
- memory_store: Store new memory
- memory_search: Search memories by query
- memory_recall: Get context for session
- memory_update: Update existing memory
- memory_delete: Delete specific memory
- memory_list: List all memories (paginated)
- session_create: Start new session
- session_get: Get session details
- session_list: List all sessions
- session_archive: Archive completed session
- code_store: Store code snippet with context
- code_search: Search code memories
- code_link: Link memories to code files
- preference_set: Store user preference
- preference_get: Retrieve preference
- preference_list: List all preferences
- graph_add_node: Add knowledge node
- graph_add_edge: Connect nodes
- graph_query: Query relationships
- : knowledge graph
- : memory statistics
- : -level stats
- : metrics
MCP Client Example
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
const transport = new StdioClientTransport({
command: 'npx',
args: ['-y', '@agentmemory/agentmemory', 'mcp']
});
const client = new Client({
name: 'my-agent',
version: '1.0.0'
}, {
capabilities: {}
});
await client.connect(transport);
const result = await client.request({
method: 'tools/call',
params: {
name: 'memory_store',
arguments: {
sessionId: 'session-001',
content: 'User wants error handling with Zod validation',
type: 'decision',
tags: ['error-handling', 'validation', 'zod']
}
}
});
console.log(result);
Configuration
Environment Variables
AGENTMEMORY_PORT=3111
AGENTMEMORY_VIEWER_PORT=3112
AGENTMEMORY_DATA_DIR=./data/memory
AGENTMEMORY_EMBEDDING_MODEL=all-MiniLM-L6-v2
OPENAI_API_KEY=your_openai_key_here
AGENTMEMORY_EMBEDDING_PROVIDER=openai
AGENTMEMORY_EMBEDDING_MODEL=text-embedding-3-small
AGENTMEMORY_HYBRID_ALPHA=0.7
AGENTMEMORY_MAX_RESULTS=10
AGENTMEMORY_AUTO_ARCHIVE_DAYS=30
AGENTMEMORY_MIN_CONFIDENCE=0.5
AGENTMEMORY_ENABLE_HOOKS=true
AGENTMEMORY_HOOK_ON_FILE_EDIT=true
AGENTMEMORY_HOOK_ON_COMMAND=true
AGENTMEMORY_HOOK_ON_ERROR=true
Configuration File
Create agentmemory.config.json:
{
"server": {
"port": 3111,
"viewerPort": 3112,
"dataDir": "./data/memory"
},
"embedding": {
"provider": "local",
"model": "all-MiniLM-L6-v2"
},
"search": {
"hybridAlpha": 0.7,
"maxResults": 10,
"minConfidence": 0.5
},
"lifecycle": {
"autoArchiveDays": 30,
"pruneInactive": true
},
Load config:
agentmemory --config ./agentmemory.config.json
Common Patterns
Pattern 1: Architecture Decision Capture
await memory.store({
sessionId: currentSession,
content: 'Decided to use PostgreSQL with Prisma ORM for type safety',
type: 'decision',
tags: ['architecture', 'database', 'prisma', 'postgresql'],
confidence: 0.95,
metadata: {
rationale: 'Team familiar with Prisma, need strong typing',
alternatives: ['MySQL + Drizzle', 'MongoDB'],
impact: 'high',
reversible: false
}
});
const context = await memory.recallForSession(newSession);
Pattern 2: Code Pattern Memory
await memory.storeCode({
sessionId: currentSession,
filePath: 'src/lib/api-client.ts',
language: 'typescript',
summary: 'API client with retry logic and exponential backoff',
pattern: `
export async function fetchWithRetry(url: string, options?: RequestInit) {
let attempt = 0;
while (attempt < 3) {
try {
return await fetch(url, options);
} catch (err) {
if (attempt === 2) throw err;
await new Promise(r => setTimeout(r, 2 ** attempt * 1000));
attempt++;
}
}
}
`,
tags: ['api', 'retry', 'fetch', 'resilience'],
keyDecisions: [
'3 retries with exponential backoff',
'Throws on final failure',
'No retry on 4xx errors (only network failures)'
]
});
const codeMemories = await memory.search({
query: 'api error handling',
type: 'code',
limit: 3
});
Pattern 3: Bug Fix Memory
await memory.store({
sessionId: currentSession,
content: 'Fixed race condition in WebSocket reconnection logic',
type: 'bug_fix',
tags: ['websocket', 'race-condition', 'concurrency'],
confidence: 1.0,
metadata: {
symptom: 'Duplicate connections causing message echoes',
rootCause: 'reconnect() called before disconnect() completed',
fix: 'Added connectionLock mutex to serialize connect/disconnect',
filePath: 'src/websocket/connection.ts',
linesChanged: '45-67',
testAdded: 'tests/websocket/reconnect.test.ts'
}
});
const pastBugs = await memory.search({
query: 'websocket connection issues',
type: 'bug_fix'
});
Pattern 4: Preference Learning
await memory.store({
sessionId: currentSession,
content: 'User prefers named exports over default exports',
type: 'preference',
tags: ['code-style', 'exports', 'modules'],
confidence: 0.85
});
await memory.store({
sessionId: currentSession,
content: 'User wants all async errors wrapped in Result<T, E> type',
type: 'preference',
tags: ['error-handling', 'types', 'functional'],
confidence: 0.9
});
const prefs = await memory.search({
query: 'code style preferences',
type: 'preference'
});
Pattern 5: Cross-File Context
await memory.storeCode({
sessionId: currentSession,
filePath: 'src/middleware/auth.ts',
language: 'typescript',
summary: 'JWT authentication middleware',
tags: ['auth', 'jwt', 'middleware']
});
await memory.linkCode({
from: 'src/middleware/auth.ts',
to: 'src/routes/api.ts',
relationship: 'used_by',
context: 'All /api/* routes use JWT auth middleware'
});
await memory.linkCode({
from: 'src/middleware/auth.ts',
to: 'tests/middleware/auth.test.ts',
relationship: 'tested_by',
context: 'Test coverage: token validation, expiry, refresh'
});
const linkedFiles = await memory.getCodeLinks('src/middleware/auth.ts');
Real-Time Viewer
Open http://localhost:3112 to see:
- Memory timeline: Visual history of all stored memories
- Session explorer: Browse by session, see context evolution
- Search interface: Test queries, see retrieval scores
- Knowledge graph: Visual map of connected memories
- Stats dashboard: Recall accuracy, token savings, storage usage
Viewer API
const viewerData = await fetch('http://localhost:3112/api/viewer/data').then(r => r.json());
console.log(viewerData);
CLI Commands
agentmemory
agentmemory --port 4000 --viewer-port 4001
agentmemory --daemon
agentmemory stop
agentmemory connect <agent-name>
agentmemory demo
agentmemory export --format json --output memories.json
agentmemory import --input memories.json
agentmemory clear
agentmemory stats
agentmemory health
agentmemory update
Troubleshooting
Server Won't Start
lsof -i :3111
kill -9 $(lsof -t -i:3111)
agentmemory --port 4000
Agent Not Connecting
curl http://localhost:3111/health
cat ~/Library/Application\ Support/Cursor/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json
npx @agentmemory/agentmemory mcp
Poor Recall Accuracy
AGENTMEMORY_HYBRID_ALPHA=0.85
OPENAI_API_KEY=your_key_here
AGENTMEMORY_EMBEDDING_PROVIDER=openai
AGENTMEMORY_EMBEDDING_MODEL=text-embedding-3-large
Memory Storage Growing Large
agentmemory archive --older-than 30d
agentmemory prune --min-confidence 0.5
agentmemory compact
Viewer Not Loading
curl http://localhost:3112
agentmemory --enable-viewer --viewer-port 3112
npx Cache Issues
rm -rf ~/.npm/_npx
npx -y @agentmemory/agentmemory@latest
Advanced: iii Engine Integration
agentmemory is built on the iii engine, a knowledge processing system. You can use iii directly for custom memory backends:
import { IIIEngine } from '@iii-hq/iii';
const engine = new IIIEngine({
storage: 'local',
embeddings: 'all-MiniLM-L6-v2'
});
await engine.store({
content: 'User prefers Tailwind CSS for styling',
type: 'preference',
tags: ['ui', 'css', 'tailwind'],
confidence: 0.9
});
const results = await engine.query({
semantic: 'css framework choice',
graphDepth: 2,
includeRelated: true
});
Environment Setup Example
AGENTMEMORY_PORT=3111
AGENTMEMORY_VIEWER_PORT=3112
AGENTMEMORY_DATA_DIR=/var/lib/agentmemory
AGENTMEMORY_EMBEDDING_PROVIDER=local
AGENTMEMORY_EMBEDDING_MODEL=all-MiniLM-L6-v2
AGENTMEMORY_HYBRID_ALPHA=0.75
AGENTMEMORY_AUTO_ARCHIVE_DAYS=90
AGENTMEMORY_MIN_CONFIDENCE=0.6
AGENTMEMORY_ENABLE_HOOKS=true
AGENTMEMORY_LOG_LEVEL=info
Performance Notes
- Embedding: Local model (all-MiniLM-L6-v2) processes ~500 tokens/sec on M1 Mac
- Search: Hybrid search returns results in <50ms for 10K memories
- Storage: ~1KB per memory average, ~10MB for 10K memories
- Startup: Cold start ~2 seconds, warm start <500ms
- Token savings: 92% reduction vs. full context pasting (see benchmarks)
Resources