Skip to content
Swap Tools Mid-Chat on Claude Opus 5, Keep the Cache — ContentBuffer guide

Swap Tools Mid-Chat on Claude Opus 5, Keep the Cache

K
Kodetra Technologies··12 min read Advanced

Summary

Add or drop Claude Opus 5 tools between turns without invalidating your prompt cache.

Anthropic shipped Claude Opus 5 on July 24, 2026, and within days it took the top spot on the Artificial Analysis Intelligence Index and Agentic Index at the same $5/$25 per-million-token price as Opus 4.8. The headline was the intelligence jump, but the release also carried a quieter change that matters a lot if you build agents: a new beta called mid-conversation tool changes.

Here is the problem it solves. In a long agentic session you often want to change which tools the model can reach. You start an agent with read-only tools, then unlock write tools once it has passed a check. Or you hide ten rarely-used tools until the task actually needs them. The obvious way is to edit the tools array between turns. On the Claude API that is the single most expensive thing you can do to a cached conversation, because tools sits at the very front of the hashed request prefix. Change one byte there and you invalidate the prompt cache for the entire conversation behind it.

Mid-conversation tool changes fix that. You declare the full tool set once, then offer or withdraw individual tools with small tool_addition and tool_removal blocks placed inside a system message. The tools array never changes, so the cached prefix stays byte-identical and your next request still reads it from cache. This guide walks through the mechanics with runnable code, a real support-agent example, and the placement gotchas that trip people up.

Prerequisites

  • Python 3.9+ and an Anthropic API key exported as ANTHROPIC_API_KEY.
  • The Anthropic SDK version that supports the beta: pip install -U anthropic (1.50.0 or later).
  • Access to claude-opus-5 (available to all API customers, also on Amazon Bedrock and Google Cloud).
  • A working understanding of the tool-use loop: tool_use blocks from the model, tool_result blocks back from you.
  • Familiarity with prompt caching. If caching is new, the short version is below.

Why editing the tools array nukes your cache

Prompt caching hashes the request prefix in a fixed order: tools first, then system, then messages. A cache hit requires that prefix to match a recent request exactly, byte for byte, up to the cache breakpoint. Because tools comes first, any edit to it, even adding one tool at the end of the array, produces a different hash and misses the cache for everything after it.

On a conversation that has grown to tens of thousands of tokens, that means re-paying full input price for the whole history just to add or remove one tool. Cache reads are billed at roughly one tenth of the base input rate, so a cache miss on a 60K-token conversation is not a rounding error. Mid-conversation tool changes let you keep the toolset stable in the prefix and express the change as an appended block instead.

Prefix segmentPosition in hashEffect of editing it mid-session
toolsFirst (earliest)Invalidates cache for the entire conversation
system (top-level)SecondInvalidates system + all messages after it
messages (append only)LastOnly the new turn is processed as fresh input

The trick is to move the tool change from the tools segment (position one) into an appended messages entry (position three), where it costs you nothing but the new block.

Step 1: Set up the client and the beta header

Mid-conversation tool changes are gated behind the beta header mid-conversation-tool-changes-2026-07-01. With the Python SDK you pass it through the betas list on client.beta.messages.create.

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

MODEL = "claude-opus-5"
BETA = "mid-conversation-tool-changes-2026-07-01"

# A tiny sanity call so you know auth and the beta header work.
resp = client.beta.messages.create(
    model=MODEL,
    max_tokens=256,
    betas=[BETA],
    tools=[],
    messages=[{"role": "user", "content": "Reply with the single word: ready"}],
)
print(resp.content[0].text)

Expected output:

ready

One thing to budget for: on Opus 5, thinking is on by default. The model decides how much to think per turn, and max_tokens is a hard cap on thinking plus visible output combined. If you set max_tokens too low you can get truncated responses that used to be fine on Opus 4.8. Give agentic calls generous headroom (4K+).

Step 2: Remove a tool without touching the tools array

Declare every tool you might use up front in tools. To withdraw one from a certain point onward, append a system message whose content holds a tool_removal block. The block's tool field references a tool by name; it does not redefine it.

weather_tool = {
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "input_schema": {
        "type": "object",
        "properties": {"location": {"type": "string", "description": "City name"}},
        "required": ["location"],
    },
}

resp = client.beta.messages.create(
    model=MODEL,
    max_tokens=1024,
    betas=[BETA],
    # Full tool set declared once. This array never changes across turns.
    tools=[weather_tool],
    messages=[
        {"role": "user", "content": "Say OK."},
        {"role": "assistant", "content": "OK"},
        {"role": "user", "content": "What tools can you call now?"},
        # Withdraw get_weather from this point onward. Earlier turns stay
        # byte-identical, so the cached prefix still matches.
        {
            "role": "system",
            "content": [
                {"type": "tool_removal",
                 "tool": {"type": "tool_reference", "name": "get_weather"}},
            ],
        },
    ],
)
print(resp.content[0].text)

Representative output (the model no longer sees get_weather):

I don't currently have any tools available to call. A moment ago I could
check the weather, but that capability has been turned off for now.

The key detail: tools still contains exactly [weather_tool]. You changed availability without changing the array, so a cached prefix built on that array is untouched.

Step 3: Defer a tool and surface it later with tool_addition

Every tool in tools is offered to the model from turn one unless you mark it defer_loading: true. A deferred tool stays hidden until a tool_addition block surfaces it. This is how you hold back write or destructive tools until the agent earns them, while still declaring them in the stable prefix from the start.

delete_tool = {
    "name": "delete_record",
    "description": "Permanently delete a record by id.",
    "input_schema": {
        "type": "object",
        "properties": {"id": {"type": "string"}},
        "required": ["id"],
    },
    # Declared up front (so it is in the cached prefix) but withheld
    # from the model until we explicitly add it.
    "defer_loading": True,
}

messages = [
    {"role": "user", "content": "Find the duplicate record for user 42."},
    {"role": "assistant", "content": "Found duplicate record rec_88 for user 42."},
    {"role": "user", "content": "Good. You're cleared to remove it."},
    # Surface the deferred delete tool from here onward.
    {
        "role": "system",
        "content": [
            {"type": "text", "text": "Cleanup approved by operator."},
            {"type": "tool_addition",
             "tool": {"type": "tool_reference", "name": "delete_record"}},
        ],
    },
]

resp = client.beta.messages.create(
    model=MODEL, max_tokens=1024, betas=[BETA],
    tools=[delete_tool], messages=messages,
)
print(resp.stop_reason)               # -> "tool_use"
print([b.name for b in resp.content if b.type == "tool_use"])

Representative output:

tool_use
['delete_record']

Notice that a single system message mixed a plain text block with a tool_addition block. That is allowed, and it is a clean way to state the operator-level fact ("cleanup approved") and grant the capability in the same breath. tool_addition also re-offers a tool that an earlier tool_removal withdrew, so you can toggle a tool on and off across a session.

Step 4: Place the change correctly inside an agentic loop

Placement is strict, and getting it wrong returns a 400. A system message must immediately follow a user turn (a user turn carrying tool_result blocks counts) or an assistant turn that ends in a server tool result, and it must either end the messages array or be immediately followed by an assistant turn. It can never sit between an assistant tool_use block and the tool_result that answers it.

In a real loop that means: run the tool, append the tool_result in a user message, then append your system message with the tool change right after the results and before the next model turn.

def run_agent(client, tools, first_user_msg, tool_impls):
    messages = [{"role": "user", "content": first_user_msg}]
    unlocked = False

    while True:
        resp = client.beta.messages.create(
            model=MODEL, max_tokens=4096, betas=[BETA],
            tools=tools, messages=messages,
        )
        messages.append({"role": "assistant", "content": resp.content})

        if resp.stop_reason != "tool_use":
            return resp, messages

        # Execute every tool call and collect results.
        results = []
        for block in resp.content:
            if block.type != "tool_use":
                continue
            output = tool_impls[block.name](block.input)
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": str(output),
            })
        messages.append({"role": "user", "content": results})

        # Unlock write tools once the read phase produced a result,
        # placed right AFTER the tool_result user turn. This is legal.
        if not unlocked and any("verified" in r["content"] for r in results):
            messages.append({
                "role": "system",
                "content": [
                    {"type": "text", "text": "Read checks passed. Write tools unlocked."},
                    {"type": "tool_addition",
                     "tool": {"type": "tool_reference", "name": "apply_fix"}},
                ],
            })
            unlocked = True

The comment matters: the system message lands after the user turn that delivered the tool results, which is exactly where the placement rule allows it. Drop it one line earlier, between the tool_use and its tool_result, and the API rejects the request.

Step 5: Reference MCP tools individually or by toolset

If your tools come from an MCP connector rather than inline definitions, you reference them with different block shapes. Use mcp_tool_reference to target one tool, or mcp_toolset_reference to add or remove a whole server's toolset at once.

# Withdraw a single MCP tool
{"type": "tool_removal",
 "tool": {"type": "mcp_tool_reference",
          "server_name": "github", "name": "create_issue"}}

# Add back every tool from an MCP server in one block
{"type": "tool_addition",
 "tool": {"type": "mcp_toolset_reference", "server_name": "github"}}

As with inline tools, the name you reference must be declared in the request; referencing a tool that is not in tools (or an MCP server not attached to the request) returns a 400 error.

Worked example: a support agent that earns write access

Here is the pattern end to end. A support agent starts with two read tools, lookup_account and read_ticket, and one deferred write tool, issue_refund. The agent must read the account and confirm eligibility before it can touch money. Only after the read tools return a verified-eligible result does the app surface issue_refund with a tool_addition.

import anthropic

client = anthropic.Anthropic()
MODEL, BETA = "claude-opus-5", "mid-conversation-tool-changes-2026-07-01"

def schema(**props):
    return {"type": "object", "properties": props, "required": list(props)}

tools = [
    {"name": "lookup_account", "description": "Look up an account by email.",
     "input_schema": schema(email={"type": "string"})},
    {"name": "read_ticket", "description": "Read a support ticket by id.",
     "input_schema": schema(ticket_id={"type": "string"})},
    {"name": "issue_refund", "description": "Issue a refund to an account.",
     "input_schema": schema(account_id={"type": "string"},
                            amount_cents={"type": "integer"}),
     "defer_loading": True},          # hidden until unlocked
]

DB = {"amy@example.com": {"account_id": "acct_7", "eligible": True, "plan": "pro"}}
TICKETS = {"T-101": "Double charged on July invoice, requesting refund."}

def impl_lookup(inp):
    acct = DB.get(inp["email"], {})
    tag = "verified-eligible" if acct.get("eligible") else "not-eligible"
    return {"account": acct, "status": tag}

def impl_read(inp):   return {"body": TICKETS.get(inp["ticket_id"], "not found")}
def impl_refund(inp): return {"refund_id": "re_555", "status": "succeeded", **inp}

IMPLS = {"lookup_account": impl_lookup, "read_ticket": impl_read,
         "issue_refund": impl_refund}

messages = [{"role": "user", "content":
    "Ticket T-101 from amy@example.com wants a refund for a double charge. "
    "Check eligibility, then refund the duplicate $20 charge if allowed."}]
unlocked = False

while True:
    resp = client.beta.messages.create(
        model=MODEL, max_tokens=4096, betas=[BETA],
        tools=tools, messages=messages,
    )
    messages.append({"role": "assistant", "content": resp.content})
    if resp.stop_reason != "tool_use":
        print("FINAL:", resp.content[-1].text)
        print("cache_read_input_tokens:", resp.usage.cache_read_input_tokens)
        break

    results = []
    for b in resp.content:
        if b.type == "tool_use":
            out = IMPLS[b.name](b.input)
            results.append({"type": "tool_result", "tool_use_id": b.id,
                            "content": str(out)})
    messages.append({"role": "user", "content": results})

    if not unlocked and any("verified-eligible" in r["content"] for r in results):
        messages.append({"role": "system", "content": [
            {"type": "text", "text": "Eligibility verified. Refund tool unlocked."},
            {"type": "tool_addition",
             "tool": {"type": "tool_reference", "name": "issue_refund"}},
        ]})
        unlocked = True

A representative run of the loop:

# turn 1: model calls lookup_account + read_ticket  (issue_refund not visible yet)
# tool results include status: "verified-eligible"
# app appends system message: tool_addition for issue_refund
# turn 2: model now sees issue_refund and calls it with amount_cents=2000
# turn 3: model summarizes

FINAL: Refund re_555 for $20.00 issued to acct_7. The duplicate July charge
has been reversed; Amy should see it in 3-5 business days.
cache_read_input_tokens: 3187

Because the tools array held all three tools from the first request, the growing conversation kept hitting the cache on every turn, and the issue_refund unlock added a small system block instead of rebuilding the prefix. The write tool was structurally impossible for the model to call until the app decided to surface it, which is a much stronger guarantee than a prompt asking it to please not refund yet.

Common pitfalls and gotchas

1. Forgetting the beta header. Without betas=["mid-conversation-tool-changes-2026-07-01"], the API does not recognize tool_addition or tool_removal and rejects the request. It is easy to lose the header when you refactor a working non-tool-change call.

2. Referencing a tool that is not declared. The reference blocks point at tools in the request's tools array (or an attached MCP server). A typo in the name, or a tool you forgot to declare because you planned to add it later, returns a 400. Declare everything up front, even deferred tools.

3. Illegal placement. The system message cannot be the first entry in messages, and it cannot sit between a tool_use block and its matching tool_result. In an agentic loop, always append it after the user turn that carries the tool results, not before the results arrive.

4. Editing a system message you already sent. Once a mid-conversation system message is in the history it is part of the stable prefix. Rewriting or deleting it invalidates the cache from that point forward, which defeats the whole purpose. If the instruction needs to change, append a new system message instead.

5. Expecting cache savings without enabling caching. Caching is opt-in. If your request has no cache_control (automatic or an explicit breakpoint), nothing is cached and there is no prefix to protect. Mid-conversation tool changes preserve a cache; they do not create one.

6. Putting untrusted content in the system message. Claude treats system content as operator instructions. Never drop raw tool output, retrieved documents, or web text into a tool_addition message's text block; keep that data in tool_result blocks. Giving external text operator authority is a prompt-injection foothold.

7. Reaching for it on Sonnet 5. Mid-conversation tool changes are available on Claude Fable 5, Mythos 5, Opus 4.8, and Opus 5, but not on Sonnet 5. On Sonnet 5 you are back to editing the top-level tools array.

8. Under-budgeting max_tokens on Opus 5. Thinking is on by default and shares the max_tokens budget with the visible response. Agentic turns that unlock a powerful tool are exactly the turns the model wants to think hardest about, so keep max_tokens comfortably above your expected output size.

Quick reference

ElementValue / rule
Modelclaude-opus-5 (also Fable 5, Mythos 5, Opus 4.8)
Beta headermid-conversation-tool-changes-2026-07-01
SDK callclient.beta.messages.create(..., betas=[BETA])
Withdraw a tooltool_removal block in a role:system message
Offer a tooltool_addition block in a role:system message
Hold a tool back at startdeclare it with "defer_loading": true
Inline tool ref{"type":"tool_reference","name":"..."}
MCP single tool{"type":"mcp_tool_reference","server_name":..,"name":..}
MCP whole server{"type":"mcp_toolset_reference","server_name":..}
Placementafter a user/tool_result turn; never between tool_use and its result
Undeclared tool ref400 error
Not supported onClaude Sonnet 5

Next steps

  • Add cache_control to your requests and watch usage.cache_read_input_tokens climb across turns to confirm the cache is holding.
  • Combine tool changes with mid-conversation system messages (generally available, no beta header) to switch persona or policy in the same session.
  • Use defer_loading for a large tool catalog: declare all of them, surface only the handful a task needs, and keep the model's tool-selection space small.
  • Read Anthropic's mid-conversation system messages and tool changes docs and the what's new in Opus 5 page for the full behavior list.
  • Wire the unlock signal to a real gate (a policy check, a human approval webhook) instead of a substring match, so capability grants map to your actual authorization logic.

Mid-conversation tool changes turn tool availability from a fixed, cache-breaking property of the whole conversation into a cheap, per-turn decision. On Opus 5, that means you can build agents that visibly earn their more powerful tools, keep the prompt cache intact the whole way, and pay for the new capability with a few tokens instead of a full prefix rebuild.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get