What you will be able to do
- Choose between server-side compaction on demand, compaction at a token threshold, and your own summarizer
- Configure tool result clearing and thinking block clearing with the right parameters
- Weigh context clearing against prompt cache invalidation
- Know when the SDK's client-side compaction is a poor fit
1.Server-side compaction
Anthropic's context engineering guidance says to find the smallest possible set of high-signal tokens that make the result you want most likely. The model's attention is finite, so every token you add takes some of it.
When a conversation or agent task keeps growing, the main tool for this is server-side compaction. Claude writes a summary of the older turns on the server, and that summary replaces them. You write no summarization code. It keeps the task inside the window and keeps active context small. It is in beta for Claude 4.6 and later models and Claude Mythos Preview.
| Aspect | Compaction on demand | Compaction at a token threshold | Your own summarizer |
|---|---|---|---|
| Who decides when | You, by sending a request | The API, when input tokens reach the trigger you set | You |
| Code you write | A compaction loop that requests the summary and swaps it in | One parameter on your ordinary requests | The summarization call, its prompt, and the history rewrite |
| Runs in the background | Yes | No: it runs inside the request that reaches the threshold | Yes, in your own code |
| Setup | compact-2026-09-04 beta header and the top-level compaction parameter | See the threshold compatibility list | None |
Pick on-demand when your application has to control when compaction happens, can't pause while a summary is written, or must keep recent turns word for word along with their thinking. Pick threshold compaction when you want the API to handle context inside ordinary requests. If the default summary drops something a later turn needs, you can supply your own summarization prompt.
Threshold compaction works differently from on-demand in a few ways. You set a trigger, and the API compacts when input tokens reach it. You add one parameter to your ordinary requests. You append the response as usual, and the API drops what came before the compaction block. It runs inside the request that reaches the threshold, so it cannot run in the background. You can keep recent turns word for word only by pausing after compaction and re-inserting them. On Claude Fable 5.1, Claude Opus 5.5, and Claude Sonnet 5.5, remove or drop the thinking in the turns you re-insert.
Checkpoint 1 of 8· Match them up
Match each compaction approach to who triggers it and what you build
Tap a term, then the definition that fits it.
The difference is who decides when compaction runs, and how much code that leaves for you.
“The API, when input tokens reach the trigger you set”Source: platform.claude.com
Compaction keeps you under the window, and the window has hard edges. If the input alone already exceeds the model's context window, the API returns a 400 invalid_request_error ("prompt is too long") on every model.
Input tokens plus max_tokens is a different case. On Claude 4.5 models and newer, if that sum exceeds the context window size, the API still accepts the request. If generation then reaches the window limit, it stops with stop_reason: "model_context_window_exceeded". On earlier models, the API returns a validation error instead. To opt in to the model_context_window_exceeded behavior on those models, use the model-context-window-exceeded-2025-08-26 beta header. To stay within the limits, estimate usage with the token counting API before you send.
Checkpoint 2 of 8· Exam question
A developer calling Claude Opus 4.8 sends a request where the input tokens alone fit comfortably within the model's context window, but input tokens plus the requested max_tokens together exceed it. What should they expect from the API?
Correct answer: A — The API accepts the request, and if generation reaches the context window limit it stops early with stop_reason set to model_context_window_exceeded
- A. Correct. On Claude 4.5 models and newer, a request where input plus max_tokens exceeds the window is still accepted. If generation actually reaches the limit, the response stops with stop_reason model_context_window_exceeded rather than failing upfront.
- B. Incorrect. The 400 invalid_request_error for a prompt being too long is reserved for cases where the input alone already exceeds the context window, not when only input-plus-max_tokens would exceed it.
- C. Incorrect. The Claude API does not perform rolling first-in-first-out trimming of conversation history on your behalf; that behavior is associated with some chat interfaces, not standard API requests.
- D. Incorrect. Context window size is fixed per model and is not dynamically expanded for an individual request based on the max_tokens value requested.
2.Context editing: clearing by rule
Compaction summarizes. Context editing removes content by rule instead, and it runs on the server before the prompt reaches Claude. It requires the context-management-2025-06-27 beta header. There are two strategies.
Tool result clearing (clear_tool_uses_20250919) is for agents that use tools heavily. Once Claude has processed an old file read or search result, it is rarely needed again. When the threshold is crossed, the API clears the oldest results first and puts placeholder text in their place. By default only results are cleared. Set clear_tool_inputs to true to clear the tool call parameters too.
context_management={
"edits": [
{
"type": "clear_tool_uses_20250919",
# Trigger clearing when threshold is exceeded
"trigger": {"type": "input_tokens", "value": 30000},
# Number of tool uses to keep after clearing
"keep": {"type": "tool_uses", "value": 3},
# Optional: Clear at least this many tokens
"clear_at_least": {"type": "input_tokens", "value": 5000},
# Exclude these tools from being cleared
"exclude_tools": ["web_search"],
}
]
},| Parameter | Default | Meaning |
|---|---|---|
| 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 survive |
| clear_at_least | None | Minimum tokens to clear, or the strategy is skipped |
| exclude_tools | None | Tools whose uses and results are never cleared |
| clear_tool_inputs | false | Also clear the tool call parameters |
Checkpoint 3 of 8· Check yourself
Your research agent's web_search results must never be cleared, but old file reads can go. Which parameter handles this?
exclude_tools lists the tools whose uses and results are never cleared. keep only sets how many recent pairs survive, whatever the tool.
“List of tool names whose tool uses and results should never be cleared.”Source: platform.claude.com
Thinking block clearing (clear_thinking_20251015) sets how many recent assistant turns keep their thinking. The default depends on the model: all turns on Opus 4.5+, Sonnet 4.6+ and the Fable and Mythos models, and only the last turn on earlier Opus and Sonnet models and all Haiku models.
Two more details. First, your client keeps the full, unedited history and never needs to sync with the edited version. Second, if you pair context editing with the memory tool, Claude gets an automatic warning as context nears the clearing threshold, so it can save important information to memory files before it is cleared.
Checkpoint 4 of 8· Fill the gap
Complete this config so that thinking blocks from the last two assistant turns are kept
context_management={
"edits": [
{
"type": "clear_thinking_20251015",
"keep": {"type": " ? ", "value": 2},
}
]
},For clear_thinking_20251015, keep is measured in thinking_turns. tool_uses and input_tokens belong to tool result clearing.
Source: platform.claude.comSources4
3.Keeping tool context small
Clearing by rule is not the only way to control what tools cost you in context. Everything in the request counts toward the window, including your tool definitions. To reduce the context the definitions themselves consume, see Manage tool context, or defer tool definitions with the tool search tool.
Another lever is programmatic tool calling, which Anthropic's cookbook lists among the ways to keep large results out of the window entirely. Prompt caching helps with the cost of repeated prefixes, but it changes what you pay for those tokens, not whether they count toward the window.
Checkpoint 5 of 8· Exam question
A production agent uses 45 different tools across long-running conversations. The team identifies three separate cost sources: tool schema definitions consuming context on every request even when most tools go unused that turn, many small sequential tool calls each leaving a tool_result in history, and the same stable tool definitions being resent and re-priced identically on every request. Which changes directly address these three sources?(Select 3)
Correct answers: A, B, C — Enable the tool search tool so schemas load on demand instead of being sent upfront; Use programmatic tool calling so chains of tool calls run as a single script instead of many roundtrips; Apply prompt caching to the stable tool definitions so repeated requests pay the discounted cache-read rate
- A. Correct. Tool search keeps tool definitions out of the context window until Claude requests them, directly reducing the baseline cost of unused schemas loaded upfront.
- B. Correct. Programmatic tool calling collapses chains of tool calls into a single executed script, so intermediate tool_result blocks never enter the conversation history.
- C. Correct. Prompt caching does not shrink the token count of tool definitions but cuts what repeated, stable definitions cost on subsequent requests via the discounted cache-read rate.
- D. Incorrect. max_tokens controls the ceiling on generated output length and has no effect on how much context tool definitions or tool_result history consume.
- E. Incorrect. A larger context window gives more headroom but does not reduce the underlying token cost of the toolset or address any of the three described cost sources.
- F. Incorrect. Shortening tool names yields negligible savings and is not a documented strategy for managing tool-related context cost compared to the other approaches.
4.Context management versus the prompt cache
Prompt caching and context management solve different problems. Cached prefixes still sit in the context window. Caching changes what you pay for those tokens, not whether they count. So caching never rescues a conversation that is about to hit the limit.
The two do interact. Tool result clearing invalidates cached prompt prefixes whenever it clears something, and each clearing triggers a new cache write. That is the reason for clear_at_least: if the API can't free at least that many tokens, it skips the clearing, so you only break the cache when the savings justify it. Thinking block clearing works the same way. Kept thinking preserves the cache, and clearing invalidates it at the point where clearing happens. Set keep according to which matters more to you, cache performance or free context space.
There is one model-specific nuance. On Claude Fable 5.1, Claude Opus 5.5, and Claude Sonnet 5.5, server-side context management never invalidates thinking blocks. Client-side edits to earlier turns can invalidate the thinking blocks in every later assistant turn.
Checkpoint 6 of 8· Check yourself
Why set clear_at_least on a tool result clearing strategy?
Every clear invalidates the cached prefix and costs a cache write. With clear_at_least, small clears that wouldn't pay for that are skipped.
“This helps determine if context clearing is worth breaking your prompt cache.”Source: platform.claude.com
To preview a configuration before you commit to it, pass the same context_management block to client.beta.messages.count_tokens. The response returns both the count after clearing and the original count.
{
"input_tokens": 25000,
"context_management": {
"original_input_tokens": 70000
}
}Sources4
5.Client-side SDK compaction and when it fits
There is also a client-side option. The TypeScript and Ruby SDKs offer compaction when you use tool_runner, turned on by adding compaction_control. The docs say server-side compaction is generally preferred. The SDK version watches token usage after each response. Once usage passes context_token_threshold (default 100,000), it asks for a summary in <summary></summary> tags and replaces the entire history with it. You can name a cheaper model to write summaries, or pass a custom summary_prompt. A lower threshold compacts more often and keeps contexts smaller. A higher one keeps more context but risks hitting the limit.
Checkpoint 7 of 8· Put it in order
Put the SDK's client-side compaction loop in order
- 1.The SDK replaces the entire message history with the summary
- 2.The conversation resumes from the summary
- 3.A summary prompt is added as a user turn and Claude writes a summary
- 4.The SDK checks total tokens against the threshold after a response
The steps are threshold check, summary generation, context replacement, continuation. The full history is replaced, not trimmed.
“The SDK extracts the summary and replaces the entire message history with it.”Source: platform.claude.com
One known problem: the SDK adds input, cache-creation, cache-read and output tokens together. After server-side tools such as web search, cache_read_input_tokens includes reads from the tool's internal calls. The total then looks inflated and compaction fires too early. The workarounds are to get an accurate length from the token counting endpoint, or to avoid this compaction when you rely heavily on server tools. It works best for long tasks with measurable progress whose artifacts persist outside the conversation. It is a poor fit when a task needs exact recall of early details or has to track exact state across many variables.
Checkpoint 8 of 8· Check yourself
Which workload is LEAST suited to the SDK's client-side compaction?
Compaction replaces history with a summary, so exact early details can be lost. Tasks whose artifacts persist outside the conversation are the good cases.
“Tasks requiring precise recall of early conversation details”Source: platform.claude.com
Sources4
Exam traps
Each one states something that sounds right. Open it to see what is actually true.
1.Prompt caching frees up context window space for long conversations.Why is that wrong?
Cached tokens still count toward the window. Caching only lowers what you pay for them.
Covered in Context management versus the prompt cache
2.After server-side context editing clears tool results, your client has to rewrite its local history to match.Why is that wrong?
Editing happens on the server before Claude sees the prompt. The client keeps sending its full history.
Covered in Context editing: clearing by rule
3.The SDK's summed usage is always an accurate measure of conversation length.Why is that wrong?
After server-side tools, cache_read_input_tokens includes the tool's internal reads, so the SDK can trigger compaction too early.
Covered in Client-side SDK compaction and when it fits
Practise it for real
Measure how many tokens a tool result clearing configuration would save before you enable it in production
1.Take a long agent conversation with many tool results and run client.messages.count_tokens on it with no context management
Why: You need a baseline input count
You should see: A response with a single input_tokens value
2.Run client.beta.messages.count_tokens again with betas=["context-management-2025-06-27"] and a clear_tool_uses_20250919 edit with a trigger below your baseline
Why: The counting endpoint can preview the effect of context editing
You should see: input_tokens comes back lower than context_management.original_input_tokens
3.Add clear_at_least and raise it until clearing stops applying
Why: Clearing invalidates the prompt cache, so find the point where the savings stop being worth the cache rewrite
You should see: Once the API can't clear at least that amount, the strategy is not applied
Stuck? Get a nudge
If the savings are small, raise the trigger or drop context editing and rely on server-side compaction.
Sources
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“For long-running conversations and agentic workflows, server-side compaction is the primary strategy for context management.”
↩︎ Server-side compaction“the API returns a 400 invalid_request_error ("prompt is too long") on every model.”
↩︎ Server-side compaction“it stops with stop_reason: "model_context_window_exceeded".”
↩︎ Server-side compaction“or defer tool definitions with the tool search tool.”
↩︎ Keeping tool context small“Cached prompt prefixes still occupy the context window: prompt caching changes what you pay for those tokens, not whether they count.”
↩︎ Keeping tool context small“Cached prompt prefixes still occupy the context window: prompt caching changes what you pay for those tokens, not whether they count.”
↩︎ Exam trap 1 - 2.
“good context engineering means finding the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome”
↩︎ Server-side compaction - 3.
“Compaction replaces the older turns of a conversation with a summary that Claude writes on the server”
↩︎ Server-side compaction“The response, appended as usual. The API drops what came before the block”
↩︎ Server-side compaction“Use on-demand compaction wherever it is available.”
↩︎ Prediction“The API, when input tokens reach the trigger you set”
↩︎ Checkpoint - 4.
“The API replaces each cleared result with placeholder text indicating to Claude that it was removed.”
↩︎ Context editing: clearing by rule“When your conversation context approaches the configured clearing threshold, Claude receives an automatic warning to preserve important information.”
↩︎ Context editing: clearing by rule“Invalidates cached prompt prefixes when content is cleared.”
↩︎ Context management versus the prompt cache“Configure the keep parameter based on whether you want to prioritize cache performance or context window availability.”
↩︎ Context management versus the prompt cache“server-side context management never invalidates thinking blocks.”
↩︎ Context management versus the prompt cache“An SDK-based alternative for summary-based context management (server-side compaction is generally preferred)”
↩︎ Client-side SDK compaction and when it fits“A lower threshold means more frequent compactions with smaller context windows. A higher threshold allows more context but risks hitting limits.”
↩︎ Client-side SDK compaction and when it fits“Your client application maintains the full, unmodified conversation history. You do not need to sync your client state with the edited version.”
↩︎ Exam trap 2“the cache_read_input_tokens value includes accumulated reads from multiple internal API calls made by the server-side tool, not your actual conversation context.”
↩︎ Exam trap 3“List of tool names whose tool uses and results should never be cleared.”
↩︎ Checkpoint“This helps determine if context clearing is worth breaking your prompt cache.”
↩︎ Checkpoint“The SDK extracts the summary and replaces the entire message history with it.”
↩︎ Checkpoint“Tasks requiring precise recall of early conversation details”
↩︎ Checkpoint - 5.https://platform.claude.com/cookbook/tool-use-context-engineering-context-engineering-toolsSecondary source
“programmatic tool calling that keeps large results out of the window entirely”
↩︎ Keeping tool context small