Skip to content
,

Claude Memory Tool and Context Editing API: Python Guide

14–21 minutes
Woman in a server room holding a tablet with a CLAUDE MEMORY card, hook memory tool no beta header

Claude’s memory tool lets an agent save notes to files and read them back in a later session. Context editing clears old tool results and thinking from a long conversation so it keeps fitting in the context window.

Together they are the simplest way to build a Python agent that runs for hours without forgetting what it did. This guide covers both, with code you can run today.

TLDR

  • Memory tool: add {"type": "memory_20250818", "name": "memory"}. It is generally available and needs no beta header (since 17 Feb 2026).
  • You run the storage: Claude asks for file commands under /memories, and your code executes them. The Python SDK ships BetaLocalFilesystemMemoryTool so you can skip writing a handler.
  • Context editing: still beta. Send the header context-management-2025-06-27 with clear_tool_uses_20250919 and/or clear_thinking_20251015.
  • Price: no extra fee. You pay normal input and output tokens, for example $2 / $10 per million on Claude Sonnet 5.5.
  • Security: validate every path. A path like /memories/../../secrets.env must be rejected.

What the Claude Memory Tool Is

The memory tool gives Claude a small folder of files that survives between conversations. Claude can create, read, edit, rename and delete files in that folder. Nothing is stored by Anthropic: the tool is client-side, so your app holds the data.

When the tool is on, the API adds a short instruction that tells Claude to view its memory directory before doing anything else. It also tells Claude to assume its context could be reset at any time, so it saves progress as it goes.

When to use it

  • Multi-session projects: a coding or research agent picks up where yesterday’s session stopped.
  • Learning from feedback: Claude stores lessons, decisions and user preferences, then applies them next time.
  • Knowledge bases: support agents build up notes on customers, policies or past tickets.
  • Very long tasks: the agent writes findings to memory so old tool output can be cleared safely.

Memory vs context editing vs compaction

These three features are easy to mix up. Here is how they differ.

Feature What it does Where it runs Status (Dec 2026)
Memory tool Saves facts to files that persist across sessions Your app (client-side) Generally available
Context editing Clears old tool results or thinking blocks from the prompt Anthropic API (server-side) Beta
Compaction Summarizes older conversation into a short block Anthropic API (server-side) Beta

Note: The memory tool on the API is different from the memory feature in the Claude apps. The app feature is managed by Anthropic. The API tool stores everything in storage you control.

Tool Versions, Beta Headers and SDK Versions

These strings come from the official Claude docs and release notes, checked on 3 December 2026. The memory tool lost its beta header on 17 February 2026, but context editing is still in beta.

Item Exact string Beta header needed?
Memory tool memory_20250818 (name must be memory) No
Tool result clearing clear_tool_uses_20250919 Yes: context-management-2025-06-27
Thinking block clearing clear_thinking_20251015 Yes: context-management-2025-06-27
Compaction at a threshold compact_20260112 Yes: compact-2026-01-12
API version header 2026-10-21 n/a
Python SDK checked anthropic 2.16.0 (1 Dec 2026), Python 3.10+ n/a
Claude Platform Docs Getting started section showing the memory_20250818 tools entry and the rule that handlers must reject paths outside /memories
Official Claude Platform Docs memory tool page (checked 3 Dec 2026).

The memory tool works on every current model, including Claude Fable 5.2, Opus 5.5, Sonnet 5.5 and Haiku 5.5. It is also available on Amazon Bedrock, Google Cloud and Microsoft Foundry.

Setup: Install the SDK and Your Key

  1. Check Python. Run python3 --version. The current SDK needs Python 3.10 or newer.
  2. Install the SDK. Run pip install -U anthropic. Version 2.16.0 was the latest when I checked.
  3. Get an API key. Create one in the Claude Console. My guide on how to get a Claude API key walks through it.
  4. Set the key as an environment variable. On macOS or Linux run export ANTHROPIC_API_KEY="sk-ant-...". Never paste the key into code.
  5. Make a project folder. The examples below create a memory or agent_memory folder next to your script.

New to the SDK? Start with my Claude API Python tutorial and the Claude tool use tutorial, since the memory tool follows the normal tool-use loop.

Example 1: The Fastest Way (SDK Helper)

The Python SDK includes BetaLocalFilesystemMemoryTool. It stores files on disk, checks paths for you and runs the tool loop through tool_runner. The class name says “Beta” because it lives in the SDK’s beta helpers, even though the tool itself is GA.

import anthropic
from anthropic.tools import BetaLocalFilesystemMemoryTool

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

# Files land in ./memory/memories/ on your disk
memory = BetaLocalFilesystemMemoryTool(base_path="./memory")

runner = client.beta.messages.tool_runner(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    tools=[memory],
    messages=[{
        "role": "user",
        "content": "Remember that customer Acme Corp prefers email follow-ups.",
    }],
)
final_message = runner.until_done()
print(final_message.content)

Run it twice. On the second run, ask “How should I follow up with Acme Corp?” and Claude will read the saved file before it answers.

Tip: The helper creates folders with mode 0o700 and files with 0o600, so other users on the machine cannot read them. That matters inside Docker, where the umask is often wide open.

Example 2: Write Your Own Memory Handler

Write your own handler when memory must live somewhere else, such as a per-user folder, a database or encrypted storage. The handler below maps the virtual /memories path to a real folder and returns the reference strings from the docs.

Save it as memory_handler.py. It rejects ../ traversal, refuses to delete the root and caps file size.

import shutil
from pathlib import Path

ROOT = Path("./agent_memory").resolve()  # real folder behind /memories
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
MAX_FILE_CHARS = 50_000  # cap how big one memory file can grow


class ToolFailure(Exception):
    """An error message we send back to Claude with is_error=True."""


def safe_path(virtual: str) -> Path:
    if virtual != "/memories" and not virtual.startswith("/memories/"):
        raise ToolFailure(f"Error: path must start with /memories, got {virtual}")
    real = (ROOT / virtual[len("/memories"):].lstrip("/")).resolve()
    if real != ROOT and ROOT not in real.parents:
        raise ToolFailure(f"Error: {virtual} would escape /memories")
    return real


def size_label(p: Path) -> str:
    return "4.0K" if p.is_dir() else f"{p.stat().st_size / 1024:.1f}K"


def view(cmd):
    path = cmd["path"]
    real = safe_path(path)
    if real.is_dir():
        rows = [f"{size_label(real)}\t{path}"]
        for item in sorted(real.rglob("*")):
            parts = item.relative_to(real).parts
            if len(parts) > 2 or any(x.startswith(".") or x == "node_modules" for x in parts):
                continue
            rows.append(f"{size_label(item)}\t{path.rstrip('/')}/{'/'.join(parts)}")
        return ("Here're the files and directories up to 2 levels deep in "
                f"{path}, excluding hidden items and node_modules:\n" + "\n".join(rows))
    if real.is_file():
        lines = real.read_text(encoding="utf-8").splitlines()
        start, end = 1, len(lines)
        if cmd.get("view_range"):
            start, end = cmd["view_range"]
            end = len(lines) if end == -1 else min(end, len(lines))
        body = "\n".join(f"{i:6d}\t{lines[i - 1]}" for i in range(start, end + 1))
        return f"Here's the content of {path} with line numbers:\n{body}"
    raise ToolFailure(f"The path {path} does not exist. Please provide a valid path.")


def create(cmd):
    real = safe_path(cmd["path"])
    if len(cmd["file_text"]) > MAX_FILE_CHARS:
        raise ToolFailure(f"Error: file is larger than {MAX_FILE_CHARS} characters")
    real.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
    real.write_text(cmd["file_text"], encoding="utf-8")  # overwrite is allowed
    return f"File created successfully at: {cmd['path']}"


def str_replace(cmd):
    path, old = cmd["path"], cmd["old_str"]
    real = safe_path(path)
    if not real.is_file():
        raise ToolFailure(f"Error: The path {path} does not exist. Please provide a valid path.")
    text = real.read_text(encoding="utf-8")
    hits = text.count(old)
    if hits == 0:
        raise ToolFailure(f"No replacement was performed, old_str `{old}` did not appear verbatim in {path}.")
    if hits > 1:
        nums = [str(n) for n, line in enumerate(text.splitlines(), 1) if old in line]
        raise ToolFailure(f"No replacement was performed. Multiple occurrences of old_str `{old}` "
                          f"in lines: {', '.join(nums)}. Please ensure it is unique")
    real.write_text(text.replace(old, cmd.get("new_str", ""), 1), encoding="utf-8")
    return "The memory file has been edited."


def insert(cmd):
    path, n = cmd["path"], cmd["insert_line"]
    real = safe_path(path)
    if not real.is_file():
        raise ToolFailure(f"Error: The path {path} does not exist")
    lines = real.read_text(encoding="utf-8").splitlines()
    if not 0 <= n <= len(lines):
        raise ToolFailure(f"Error: Invalid `insert_line` parameter: {n}. It should be "
                          f"within the range of lines of the file: [0, {len(lines)}]")
    lines.insert(n, cmd["insert_text"].rstrip("\n"))
    real.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return f"The file {path} has been edited."


def delete(cmd):
    path = cmd["path"]
    real = safe_path(path)
    if real == ROOT:
        raise ToolFailure("Error: the /memories directory itself cannot be deleted")
    if real.is_dir():
        shutil.rmtree(real)
    elif real.is_file():
        real.unlink()
    else:
        raise ToolFailure(f"Error: The path {path} does not exist")
    return f"Successfully deleted {path}"


def rename(cmd):
    old, new = safe_path(cmd["old_path"]), safe_path(cmd["new_path"])
    if old == ROOT:
        raise ToolFailure("Error: the /memories directory itself cannot be renamed")
    if not old.exists():
        raise ToolFailure(f"Error: The path {cmd['old_path']} does not exist")
    if new.exists():
        raise ToolFailure(f"Error: The destination {cmd['new_path']} already exists")
    new.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
    old.rename(new)
    return f"Successfully renamed {cmd['old_path']} to {cmd['new_path']}"


HANDLERS = {"view": view, "create": create, "str_replace": str_replace,
            "insert": insert, "delete": delete, "rename": rename}


def run_memory(cmd: dict) -> tuple[str, bool]:
    handler = HANDLERS.get(cmd.get("command"))
    if handler is None:
        return f"Error: unknown command {cmd.get('command')}", True
    try:
        return handler(cmd), False
    except ToolFailure as e:
        return str(e), True
    except (OSError, UnicodeDecodeError, KeyError, ValueError) as e:
        return f"Error: {e}", True

The tool-use loop

Now plug the handler into a plain loop with client.messages.create. Because the memory tool is GA, you do not need the beta client here.

import anthropic
from memory_handler import run_memory

client = anthropic.Anthropic()
MEMORY_TOOL = {"type": "memory_20250818", "name": "memory"}

messages = [{"role": "user",
             "content": "What do you know about Acme Corp? Save anything new you learn."}]

while True:
    response = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=2048,
        tools=[MEMORY_TOOL],
        messages=messages,
    )
    messages.append({"role": "assistant", "content": response.content})
    if response.stop_reason != "tool_use":
        break

    results = []
    for block in response.content:
        if block.type == "tool_use" and block.name == "memory":
            text, failed = run_memory(block.input)
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": text,
                "is_error": failed,
            })
    messages.append({"role": "user", "content": results})

print("".join(b.text for b in response.content if b.type == "text"))

Errors go back with "is_error": true. Claude reads the message and usually retries with a fixed path or a unique old_str.

Subclassing the SDK base class instead

If you still want tool_runner to drive the loop, subclass BetaAbstractMemoryTool. You must implement six methods. Each one gets a typed command object.

from anthropic.lib.tools import ToolError
from anthropic.tools import BetaAbstractMemoryTool


class DatabaseMemoryTool(BetaAbstractMemoryTool):
    """Store memory files in your own database instead of on disk."""

    def __init__(self, user_id: str):
        super().__init__()
        self.user_id = user_id  # one memory space per user

    def view(self, command):
        # command.path, command.view_range
        raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.")

    def create(self, command):        # command.path, command.file_text
        ...

    def str_replace(self, command):   # command.path, command.old_str, command.new_str
        ...

    def insert(self, command):        # command.path, command.insert_line, command.insert_text
        ...

    def delete(self, command):        # command.path
        ...

    def rename(self, command):        # command.old_path, command.new_path
        ...

Raise ToolError to send an error string back to Claude. There is also a BetaAsyncAbstractMemoryTool for async apps.

The Six Memory Commands

Claude only ever sends these six commands. Your handler must answer all of them.

Command Input fields Success string
view path, optional view_range Directory list (2 levels deep) or file with 6-wide line numbers
create path, file_text File created successfully at: {path}
str_replace path, old_str, optional new_str The memory file has been edited.
insert path, insert_line, insert_text The file {path} has been edited.
delete path Successfully deleted {path}
rename old_path, new_path Successfully renamed {old_path} to {new_path}
  • view_range: [start, end] returns those lines, and [start, -1] reads to the end.
  • insert_line 0: inserts at the very top of the file.
  • create on an existing file: the reference returns an error, but Claude’s tool description says “creates or overwrites”, so overwriting is a valid choice.
  • delete and rename: reject any attempt on the /memories root itself.

Context Editing Strategies Explained

Context editing runs on Anthropic’s side before the prompt reaches Claude. Your app keeps the full history and sends it as normal. The API trims it on the fly, so you never need to sync an edited copy.

Tool result clearing (clear_tool_uses_20250919)

Once the prompt passes a threshold, the API removes the oldest tool results and leaves a placeholder that tells Claude it was cleared. This suits agents that read many files or search results.

Option Default What it controls
trigger 100,000 input tokens When clearing starts. Set in input_tokens or tool_uses.
keep 3 tool uses How many recent tool use/result pairs stay.
clear_at_least None Minimum tokens to clear, or nothing is cleared. Protects your cache.
exclude_tools None Tool names that are never cleared.
clear_tool_inputs false Also clear the tool call parameters, not just results.
Claude docs table of tool result clearing options showing trigger default 100,000 input tokens and keep default 3 tool uses
Official Claude Platform Docs context editing page (checked 3 Dec 2026).

Thinking block clearing (clear_thinking_20251015)

This strategy decides how many earlier assistant turns keep their thinking blocks. Set keep to {"type": "thinking_turns", "value": N} with N above 0, or to "all".

  • If you add the strategy without keep: you get 1 thinking turn on every model.
  • If you leave the strategy out: each model uses its own default. Opus 4.5+, Sonnet 4.6+, Haiku 5.5+ and all Fable and Mythos models keep all prior thinking.
  • Cache trade-off: keeping thinking preserves your prompt cache. Clearing it frees space but breaks the cache at that point.

Warning: When you combine both strategies, clear_thinking_20251015 must be listed first in the edits array.

How to see what was cleared

Each response has a context_management.applied_edits list. Every entry shows the strategy type plus cleared_tool_uses or cleared_thinking_turns and cleared_input_tokens. When streaming, it arrives in the final message_delta event.

You can also preview the effect before sending, because the token counting endpoint accepts the same settings:

import anthropic

client = anthropic.Anthropic()
history = [{"role": "user", "content": "Continue our conversation..."}]  # your saved messages

count = client.beta.messages.count_tokens(
    model="claude-sonnet-5-5",
    messages=history,
    tools=[{"type": "memory_20250818", "name": "memory"}],
    betas=["context-management-2025-06-27"],
    context_management={"edits": [{
        "type": "clear_tool_uses_20250919",
        "trigger": {"type": "input_tokens", "value": 30000},
        "keep": {"type": "tool_uses", "value": 5},
    }]},
)
print("Before clearing:", count.context_management.original_input_tokens)
print("After clearing: ", count.input_tokens)

Example 3: Memory + Context Editing for a Long Agent

This is where the two features click. When the conversation nears the clearing threshold, Claude gets an automatic warning so it can save key facts to memory before old tool results disappear. Later, it reads the memory file instead of the cleared output.

The agent below reviews 20 log files. Each file is big, so old results get cleared, but the findings live on in /memories/log_review.md.

from pathlib import Path

import anthropic
from anthropic import beta_tool
from anthropic.tools import BetaLocalFilesystemMemoryTool

client = anthropic.Anthropic()
memory = BetaLocalFilesystemMemoryTool(base_path="./memory")


@beta_tool
def read_log(name: str) -> str:
    """Read one log file from ./logs and return its text.

    Args:
        name: File name inside the logs folder, for example app-01.log
    """
    path = (Path("./logs") / name).resolve()
    if Path("./logs").resolve() not in path.parents:
        return "Error: file must be inside ./logs"
    return path.read_text(encoding="utf-8")[:20_000]


runner = client.beta.messages.tool_runner(
    model="claude-sonnet-5-5",
    max_tokens=4096,
    max_iterations=40,
    tools=[memory, read_log],
    betas=["context-management-2025-06-27"],
    context_management={
        "edits": [
            # thinking clearing must come first when you combine strategies
            {"type": "clear_thinking_20251015",
             "keep": {"type": "thinking_turns", "value": 2}},
            {"type": "clear_tool_uses_20250919",
             "trigger": {"type": "input_tokens", "value": 30000},
             "keep": {"type": "tool_uses", "value": 3},
             "clear_at_least": {"type": "input_tokens", "value": 5000},
             "exclude_tools": ["memory"]},
        ]
    },
    messages=[{
        "role": "user",
        "content": "Read app-01.log to app-20.log one by one. After each file, "
                   "save the errors you found to /memories/log_review.md. "
                   "Then write a final summary.",
    }],
)

for message in runner:
    edits = message.context_management.applied_edits if message.context_management else []
    print(message.usage.input_tokens, "input tokens |", len(edits), "edits applied")
print(message.content[-1].text if message.content else "")

Why these settings

  • trigger 30,000: clears early so each call stays cheap. Raise it if Claude needs more history.
  • clear_at_least 5,000: clearing breaks the prompt cache, so only do it when the saving is worth a new cache write.
  • exclude_tools memory: keeps recent memory reads visible. Drop this if your memory files are large.
  • max_iterations 40: stops a runaway loop from burning tokens.

Same request with curl

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "anthropic-beta: context-management-2025-06-27" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 2048,
    "tools": [{"type": "memory_20250818", "name": "memory"}],
    "context_management": {
      "edits": [{"type": "clear_tool_uses_20250919"}]
    },
    "messages": [
      {"role": "user", "content": "Check your memory, then help me plan my week."}
    ]
  }'

Note: Anthropic now says server-side compaction is the main tool for most long chats. A good pattern for very long agents is compaction plus memory: compaction keeps the context small, and memory holds what must survive the summary. The old client-side compaction_control was removed from the Python SDK in v1.0.

Pricing and a Worked Cost Example

Neither feature has its own fee. The memory tool is a client tool, so you pay standard token prices. Every memory command and result adds tokens, plus the tool-use system prompt (286 tokens on Opus 5.5, Sonnet 5.5 and Haiku 5.5).

Model Input / MTok Cache hit / MTok Output / MTok
Claude Fable 5.2 $8 $0.20 $40
Claude Opus 5.5 $4 $0.20 $20
Claude Sonnet 5.5 $2 $0.10 $10
Claude Haiku 5.5 (prompts up to 100K) $0.10 $0.01 $0.50

Worked example (illustration only)

Say a Sonnet 5.5 agent makes 40 calls in one session and writes 800 output tokens per call. Output costs 32,000 tokens x $10 / 1M = $0.32 either way.

  • Without clearing: history grows to an average of 60,000 input tokens per call. That is 2.4M tokens, or $4.80 of input.
  • With clearing at 30,000: the average might sit near 25,000 tokens per call. That is 1M tokens, or $2.00 of input.

Real numbers depend on caching and how big your tool results are. Read my Claude API pricing guide and prompt caching guide to plan the cache side.

Limits and Defaults

Limit Value
Memory root Always /memories (a virtual prefix you map to real storage)
Directory view depth 2 levels, hidden files and node_modules skipped
Max file length 999,999 lines, then return an error
Long text views Claude expects files over 16,000 characters to be truncated, then pages with view_range
Images view may be called on .jpg, .jpeg and .png
Tool clearing trigger Default 100,000 input tokens
Compaction trigger Default 150,000, minimum 50,000 input tokens
Data retention Memory tool is ZDR and HIPAA eligible (excluding Covered Models)

Securing the Memory Directory

Your app runs every file operation Claude asks for. That makes the handler a security boundary, just like any code that takes paths from user input.

  • Block path traversal: only allow paths that start with /memories. Resolve each path with pathlib.Path.resolve() and confirm it is still inside the root. Watch for ../, ..\ and URL-encoded forms like %2e%2e%2f.
  • One folder per user: map /memories to a folder keyed by user or tenant, so one customer’s notes never leak into another’s session.
  • Strip sensitive data: Claude usually refuses to save secrets, but add your own filter for keys, card numbers and emails before writing.
  • Cap file sizes: limit how big a file can get and how much view returns.
  • Expire old memories: delete files nobody has read in a long time.
  • Tight permissions: use 0o700 folders and 0o600 files, and watch for symlinks that point outside the root.
  • Treat memory as untrusted input: anything saved in one session is read as context in the next, so a poisoned note could steer the agent later.

For agents that also use MCP servers, my MCP security best practices post covers the same “untrusted tool output” problem in more depth.

Troubleshooting: Common Errors and Fixes

Error or symptom Likely cause Fix
400 error mentioning context_management Beta header missing Use client.beta.messages with betas=["context-management-2025-06-27"]
400 error when combining strategies Thinking clearing is not first Put clear_thinking_20251015 first in edits
400 error on the tool definition Wrong name or an added schema Use exactly {"type": "memory_20250818", "name": "memory"}
The path /memories/x does not exist Claude guessed a file name Normal. Claude will view the folder and retry
Multiple occurrences of old_str Text to replace is not unique Return the error with is_error. Claude adds more context
Nothing is ever cleared Prompt below trigger, or clear_at_least not reachable Lower the trigger or the minimum. Check applied_edits
Cache hits drop after clearing Clearing changes the prompt prefix Raise clear_at_least so clearing happens less often
TypeError for compaction_control Removed in Python SDK v1.0 Use the compact_20260112 edit instead
Memory files readable by others Wide umask in containers Create folders with 0o700 and chmod 600 files
429 or 529 errors in long loops Rate limit or overload Back off and retry. See my 429 and 529 fix guide

Frequently Asked Questions

Is the Claude memory tool still in beta?

No. The memory tool stopped needing a beta header on 17 February 2026 and is generally available. Context editing is still beta and needs context-management-2025-06-27.

Where does Claude store memory files?

Wherever your code puts them. Claude only sends commands for paths under /memories, and your handler maps that to a folder, database or bucket you own.

Does the memory tool cost extra?

No separate fee. You pay normal input and output tokens for the tool calls, the results and the small tool-use system prompt.

Do I have to write my own handler in Python?

No. BetaLocalFilesystemMemoryTool from anthropic.tools works out of the box with tool_runner. Subclass BetaAbstractMemoryTool when you need custom storage.

Should I use context editing or compaction?

Anthropic recommends server-side compaction for most long conversations. Use context editing when you want exact control, like clearing only old search results while keeping everything else.

Does context editing change my saved conversation?

No. Clearing happens on the server before the prompt reaches Claude. Your local message history stays complete, and you keep sending it as normal.

Is the API memory tool the same as memory in the Claude app?

No. The app feature is managed by Anthropic for chat users. The API tool is for developers and stores files only in your own storage.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a server room holding a tablet with a CLAUDE MEMORY card, hook memory tool no beta header