Skip to content

Context engineering for AI agents that call tools

On this page

Context engineering is the work of deciding which tokens a model sees on each turn: the system prompt, tool definitions, tool results, conversation history and anything retrieved. For an agent that calls tools, much of that context comes from the tools themselves, and it grows with every call. Since model accuracy drops as context grows (context rot), the practical techniques all do one of three things: keep material out until it’s needed, remove it once it’s used, or process it somewhere else and bring back only the conclusion.

Checked as of November 2026 against Anthropic’s Effective context engineering for AI agents, Chroma’s Context Rot report, the Claude docs on context windows, compaction and context editing, Claude Code’s context window guide and the MCP tools specification (revision 2026-07-28).

What context engineering means

Anthropic’s engineering team defines it as “the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference”. Prompt engineering is about writing one good set of instructions. Context engineering covers everything else that reaches the model across many turns, which for an agent is mostly material the agent fetched itself.

The reason is architectural: every token attends to every other token, “n² pairwise relationships for n tokens”. The post concludes that context “must be treated as a finite resource with diminishing marginal returns”, and that the goal is “the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome”.

Where an agent’s context goes

The Claude docs are specific about what counts: the system prompt, every message (including tool results, images and documents), the tool definitions, and the output generated for the turn, including extended thinking. Here is where those tokens come from in a typical tool-using session:

ComponentWhen it entersHow it growsMain levers
System prompt and instruction files (CLAUDE.md, AGENTS.md)Every requestGrows as people add rulesKeep it short; move detail into files read on demand
Tool definitionsEvery request, unless deferredOne schema per tool, per connected serverFewer tools, tool search, blocking tools the agent never needs
Tool calls and resultsAfter each callEvery call adds its arguments and outputSmall results, pagination, context editing, code that filters results
Conversation historyEvery request after the firstEvery turn, including thinking on some modelsCompaction, /clear between tasks
Retrieved data (files, documents, search results)When the agent reads themWhatever the agent pulls inJust-in-time retrieval, subagents

Tool definitions are easy to underestimate. Under the MCP spec, each tool carries a name, a description, an inputSchema and optionally a title, an outputSchema and annotations. A client that loads every definition from a 40-tool server pays for all 40 on every request, before the agent has done anything. In Claude Code, /context shows the real split for your session by category.

Context rot: what the evidence says

Chroma’s July 2025 report, Context Rot: How Increasing Input Tokens Impacts LLM Performance by Kelly Hong, Anton Troynikov and Jeff Huber, tested 18 models from Anthropic, OpenAI, Google and Alibaba on deliberately simple tasks while varying input length. Its conclusion: “LLMs do not maintain consistent performance across input lengths.”

The details matter more than the headline:

  • Similarity: the less the question’s wording resembled the answer in the text, the faster performance fell as input grew.
  • Distractors: “Even a single distractor reduces performance relative to the baseline”, and four made it worse. A distractor is a passage that looks relevant but doesn’t answer the question.
  • Structure: shuffled filler text produced better results than coherent text, which the authors call surprising.
  • Conversation history: on LongMemEval, every model did significantly better with focused prompts of about 300 tokens than with the full history of about 113,000 tokens.
  • Copying: asked to reproduce a sequence of repeated words, all models degraded as length increased.

Anthropic’s docs now use the term directly: “As token count grows, accuracy and recall degrade, a phenomenon known as context rot.” Tool lists are affected too: Anthropic’s tool search documentation says Claude’s tool selection accuracy degrades past 30 to 50 available tools.

Chroma tested retrieval and replication, not multi-step agent work, so treat the results as a direction rather than a number to plan around. A bigger window doesn’t remove the effect either: several Claude models accept 1M tokens, and the docs still say more context “isn’t automatically better”. For agents the distractor finding matters most, because old tool results are exactly that: text that looks relevant and no longer is.

Techniques for tool-using agents

TechniqueWhat it keeps out of contextWhere it’s documented
Just-in-time retrievalData the agent hasn’t asked for yetAnthropic’s context engineering post
Small, paginated tool resultsBulk output from a single callMCP spec, Claude Code MCP docs
Context editingOld tool results that have been usedClaude API clear_tool_uses_20250919
CompactionOld conversation turns, replaced by a summaryClaude API, Claude Code /compact
SubagentsExploration, logs and large readsClaude Code subagents
Tool searchDefinitions of tools not needed this turnClaude API tool search, Claude Code
Code that calls toolsIntermediate results between callsProgrammatic tool calling, Code Mode
Notes and memoryNothing directly; it lets you clear safelyClaude API memory tool, Claude Code auto memory

Just-in-time retrieval

Rather than loading everything that might be relevant up front, the agent keeps “lightweight identifiers (file paths, stored queries, web links, etc.)” and loads data with tools when it needs it. Anthropic describes Claude Code as a hybrid: CLAUDE.md files go in at the start, while glob and grep let it “retrieve files just-in-time”.

Tool design decides whether this works. A search tool that returns IDs and short snippets, paired with a fetch tool for the full record, lets the model read only what it picks. MCP supports this directly: a tool result can contain a resource_link with a URI the client can fetch later instead of the full content. MCP vs RAG covers the search-then-fetch pattern in more detail.

Results still need a ceiling. tools/list supports cursor pagination in the MCP spec, and list tools should page too. Claude Code shows a warning when an MCP tool’s output exceeds 10,000 tokens, and when a successful text result exceeds MAX_MCP_OUTPUT_TOKENS (25,000 by default) it saves the result to a file and gives Claude the path instead.

Context editing: clear old tool results

Anthropic calls tool result clearing “one of the safest lightest touch forms of compaction”, asking: “once a tool has been called deep in the message history, why would the agent need to see the raw result again?” On the Claude API this is the clear_tool_uses_20250919 strategy, in beta behind the context-management-2025-06-27 header:

python
response = client.beta.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=messages,
    tools=tools,
    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": 3},
                "clear_at_least": {"type": "input_tokens", "value": 5000},
                "exclude_tools": ["web_search"],
            }
        ]
    },
)

The API clears the oldest results first and leaves placeholder text so Claude knows something was removed. By default it triggers at 100,000 input tokens and keeps the 3 most recent tool uses; tool inputs stay unless you set clear_tool_inputs to true. The response’s context_management.applied_edits reports what was cleared.

Clearing invalidates the cached prompt prefix, so clear_at_least skips clearing unless it frees enough tokens to justify a new cache write. Use exclude_tools for results the agent keeps needing, such as a schema it looked up once.

Compaction

Compaction replaces older turns with a summary. The Claude API offers it two ways, both in beta. Compaction at a token threshold runs inside a normal request (beta header compact-2026-01-12):

JSON
{
  "context_management": {
    "edits": [
      {
        "type": "compact_20260112",
        "trigger": { "type": "input_tokens", "value": 150000 },
        "instructions": "Keep open bugs, file paths, IDs returned by tools and decisions made."
      }
    ]
  }
}

The trigger defaults to 150,000 input tokens and must be at least 50,000. Custom instructions replace the default summarization prompt rather than adding to it. Compaction on demand (beta header compact-2026-09-04) lets your application decide when: you send "compaction": {"type": "summarize"} and get back a signed compaction block that takes the place of the summarized messages. Anthropic’s overview recommends on-demand compaction where it’s available.

In Claude Code, compaction runs automatically near the limit, or you run it with a focus, such as /compact focus on the auth bug fix. Afterwards Claude Code re-reads up to five recently modified files; the context window guide lists what else survives. When you’re switching to unrelated work, /clear is cheaper, since compaction reads the whole conversation it summarizes.

The risk is losing a detail that matters later. Anthropic’s advice is to tune the summary prompt for recall first, then cut what’s superfluous.

Subagents

A subagent does its work in its own context window and returns only its conclusion. Anthropic notes that each subagent might use “tens of thousands of tokens or more” while returning “a condensed, distilled summary of its work (often 1,000-2,000 tokens)”. In Claude Code, test runs, log searches and documentation lookups are the usual candidates. Subagents save main-context tokens, not total tokens, since each one makes its own requests. Claude Code subagents covers configuration, including giving a subagent its own MCP servers so their tool definitions never load in the main session.

Load tool definitions on demand

Tool search keeps definitions deferred until the model searches for them. On the Claude API you mark tools with defer_loading: true and add a tool search tool; Claude Code does the equivalent for MCP tools by default, loading only tool names and server instructions at session start. MCP tool search covers both, and MCP vs Agent Skills explains the progressive disclosure skills use for the same reason.

Let code call the tools

When an agent chains many calls, every intermediate result passes through the context window. Anthropic’s programmatic tool calling lets Claude write a script that calls your tools inside a code execution container, so only what the script prints comes back. You opt a tool in with allowed_callers: ["code_execution_20260120"]. Anthropic’s code execution with MCP post applies the idea to MCP servers, and Cloudflare’s Code Mode turns MCP tools into a TypeScript API the model writes code against. Programmatic tool calling and Code Mode for MCP go into each. Either way, model-written code runs in a sandbox, which brings its own setup and security questions.

Structured notes and memory

Notes don’t shrink context by themselves. They make it safe to clear or compact, because the important state lives outside the window. Anthropic’s examples include a NOTES.md file and Claude playing Pokémon, which kept tallies like “for the last 1,234 steps I’ve been training my Pokémon in Route 1” and read them back after context resets.

The Claude API’s memory tool ({"type": "memory_20250818", "name": "memory"}) gives this a standard shape: Claude reads and writes files under /memories, and your application stores them wherever you choose. Claude Code’s auto memory keeps a MEMORY.md index whose first 200 lines or 25KB load into each session, with detail in separate topic files. For hand-written project instructions, CLAUDE.md vs AGENTS.md covers what belongs in the file that loads every time.

Where to start

Anthropic’s manage tool context page suggests an order for a high-volume agent: cache tool definitions from the start, add tool search at 10 or more tools, add context editing once conversations run long enough that early results stop mattering, and consider programmatic tool calling for repeated chains of small calls. Before any of that, remove what the agent doesn’t use. A tool that is never listed costs nothing and can’t distract the model. MCP vs CLI compares the context cost of both approaches.

How this relates to Toolstile

Toolstile is a managed MCP gateway, and it affects the tool-definition part of an agent’s context. Each connection’s tools appear to agents as <namespace>__<upstream name>, for example linear__get_issue, with upstream descriptions and schemas unchanged. Per-agent rules can allow, block or require approval for individual tools, and blocked tools are not listed to the agent, so blocking tools an agent doesn’t need also shrinks the tool list it loads. Of the built-in read-only tools (search_catalog, get_catalog_entry and get_my_access), get_my_access summarizes this agent’s configured access: each connection, whether a full-access rule applies (blocks still win) or which tools are granted, and which need approval. tools/list shows what is visible right now. Tool review hides new or changed tool definitions until someone accepts them, and every forwarded call is logged. Toolstile doesn’t edit tool results or manage the model’s context window; those techniques run in the client or the model API.