Memory Tool
The memory tool lets Claude create, read, update, and delete files under a /memories prefix. It runs client-side: Claude requests operations, your code performs them on storage you control.
When to Use
- Agents that work across many sessions on the same project
- Remembering user or customer preferences without re-sending them each time
- Long tasks that may be interrupted and must resume from recorded progress
- Keeping active context small by reading facts back on demand
When NOT to Use
- Facts that fit in a short system prompt and rarely change
- Large document search: use retrieval
- Data you cannot store under your own retention and access controls
Workflow
Step 1: Add the tool
The whole configuration is one entry; no input schema, and the docs state no beta header is needed for the tool itself.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const MODEL = process.env.ANTHROPIC_MODEL!; // a current model ID
const response = await client.messages.create({
model: MODEL,
max_tokens: 2048,
tools: [{ type: "memory_20250818", name: "memory" }],
messages: [{ role: "user", content: "Help me respond to this support ticket." }],
});
When the tool is present, the API adds a memory protocol to the system prompt that tells Claude to view its memory directory first and record progress as it works.
Step 2: Implement the six commands
| Command | Input | Notes |
|---|---|---|
view |
path, optional view_range |
Directory listing (2 levels) or file with line numbers |
create |
path, file_text |
Reference behavior errors if the file exists; overwriting is an allowed choice |
str_replace |
path, old_str, new_str |
Must match exactly once |
insert |
path, insert_line, insert_text |
0 inserts at the start |
delete |
path |
Recursive for directories; never delete /memories itself |
rename |
old_path, new_path |
Do not overwrite an existing destination |
The docs specify recommended return strings for each command (for example, "File created successfully at: {path}"). Claude reads whatever you return, but matching the documented strings keeps behavior predictable. Return failures as a tool_result with is_error: true.
Step 3: Prefer the SDK helpers
The Python and TypeScript SDKs ship helpers and a ready-made local filesystem backend; the tool runner drives the loop.
import { betaMemoryTool } from "@anthropic-ai/sdk/helpers/beta/memory";
import { BetaLocalFilesystemMemoryTool } from "@anthropic-ai/sdk/tools/memory/node";
const backend = await BetaLocalFilesystemMemoryTool.init("./memory");
const memory = betaMemoryTool(backend);
const finalMessage = await client.beta.messages.toolRunner({
model: MODEL,
max_tokens: 1024,
tools: [memory],
messages: [{ role: "user", content: "Remember that Acme prefers email follow-ups." }],
max_iterations: 10,
});
from anthropic import Anthropic
from anthropic.tools import BetaLocalFilesystemMemoryTool
client = Anthropic()
memory = BetaLocalFilesystemMemoryTool(base_path="./memory")
runner = client.beta.messages.tool_runner(
model=MODEL, max_tokens=1024, tools=[memory],
messages=[{"role": "user", "content": "Remember that Acme prefers email follow-ups."}],
)
final = runner.until_done()
The helpers live in the SDK beta namespace even though the tool does not need a beta header. Subclass the abstract helper (BetaAbstractMemoryTool in Python) to back memory with a database or object store.
Step 4: Map /memories to per-tenant storage
/memories is a prefix your handler maps to real storage. Scope it per user or per project so one tenant can never read another's files, and serve the same store to later conversations so they resume from the same memory.
Step 5: Lock down paths
The docs call out path traversal explicitly: a path such as /memories/../../secrets.env must be rejected.
from pathlib import Path
ROOT = Path("/var/app/memory/tenant-123").resolve()
def safe_path(p: str) -> Path:
if not p.startswith("/memories"):
raise ValueError("path outside /memories")
candidate = (ROOT / p.removeprefix("/memories").lstrip("/")).resolve()
candidate.relative_to(ROOT) # raises if it escaped the root
return candidate
Also cap file sizes, cap how much view returns (Claude can page with view_range), watch for URL-encoded traversal sequences, and expire files that have not been accessed in a long time.
Step 6: Pair with context management
Memory preserves what must survive; compaction or context editing keeps the active window small. For long-running agents the docs suggest using both. A useful pattern from the docs for multi-session software work: an initializer session writes a progress log and a feature checklist; every later session reads them first and updates the log before ending.
Data Handling
Because storage is yours, you control retention. The docs list the memory tool as ZDR-eligible with exclusions for certain models; check the data-retention page if this matters to you.
Anti-Patterns
- No path validation in the handler
- One shared memory directory for all users
- Writing secrets or regulated data to memory without filtering
- Unbounded file growth and no expiry
- Using memory as a substitute for a search index
Best Practices
- Start with the SDK filesystem helper, then swap the backend
- Scope storage per tenant and validate every path
- Steer what gets written ("only record decisions about the billing migration")
- Keep memory files few and organized; delete stale ones
- Combine with compaction or context editing for long sessions
References
- Memory tool: https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool
- Context editing: https://platform.claude.com/docs/en/build-with-claude/context-editing
- Compaction: https://platform.claude.com/docs/en/build-with-claude/compaction
- Effective harnesses for long-running agents: https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents