Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool

A refund agent loses its context between sessions and refunds R-11 twice. Context editing and compaction keep the window small; only the memory tool's notes under /memories survive a reset, so session two goes straight to R-13.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Tell context editing, compaction and the memory tool apart by the problem each one solves
  • Turn on the client-side memory tool and write a handler that keeps every path under /memories
  • Add a context editing rule that clears old tool results past a trigger
  • Make a second session resume from notes instead of redoing the work

Before you start

  • Claude tool use: tool_use and tool_result
  • Context engineering: what belongs in the context window

A refund agent works through a list of tickets. In session one it finishes R-11 and R-12; R-13 is still waiting. Then the session ends and the context window is gone. Session two starts blank. It has no way to know what was done, so it starts again at R-11. A refund goes out twice.

The agent did the work and then lost the record of it. The fix is a notebook outside the window. Claude has three tools for this kind of problem, and only one of them survives a reset.

A desk and a notebook

Picture someone at a busy desk with three habits:

  • Clear the desk. Old papers go in the bin. In the agent, old tool results are cleared: context editing.
  • Summarise the pile. One short page replaces many. Older turns become a summary: compaction.
  • Write in a notebook and keep it in the drawer. The notes outlive the desk: the memory tool.
Trim, summarise, remember Context editing clears old tool results past a trigger server side, beta problem: results pile up Compaction older turns become a summary server side, beta problem: the chat grows Memory tool files under /memories in your own storage client side problem: work must outlive the session these two shrink the window only this survives a reset
Pick the pattern by the problem. Clearing and summarising shrink the window; memory keeps the facts.

The general ideas behind clearing, compacting and keeping notes are covered in context engineering for a long-running agent. This article is about the Claude-specific pieces: the memory tool and the context editing rule.

Claude asks, your app runs

The memory tool is client-side. To turn it on, you add one entry to the tools list: {"type": "memory_20250818", "name": "memory"}. That's the whole configuration. When Claude wants a file, it sends a tool_use with a command such as view. Your app runs the command against your storage, and the text goes back as a tool_result. You decide where the notes live: a folder, a database, anything.

The tool has six commands: view, create, str_replace, insert, delete and rename. The lecture's handler implements four of them.

memory_store.py: the handler

"""The client-side half of the memory tool.
Claude asks for a file operation. This code runs it."""
ROOT = "/memories"


def numbered(text):
    rows = enumerate(text.splitlines(), 1)
    return "\n".join(f"{i:6d}\t{r}" for i, r in rows)


class MemoryStore:
    def __init__(self):
        # path -> text. Swap this dict for a folder or a database.
        self.files = {}

    def view(self, path):
        if path == ROOT:
            rows = sorted(self.files.items())
            names = "\n".join(f"{len(t)}\t{p}" for p, t in rows)
            return f"Files in {ROOT}:\n{names}"
        if path not in self.files:
            return f"The path {path} does not exist."
        return f"Content of {path}:\n" + numbered(self.files[path])

    def run(self, cmd):
        path = cmd.get("path", ROOT)
        inside = path == ROOT or path.startswith(ROOT + "/")
        if not inside or ".." in path:
            return f"Error: {path} is outside {ROOT}"
        op = cmd["command"]
        if op == "view":
            return self.view(path)
        if op == "create":
            self.files[path] = cmd["file_text"]
            return f"File created successfully at: {path}"
        if op == "insert":
            lines = self.files[path].splitlines(keepends=True)
            at, new = cmd["insert_line"], cmd["insert_text"]
            lines.insert(at, new)
            self.files[path] = "".join(lines)
            return f"The file {path} has been edited."
        if op == "delete":
            del self.files[path]
            return f"Successfully deleted {path}"
        return f"Error: unknown command {op}"

The first check matters most: every path must sit under /memories, and anything with .. is refused, so a path can't escape the folder. You're running file operations that a model asked for; treat the path as untrusted input.

agent.py: the tool, the rule and the loop

"""One agent session: a tool-use loop with memory and context editing."""
MODEL = "claude-sonnet-5-5"
LOOKUP = {"name": "lookup_ticket",
          "description": "Fetch one refund ticket by id.",
          "input_schema": {"type": "object",
                           "properties": {"ticket_id": {"type": "string"}},
                           "required": ["ticket_id"]}}
TOOLS = [{"type": "memory_20250818", "name": "memory"}, LOOKUP]
# The server clears the oldest tool results past the trigger.
CONTEXT_EDITING = {"edits": [{
    "type": "clear_tool_uses_20250919",
    "trigger": {"type": "input_tokens", "value": 30000},
    "keep": {"type": "tool_uses", "value": 3}}]}
BETAS = ["context-management-2025-06-27"]


def lookup_ticket(ticket_id):
    """A stand-in order system. Forty fields come back."""
    fields = " ".join(f"field{n}=x" for n in range(40))
    return f"{fields} ticket={ticket_id}"


def run_tool(store, block):
    if block.name == "memory":
        out = store.run(block.input)
    else:
        out = lookup_ticket(block.input["ticket_id"])
    return {"type": "tool_result", "tool_use_id": block.id,
            "content": out}


def run_session(client, store, task, max_calls, log):
    messages = [{"role": "user", "content": task}]
    for call in range(1, max_calls + 1):
        r = client.beta.messages.create(
            model=MODEL, max_tokens=1024, tools=TOOLS,
            messages=messages, betas=BETAS,
            context_management=CONTEXT_EDITING)
        reply = {"role": "assistant", "content": r.content}
        messages.append(reply)
        if r.stop_reason != "tool_use":
            return f"finished: {r.content[0].text}"
        results = []
        for block in r.content:
            if block.type == "tool_use":
                log(call, block)
                results.append(run_tool(store, block))
        messages.append({"role": "user", "content": results})
    return "stopped: the context window was reset"
  • The memory tool sits in the tools list next to our own lookup_ticket.
  • The context editing rule: once the prompt passes 30,000 input tokens, the server clears the oldest tool results and keeps the latest three. It needs the context-management-2025-06-27 beta flag on client.beta.messages.create.
  • Memory calls go to our handler; anything else goes to the ticket lookup. Each answer is wrapped as a tool_result.
  • The loop is the ordinary one from the agentic loop article: it ends when the stop reason is anything but tool_use. Here max_calls plays the session ending.

Two sessions, one notebook

run_all.py runs two sessions on the same task, "Refund tickets R-11, R-12 and R-13. Check your memory first." Session one gets a budget of five calls, then its context is thrown away. The memory store is kept.

session 1
  call 1: memory view /memories
  call 2: lookup_ticket R-11
  call 3: memory create /memories/progress.md
  call 4: lookup_ticket R-12
  call 5: memory insert /memories/progress.md
  stopped: the context window was reset
  context chars: 93 -> 1968 over 5 calls
  memory now: R-11: refunded 24.00 | R-12: refunded 61.50
session 2
  call 1: memory view /memories
  call 2: memory view /memories/progress.md
  call 3: lookup_ticket R-13
  call 4: memory insert /memories/progress.md
  finished: test model reply: resumed after R-12. R-13 refunded, all three done.
  context chars: 93 -> 1725 over 5 calls
  memory now: R-11: refunded 24.00 | R-12: refunded 61.50 | R-13: refunded 18.25
sent every call: memory_20250818, lookup_ticket + clear_tool_uses_20250919
outside the store: Error: /memories/../secrets.env is outside /memories

The model is a scripted stand-in (the amounts are made up), and it sends no real clearing; the context editing rule is only carried in the request. What to notice:

  • Session one checked memory, found it empty, and wrote a note after each ticket.
  • Session two started with a blank context, viewed the folder, read the progress file, and went straight to R-13. It never looked at R-11 or R-12 again.
  • A path that tries to leave /memories is refused.

Warn, save, then clear

The patterns work best together. As the agent works, tool results pile up. When the context nears the clearing threshold, Claude gets an automatic warning to save what matters, so it writes its notes to memory. Then the oldest results are cleared, and nothing important is lost because it's already in the notes. Compaction pairs with memory the same way: compaction keeps the active context small, memory keeps what must survive the summary.

Common mistakes

  • Raising max_tokens. That only caps one reply. It does nothing for a reset.
  • Resending the whole history every time. The window grows until it overflows.
  • Summarising harder. A summary can drop an exact fact, like which ticket was already refunded.
  • Trusting the path. Without the /memories check, a model-chosen path could read or write anywhere your handler can.
  • Writing notes but not reading them. Tell the agent to view its memory first, at the start of every session.

Quick recap

PatternWhere it runsWhat it fixes
Context editing (clear_tool_uses_20250919)Server, betaOld tool results piling up
CompactionServer, betaA long conversation
Memory tool (memory_20250818)Your code and storageWork that must outlive the session

The desk is small; the notebook is not. When an agent misbehaves and you need to tell which of these patterns is missing, see reading an agent trace.

Try it yourself

Add str_replace to the handler, then change the agent so it marks a ticket "in progress" before the refund and "done" after. Stop session one between the two notes and decide what session two should do with an "in progress" ticket.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 32 of 66

Previous
Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
Next post
Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared

Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.

Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move

Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.

On this page

  • A desk and a notebook
  • Claude asks, your app runs
  • memory_store.py: the handler
  • agent.py: the tool, the rule and the loop
  • Two sessions, one notebook
  • Warn, save, then clear
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.