Context Engineering · 7 min read
Keeping tool results from flooding context: truncation, masking, summarisation and just-in-time retrieval
In most agents, tool output is the biggest thing in the context window. Here's how to shape it at the source, clear it once it's stale, and keep it recoverable, with what the research says about which approach pays.
Watch the context window of a working agent and you’ll see a pattern. The system prompt and the user’s request are small. The model’s own reasoning is modest. What fills the window is tool output: file contents, search results, logs, API responses, query results, web pages.
JetBrains researchers measured this for a coding agent. In their study, observation tokens (what tools and the environment send back) made up around 84% of an average SWE-agent turn. If you want a cheaper, faster agent that stays on track for longer, tool output is where to look first.
This post covers four levers, in the order you should reach for them: shape output at the source, clear stale output, summarise when you must, and keep everything you drop recoverable. (For background, see our posts on context rot and prompt and context compression.)
Lever 1: shape the output at the source
The cheapest token is one the tool never returns. Anthropic’s guide to writing tools for agents (September 2025) recommends that any tool that could return a lot of data use “some combination of pagination, range selection, filtering, and/or truncation”, with sensible default values. Anthropic says that for Claude Code, it limits tool responses to 25,000 tokens by default.
Three ideas from that guide are worth copying:
- Let the agent choose the level of detail. Anthropic shows a
response_formatparameter with"concise"and"detailed"options. In its example, the detailed response took 206 tokens and the concise one 72, about a third. Concise responses leave out IDs. If the agent needs them for a follow-up call, it asks for the detailed version. - Return meaning, not plumbing. The guide advises avoiding low-level fields such as
uuid,256px_image_urlormime_type. Fields likenameandfile_typeare more useful to the agent. Anthropic reports that swapping UUIDs for natural-language or simple numeric IDs significantly improved Claude’s precision on retrieval tasks by reducing hallucinations. - Truncate out loud. When you cut output, tell the agent so and suggest what to do next, such as running narrower searches. Silent truncation is worse than none, because the agent reasons as if it saw everything.
A truncation wrapper takes only a few lines:
MAX_CHARS = 20_000 # tune per tool
def shape(tool_name: str, text: str, hint: str) -> str:
if len(text) <= MAX_CHARS:
return text
head = text[: MAX_CHARS // 2]
tail = text[-MAX_CHARS // 4 :]
omitted = len(text) - len(head) - len(tail)
return (
f"{head}\n\n[... {omitted:,} characters omitted from {tool_name} output. "
f"{hint}]\n\n{tail}"
)
# e.g. hint="Re-run with a narrower path or a grep pattern to see the rest."
Keeping the head and the tail matters for logs and stack traces, where the useful line is often at the end.
Lever 2: clear stale tool results (observation masking)
A file the agent read twenty steps ago, or a search it has already acted on, is rarely needed in full. Observation masking keeps the agent’s reasoning and actions but replaces older tool outputs with a short placeholder.
The most useful evidence on this comes from The Complexity Trap (Lindenbauer and colleagues at JetBrains Research and TUM, presented at a NeurIPS 2025 workshop). They compared three setups on SWE-bench Verified: a raw agent with unbounded history, observation masking with a rolling window of the last 10 turns, and LLM summarisation of older turns. Selected SWE-agent results from the paper:
| Model | Strategy | Solve rate | Cost per instance |
|---|---|---|---|
| Qwen3-Coder 480B | Raw agent | 53.4% | $1.29 |
| Qwen3-Coder 480B | Observation masking | 54.8% | $0.61 |
| Qwen3-Coder 480B | LLM summary | 53.8% | $0.64 |
| Gemini 2.5 Flash | Raw agent | 32.8% | $0.41 |
| Gemini 2.5 Flash | Observation masking | 35.6% | $0.18 |
| Gemini 2.5 Flash | LLM summary | 36.0% | $0.24 |
The authors’ conclusion is that summarisation “does not consistently, or significantly outperform” simple masking. Both strategies cut cost by more than 50% in most configurations. Not all, though: on Qwen3-32B with thinking enabled, the savings were around 10% for masking and zero for summarisation.
Two other findings are useful in practice:
- Summaries can make agents run longer. The JetBrains blog reports that agents using summarisation took more turns than with masking. Their explanation is that summaries can “smooth over, or hide” signs that the agent should already stop. The summarisation calls themselves sometimes cost more than 7% of the total per instance.
- The window size depends on your harness. A 10-turn window worked best for SWE-agent but degraded badly in OpenHands, which keeps failed retry turns in history. Tune the window for your harness rather than copying a number.
If you use Claude, the API can do this server-side. Anthropic’s context editing (in beta at the time of writing) has a clear_tool_uses_20250919 strategy that clears the oldest tool results once a token threshold is reached and replaces them with placeholder text. Your client still holds the full history. An example from the docs:
"context_management": {
"edits": [{
"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": ["web_search"]
}]
}
exclude_tools is worth noticing. Some results, such as a spec the agent must keep following, should never be cleared.
Lever 3: summarise, but as a last resort
Summarisation still has a place. A masked placeholder tells the agent that something happened, not what it learned. For very long runs, a summary carries the important facts forward.
The JetBrains paper’s hybrid approach is a good default. Use masking as the “first line of defense”, and summarise only after a large batch of turns. On their test slice, the hybrid was 7% cheaper than masking alone and 11% cheaper than summarisation alone. The authors note that reusing the single-strategy settings in the hybrid made cost efficiency worse, so tune it as its own configuration.
When you do summarise tool output, ask for structure: what was found, exact values (paths, IDs, numbers), what failed and why, and what is still unknown. Free-form prose tends to drop the one number that matters.
Lever 4: make every drop recoverable (just-in-time retrieval)
The safest way to remove a tool result is to make sure the agent can get it back. Manus describes using the file system as “the ultimate context”: unlimited in size and persistent. Its compression is “always designed to be restorable”. A web page’s content can leave the context as long as its URL stays, and a document’s contents can go as long as its path is still in the sandbox.
In practice:
- Write large tool outputs to a file or object store.
- Put a pointer in context: the path or URL, its size, and a one-line description.
- Give the agent tools to read a range, grep, or query that stored output when it needs details.
This turns a 40,000-token log dump into a 60-token reference that the agent can look into when it needs to. It’s also easier to debug, because the full output is kept.
Trade-offs to watch
| Concern | What can go wrong | Mitigation |
|---|---|---|
| Prompt caching | Clearing old content changes the prefix and invalidates the cache | Clear in large batches (Anthropic’s clear_at_least exists for this) |
| Errors | Masking failed attempts removes evidence the agent learns from | Manus advises leaving “the wrong turns” in context; keep errors short, not absent |
| Exact values | Summaries paraphrase IDs and numbers | Extract them into a structured “must keep” block |
| Hidden truncation | The agent acts on partial data as if it were complete | Always mark omissions and say how to get more |
| Over-tuning | A window that works in one harness fails in another | Re-tune per harness and model |
Caching deserves extra care. Manus calls the KV-cache hit rate “the single most important metric for a production-stage AI agent”. In their figures, cached input tokens cost 0.30 USD per million versus 3 USD uncached. Anthropic’s docs warn that clearing tool results invalidates cached prefixes. If you clear a little on every turn, cache misses can cancel out the savings.
Where to start
- Measure. Log token counts per message type for a week. Find out how much of your context is tool output, and which tools produce it.
- Fix the worst tools at the source. Add pagination, filters, a concise mode and explicit truncation messages. This is usually the biggest single improvement.
- Add observation masking with a rolling window, or turn on server-side context editing if your provider offers it. Exclude tools whose output must persist.
- Store big outputs outside the context and pass a pointer, so nothing you drop is lost for good.
- Add summarisation last, only for long runs. Compare it on your own eval set against masking alone, tracking solve rate, cost and number of turns.