Agentic Integration with the Claude API, Part 3: Server-Side Tools and API Version 2026-10-21

On this page

Part 1 wrote the tool-use loop by hand and Part 2 handed it to the Claude Agent SDK. In both, every tool ran in our own process, so every call passed through our code before anything happened. This part adds tools that do not: web search and web fetch, which Anthropic runs inside the Messages request. The prescription assistant gets a new job, checking whether a medicines regulator has published a safety communication about a prescribed medicine, and the loop has to change in a few specific places to cope with tools it cannot gate.

The week also brought a new API version. On 21 October Anthropic released API version 2026-10-21 together with new major versions of every SDK, including anthropic 2.0.0 for Python. The sample for this part uses anthropic 2.3.0, so the first job is to move the Part 1 code across and see what breaks.

Your process runs the tool-use loop, client tools, approval gate and audit; one Claude API request runs Claude Opus 5.5 and a server-side loop for web search and web fetch, restricted to medicines regulators
Two loops in one request: yours, for client tools, and the API’s, for server tools.

Moving to anthropic 2.x and API version 2026-10-21

Python SDK 2.0.0 is the first release that sends anthropic-version: 2026-10-21; staying on 1.x keeps 2023-06-01. The migration guide lists three request rules for the Messages API and several SDK changes. Here is what each one meant for the Part 1 code:

ChangeWhat it doesEffect on this agent
temperature, top_p, top_k removedAny request that sends them returns a 400, even at default valuesNone: Part 1 never sent them
document blocks in assistant messages, citations on user text blocksBoth return a 400None: neither is sent
API key sent as Authorization: BearerReplaces X-Api-Key for the SDK’s key argument and ANTHROPIC_API_KEYCheck gateways, proxies and log filters that look for X-Api-Key
MessageParam becomes a union of role typesCalling MessageParam(...) raises TypeError; dict literals still workNone: messages are plain dictionaries
One credential per clientPassing two of api_key, auth_token and similar raises ValueErrorNone: one key from the environment

The loop itself did not change for the upgrade. The wire test from Part 1, which sends a request through the real SDK client to a mock HTTP transport, now asserts the new version header and the new authorisation header, and that no sampling parameter reaches the body:

Python10 lines
client = anthropic.Anthropic(api_key="test-key", default_headers={"anthropic-workspace-id": "wrkspc_test"},
                             http_client=httpx.Client(transport=httpx.MockTransport(handler)))
result = run(client, RxService.with_sample_data(), "Status of RX-1002?")
req = seen[0]
body = json.loads(req.content)
assert req.headers["anthropic-version"] == "2026-10-21"
assert req.headers["authorization"] == "Bearer test-key" and "x-api-key" not in req.headers
assert req.headers["anthropic-workspace-id"] == "wrkspc_test"
# removed in 2026-10-21: sending any of them is a 400, even at default values
assert not {"temperature", "top_p", "top_k"} & body.keys()

Run live against Claude Opus 5.5 with only the client tools, the upgraded agent answered the Part 1 status question with the same two parallel lookups, for $0.0134 against $0.0125 on anthropic 1.13.0.

Terminal output: the client-tools-only baseline on anthropic 2.3.0 answers the RX-1002 lookup for $0.0134
The Part 1 question on anthropic 2.3.0 with server tools switched off.
⚠️
THE BEARER CHANGE IS THE ONE THAT BITES

If your traffic to the Claude API goes through an API gateway, an egress proxy or a log scrubber, check every rule that reads, strips or masks X-Api-Key. After the upgrade the key travels in Authorization, which a scrubber written only for the old header will not mask. The migration guide shows an HTTP client hook that keeps sending X-Api-Key if you need time to change the gateway.

Tools that run on Anthropic’s side

A server tool is declared in the same tools array as a client tool, but with a type instead of an input schema. When Claude calls it, the API runs it during the request and puts both the call and its result in the response: a server_tool_use block with an ID that starts srvtoolu_, followed by a result block such as web_search_tool_result. You do not send a tool_result for it. From the loop’s point of view, the search has already happened by the time the response arrives.

That is the property that shapes everything else. In Part 1 a state-changing call waited for a person; a server tool call cannot wait for anyone, because there is no point in your code between Claude deciding to search and the search running. Whatever you want to control has to be expressed in the tool definition before the request is sent.

Locking server tools down in the definition

The assistant gets two server tools, both limited to the Irish and European medicines regulators:

Python25 lines
REGULATOR_DOMAINS: tuple[str, ...] = ("hpra.ie", "ema.europa.eu")

def server_tool_definitions(policy: ServerToolPolicy) -> list[dict[str, Any]]:
    domains = list(policy.domains)
    return [
        {
            "type": "web_search_20260318",
            "name": "web_search",
            "max_uses": policy.max_searches,          # 3; billed per search
            "allowed_domains": domains,
            "allowed_callers": ["direct"],            # no calls from a code-execution container
        },
        {
            "type": "web_fetch_20260318",
            "name": "web_fetch",
            "max_uses": policy.max_fetches,           # 2; tokens only
            "allowed_domains": domains,
            "allowed_callers": ["direct"],
            "url_sources": {"user_input": {"type": "all"},
                            "client_tool_results": {"type": "none"},   # URLs in our own data are not fetchable
                            "server_tool_results": {"type": "all"}},
            "citations": {"enabled": True},
            "max_content_tokens": policy.fetch_max_tokens,  # 6,000
        },
    ]
  • allowed_domains is the closest thing a server tool has to an approval gate. Subdomains are included, so hpra.ie also covers assets.hpra.ie, where the live runs found product documents. Web search accepts paths in the list; web fetch matches on the domain only.
  • max_uses caps calls per request. Failed calls count. With web search billed at $10 per 1,000 searches, it is also a cost control.
  • allowed_callers: ["direct"] matters for regulated data. From the 20260209 versions onwards, the web tools default to being called from inside a code-execution container so that Claude can filter results with code before they enter the context. Anthropic’s documentation lists that dynamic filtering as not eligible for zero data retention or HIPAA, and documents ["direct"] as the way to use the newer versions without it.
  • url_sources decides where fetchable URLs may come from. Web fetch only fetches URLs that already appeared in the conversation; turning off client tool results means a URL that turns up in data from our own systems cannot be fetched, which closes one route for data to leave in a query string.

The first live run failed before Claude saw the question. The original definition set user_location with the country IE to bias results towards Ireland, and the API rejected it:

Terminal output: the API rejects web_search_20260318 with a 400 because country code IE is not supported in user_location
A 400 at request validation: not every country code is accepted in user_location.

The domain list already confines results to Irish and EU regulators, so the sample drops user_location rather than pretending to be somewhere else. Test the exact location you plan to send before you rely on it.

⚖️
A SEARCH QUERY IS DATA LEAVING YOUR BOUNDARY

Search queries and fetched URLs go to third parties, and website publishers may keep URL parameters even when the API itself retains nothing. Anthropic’s documentation lists web fetch as not eligible for HIPAA and warns about exfiltration wherever Claude handles untrusted input next to sensitive data. In a clinical system, treat every server tool query as an external disclosure: search for medicines, never for patients; restrict domains; exclude your own data as a URL source; and audit what was actually sent.

What changes in the loop

Most of the Part 1 loop carries over unchanged. It already appended every response exactly as received, which server tools need: search results carry an encrypted_content field and citations an encrypted_index, and the API rejects a later request if either is missing or modified. Four things are new.

Resuming a paused turn

The API runs server tools in its own loop and may stop a long turn with stop_reason: "pause_turn". You continue by sending the paused response back as an assistant message, with the same tools and no new user message, and the API carries on. Keep every paused response in the history in order, and cap the number of resumptions like any retry:

Python10 lines
if response.stop_reason in ("tool_use", "pause_turn"):
    # Append the response unchanged: thinking blocks, encrypted search content and
    # citation indexes must go back exactly as received.
    messages.append({"role": "assistant", "content": response.content})
    if response.stop_reason == "pause_turn":
        # The server paused a long turn. Resume with the same tools and no new user message.
        pauses += 1
        if pauses > cfg.max_pause_continuations:
            return AgentResult("pause_limit", _text(response.content), turns, messages)
        continue

Server and client calls in the same turn

When Claude asks for a server tool and a client tool in the same turn, the API does not run the server tool yet. The response stops with tool_use, the server_tool_use block has no result block, and the API runs it on the next request, after you send the client results. That next message must contain only tool_result blocks. The Part 1 loop already sent exactly that, so it needed no change; the sample only records the server call as deferred so the audit trail is complete. The live web fetch run below hit this path.

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FBF1EB','primaryTextColor':'#3D3929','primaryBorderColor':'#CC785C','lineColor':'#3D3929','actorBkg':'#FBF1EB','actorBorder':'#CC785C','actorTextColor':'#3D3929','signalColor':'#CC785C','signalTextColor':'#1F1E1D','noteBkgColor':'#FFF8F3','noteBorderColor':'#CC785C','noteTextColor':'#3D3929'}}}%%
sequenceDiagram
    participant L as Your loop
    participant API as Claude API
    participant R as hpra.ie
    L->>API: messages + client and server tools
    API-->>L: tool_use get_prescription, server_tool_use web_fetch (no result)
    Note over L: run get_prescription, record web_fetch as deferred
    L->>API: user message with tool_result blocks only
    API->>R: fetch the page
    R-->>API: page content
    API-->>L: web_fetch_tool_result, then the answer

Auditing calls you could not stop

Because a server call is only visible after it ran, the audit has to work backwards. The loop pairs each server_tool_use block with its result, logs the query or URL and the outcome, and screens the input for record identifiers. A match cannot undo the disclosure, but it stops the task so that nothing further is sent, and it raises an error-level event for someone to follow up:

Python28 lines
IDENTIFIER = re.compile(r"\b(?:RX|P)-\d+\b", re.IGNORECASE)

def _server_calls(content: list[Any]) -> list[ServerCall]:
    """Pair each server_tool_use block with its result block, if the API has run it yet."""
    results = {b.tool_use_id: b for b in content if b.type in ("web_search_tool_result", "web_fetch_tool_result")}
    calls = []
    for b in content:
        if b.type != "server_tool_use":
            continue
        r = results.get(b.id)
        if r is None:
            outcome = "deferred"
        elif isinstance(r.content, list):
            outcome = f"results:{len(r.content)}"
        elif getattr(r.content, "error_code", None):
            outcome = f"error:{r.content.error_code}"     # errors arrive with HTTP 200
        else:
            outcome = "fetched"
        inp = dict(b.input or {})
        flagged = any(isinstance(v, str) and IDENTIFIER.search(v) for v in inp.values())
        calls.append(ServerCall(b.id, b.name, inp, outcome, flagged))
    return calls

# in run(), after every response:
turn.server_calls = _server_calls(response.content)
if any(sc.flagged for sc in turn.server_calls):
    log.error(json.dumps({"event": "identifier_sent_to_server_tool", "turn": index}))
    return AgentResult("policy_stop", "", turns, messages)

The pattern here matches the synthetic identifiers in the sample. A real deployment would screen for its own identifier formats and for names, and would treat a hit as an incident, not a log line. The first line of defence is still the system prompt, which tells Claude to search with the medicine’s generic name only.

Citations and cost

Answers that draw on search results come with citations: each cited span is a separate text block carrying a citations list with the URL and title. Part 1 joined text blocks with newlines, which was harmless when there was one block. With citations, a single sentence arrives in several blocks, and the first live answer came out with quotes broken onto lines of their own. The fix is to join them with nothing in between and collect the cited URLs separately.

Usage gains a server_tool_use object with web_search_requests and web_fetch_requests. Searches cost $10 per 1,000 on top of tokens; fetches cost only the tokens of the page. The cost function adds one cent per search to the token cost from Part 1.

Live runs

All runs used Claude Opus 5.5 at medium effort on the Claude API, from Azure Cloud Shell. The main question was whether there is any current safety communication about the medicine on RX-1003. Claude looked the prescription up, searched the two regulators twice, and reported what it found and what it had not checked:

Terminal output: Claude looks up RX-1003, then runs two web searches restricted to HPRA and EMA and cites regulator documents
The safety question: one client lookup, two regulator searches, cited sources and an explicit list of what was not checked.

The next run tried to get identifiers into a search by asking for regulator pages that mention P-002 or RX-1003. Claude declined to search for the identifiers, looked up the prescription, and searched for the medicine instead. The identifier screen therefore never fired live; the offline tests show it stopping the task when a query contains an identifier.

Terminal output: asked to search regulators for patient and prescription identifiers, Claude searches for the medicine name only
Asked to search for identifiers, Claude searched for the medicine.

The last run gave Claude an HPRA page to read. Claude asked for the page and the prescription in the same turn, so the fetch was deferred until our tool result went back, exactly as the documentation describes. The page builds its content with JavaScript, which web fetch does not run, so only the title came back. Claude said it could not tell whether the withdrawal applied and changed nothing.

Terminal output: web_fetch is requested in the same turn as get_prescription, shown as deferred, and runs after the tool result is sent
A mixed turn: web_fetch deferred until the client result was sent, then a page with no usable content.
RunSearchesFetchesInput tokens (cache write / read)Cost
Client tools only (anthropic 2.3.0)001,617 / 1,271$0.0134
Safety question, first run2021,555 / 24,681$0.1502
Safety question, repeated204,815 / 38,486$0.0703
Identifiers requested1014,213 / 11,292$0.0987
HPRA page given0113,920 / 5,398$0.0854

The searches themselves cost two cents; the search results did the rest. Each search added several thousand tokens of results to the context, which made the first safety question about eleven times the cost of a client-only lookup. Repeating it was cheaper because the identical searches returned content that was already in the cache. The answers were not identical between the two runs: different results came back and Claude cited different documents. For a safety check, that variability belongs in the answer, and Claude did say each time which regulators it had and had not checked.

Why code execution is not in this agent

Code execution is the third widely used server tool: a sandboxed container with no internet access where Claude can run Python and shell commands. Without the web tools it is billed by container time, at $0.05 per hour after 1,550 free hours a month per organisation and a five-minute minimum per execution, and containers live for 30 days and can be reused across requests. With the 20260209 or later web tools in the request it costs nothing extra, because it is what dynamic filtering runs on.

This assistant has nothing to compute, and the one thing code execution would add, filtering search results in a container, is the behaviour allowed_callers: ["direct"] switches off for data-retention reasons. The tool earns its place when the work is computation over data you are allowed to put in Anthropic’s sandbox; it is not a default to add because it is available.

Matrix comparing client tools and server tools: who runs them, when you see the call, approval, data that leaves, cost and mixed turns
Where each control lives for client and server tools.

What comes next

Part 4, on 3 November, sets the hand-written loop and the Agent SDK side by side on the same integration, with the versions current then, to answer the question this series has been circling: which one to choose, and when.

📝
HOW THIS WAS CHECKED

The sample was tested with Python 3.12, anthropic 2.3.0 and pytest 8.3.3: 18 offline tests pass, 17 against a scripted fake of the Messages API, including pause_turn resumption, deferred server calls, the identifier screen, citations and cost, and one that sends a request through the real SDK client to a mock HTTP transport to check the 2026-10-21 headers and body. The live runs used Claude Opus 5.5 on the Claude API from Azure Cloud Shell; outputs and screenshots are from those runs, with request IDs shortened. Costs are calculated from the API’s usage fields at list prices, including $10 per 1,000 searches. Behaviour and limits are from Anthropic’s documentation on the 2026-10-21 migration, server tools, web search, web fetch and code execution, and from the SDK 2.3.0 source. All prescription data is synthetic.

Key takeaways

  • Moving to anthropic 2.x sends API version 2026-10-21: sampling parameters return a 400, and the key moves to Authorization: Bearer.
  • Server tools run inside the request; you see the call after it ran, so the controls belong in the tool definition.
  • Restrict domains, cap max_uses, set allowed_callers: ["direct"] and exclude your own data as a URL source.
  • Handle pause_turn, send only tool_result blocks after a mixed turn, and append every response unchanged.
  • Audit every server query after the fact, and budget for search results as input tokens, not just the per-search fee.

What would you allow a clinical agent to search for, and on which domains? Tell me in the comments.

Glossary

Server tool
A tool that Anthropic runs during the Messages request, such as web search, web fetch or code execution.
Client tool
A tool your application defines and runs, returning a tool_result.
server_tool_use
The response block that records a server tool call; its ID starts with srvtoolu_.
pause_turn
A stop reason meaning the API paused a long server-side turn; send the response back to continue.
Deferred server call
A server tool call made in the same turn as a client tool; it runs after you return the client results.
allowed_domains
The list of domains a web tool may search or fetch; subdomains are included.
allowed_callers
Who may call a tool: Claude directly, code running in a code-execution container, or both.
Dynamic filtering
Filtering web results with code in a container before they enter the context, used by the newer web tool versions.
url_sources
Which parts of the conversation may supply URLs that web fetch is allowed to fetch.
Citations
References attached to cited text, giving the source URL and title.
API version
The anthropic-version header value that fixes request and response rules; 2026-10-21 is the newest.
Zero data retention (ZDR)
An arrangement under which the API does not keep request data; some tools and modes are not eligible.

References & Further Reading


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.