Inside Claude’s Memory Tool: What Each of the Six Commands Actually Does

Rows of server racks in a data center computer room

Claude’s memory tool (memory_20250818) gives a Claude-powered application a small file system the model can write to and read back from across separate conversations. Claude never touches a disk directly: it sends a command, your application’s handler executes it against whatever storage you choose, and the result goes back as a tool result. That split is simple to describe and easy to get wrong in the details, so this walkthrough goes command by command through what actually happens when Claude calls view, create, str_replace, insert, delete, and rename.

What “memory” means for this tool, and what it doesn’t

The memory tool is an Anthropic-defined tool with no input schema of its own. You add a single entry to your tools array — {"type": "memory_20250818", "name": "memory"} — and Claude starts issuing tool_use blocks whose input.command field names one of the six operations below. Memory “lives entirely in your application,” as Anthropic’s documentation puts it: the /memories path is a prefix your handler maps onto real storage, whether that’s a directory on disk, a row in Postgres, or a per-user bucket in object storage. A later conversation only continues from the same memory if it sends the same tool entry and your handler serves the same backing store for that user or session. There’s nothing automatic about continuity — you own that wiring.

That matters for a decision a lot of teams skip past: memory is not a substitute for a bigger context window, it’s a substitute for re-explaining things every session. If your actual problem is that a single conversation runs long and tool results pile up, the tool you want first is context editing, not memory. The two are designed to work together, which the FAQ-style section near the end covers.

The six commands, and the trap in each one

Every command arrives as a tool_use block named memory. The table below is built directly from Anthropic’s tool-use documentation for memory_20250818, with the failure mode each command actually produces when a handler is written carelessly.

CommandRequired inputWhat happensTrap worth knowing
viewpath, optional view_rangeDirectories list two levels deep, skipping hidden items and node_modules. Files return line-numbered content.Text views longer than 16,000 characters are truncated. Claude has to page through long files with view_range, which it will only do if your tool result makes the truncation obvious.
createpath, file_textWrites a new file and returns “File created successfully at: {path}”.The docs don’t mandate a behavior when the file already exists — the reference implementation treats it as an error, but a handler that silently overwrites instead will quietly destroy Claude’s own notes.
str_replacepath, old_str, optional new_strReplaces one exact occurrence of old_str. Omitting new_str deletes it.Fails if old_str isn’t unique in the file — the same constraint as find-and-replace tools elsewhere, and just as easy for Claude to trip on a short, repeated string.
insertpath, insert_line, insert_textInserts text after the given line number; 0 inserts at the top of the file.There’s no dry run. A wrong line number silently lands the text in the wrong place rather than erroring.
deletepathDeletes a file or directory, recursively for directories.The /memories root itself is rejected as a target — but nothing stops Claude from deleting a whole subdirectory in one call if your handler doesn’t ask for confirmation on multi-file deletes.
renameold_path, new_pathMoves or renames a file or directory.Won’t overwrite an existing destination, and /memories itself is rejected as old_path — but a destination one directory up from where you expected still succeeds.

Files over 999,999 lines return an error from view outright, and the documentation’s only sizing advice is to cap file sizes yourself and periodically delete stale ones — there’s no published numeric ceiling on total memory per user. Treat that as a product decision you have to make, not a default Anthropic ships for you.

A before/after on what this buys you

Without memory: a support agent starts each new ticket with no idea the same customer filed three similar bugs last month, unless your application re-sends that history as part of the prompt every single time — which costs tokens on every turn whether Claude needs the history or not.

With memory: Claude calls view on /memories/customers/{id}.md at the start of the conversation, finds the earlier notes it wrote itself, and only pays the token cost for that file on the turns where it actually reads it. The history persists because your handler stored the file after the previous conversation, not because Anthropic stored it for you.

The security check that isn’t optional

Because Claude supplies the path argument as plain text, every command handler has to validate it before touching storage. Anthropic’s own documentation calls this out explicitly: a path like /memories/../../secrets.env must never be allowed to resolve outside the memory root. The recommended defenses are mundane but easy to skip under deadline pressure: require the /memories prefix, resolve the path to its canonical form and confirm it still starts with that prefix, reject literal ../ or ..\ sequences, and watch for URL-encoded traversal attempts such as %2e%2e%2f. In Python, pathlib.Path.resolve() followed by relative_to() does the canonicalization and containment check in two lines. If you’re also exposing any MCP server to the same agent, the trust-boundary questions are the same ones worth asking before connecting an MCP server to Claude Code in the first place: what can this tool actually read or write, and have you verified that rather than assumed it.

A minimal handler shape

import re
from pathlib import Path

MEMORY_ROOT = Path("/var/app_memories").resolve()

def resolve_safe(path: str) -> Path:
    if not path.startswith("/memories"):
        raise ValueError("path must start with /memories")
    rel = path.removeprefix("/memories").lstrip("/")
    candidate = (MEMORY_ROOT / rel).resolve()
    if MEMORY_ROOT != candidate and MEMORY_ROOT not in candidate.parents:
        raise ValueError("path escapes memory root")
    return candidate

def handle_memory_command(cmd: dict) -> dict:
    try:
        target = resolve_safe(cmd["path"])
        if cmd["command"] == "view":
            text = target.read_text()
            return {"type": "tool_result", "tool_use_id": cmd["id"], "content": text}
        # create / str_replace / insert / delete / rename follow the same
        # resolve-then-act shape; each still needs its own existence and
        # uniqueness checks before it touches the filesystem.
    except Exception as exc:
        return {"type": "tool_result", "tool_use_id": cmd["id"],
                "content": f"Error: {exc}", "is_error": True}

Setting is_error: true on a failed command is what lets Claude recover instead of repeating the same broken call. If you’ve ever had Claude loop on a tool failure, the usual cause isn’t the memory tool specifically — it’s a handler that returns a generic failure instead of the kind of specific, machine-readable message described in our field guide to Claude API error codes.

Pairing it with context editing

Memory and context editing solve different problems and are built to be combined. Context editing’s clear_tool_uses_20250919 strategy clears old tool results once a conversation crosses a token threshold, which keeps a long agent loop from blowing through your context window. On its own, that clearing is lossy: once a tool result is cleared, it’s gone. Combine the two and Claude gets an automatic warning as the clearing threshold approaches, so it can write the important parts of a result to a memory file before context editing removes it — then look the file back up later with view if it needs that detail again. One caveat worth budgeting for: clearing invalidates cached prompt prefixes, so pairing frequent memory writes with aggressive context editing means paying for cache writes more often, which is the same cost trade-off covered in our walkthrough of setting up prompt caching breakpoints.

When it’s worth the extra moving part

  • A coding agent that resumes work on the same repository across multiple sessions and shouldn’t re-discover the same architecture notes every time.
  • A support or sales assistant where the same customer returns across days or weeks, and re-sending the full history every turn would be wasteful.
  • A long-running research or audit task that periodically needs to checkpoint findings somewhere more durable than the current conversation.
  • A single-turn Q&A tool, a one-off script, or anything where the conversation never outlives one request — memory adds a handler to secure and maintain for no real benefit here.

The memory tool is documented as available on all Claude 4 and later models, requires no beta header (unlike context editing, which does), and is eligible for zero data retention and HIPAA deployments since the data never leaves your own infrastructure. That last point is also the catch: Anthropic ships the protocol, not the storage, the backups, or the access control. Those are yours to build.

SDK helpers, if you’d rather not write the loop by hand

Anthropic ships helper classes for some languages so you don’t have to write the full command-dispatch loop yourself: Python gets BetaAbstractMemoryTool and a ready-made BetaLocalFilesystemMemoryTool, TypeScript gets betaMemoryTool, C# gets its own BetaAbstractMemoryTool, and Java gets BetaMemoryToolHandler. Go and Ruby have no helper in the SDK yet, so in those languages you’re implementing the six-command dispatch loop shown above from scratch. One more detail worth knowing before you rely on it for anything visual: view can display image files directly — .jpg, .jpeg, and .png — which is useful if an agent is saving diagrams or screenshots as part of its own notes, not just text.

Photo: server racks at the NOIRLab Headquarters computer room, Tucson, Arizona — NOIRLab/NSF/AURA/T. Slovinský, licensed CC BY 4.0.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top