Follow Discord
Sweep 22 Oct 2026 · 21:04Z Build v2.1.309 528 read Stable v2.1.308 Latest v2.1.309 Next v2.1.309 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · api

One read of Claude Developer Platformapi-20261021T193714Z

242 pages moved out of 808 read.

Pages moved 242 significant first
Pages read 808 in this capture
Captured 19:37 UTC
Corpus hash 851c97e9b6f0 corpus-hash

What this read moved

26-50 of 242, page 2 of 10

This capture is too large to show at once. Changes 26-50 of 242 are below, significant first; the rest are on the following screens.

agents-and-tools/tool-use/browser-use-sdk Changed · +24 / -24 lines

from line 4
44description: Run the browser use tool or the computer use tool from the Python or TypeScript SDK. The SDK runs the loop and the checks you configure, and you supply the browser or the desktop.
55---
66 
7With the browser and computer toolsets in the Python and TypeScript SDKs, you can build an agent that works in a web browser or on a desktop. It can use applications with no programmatic interface. Through the [browser use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool), Claude navigates, reads, and interacts with webpages. Through the [computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool), Claude sees a desktop in screenshots and uses the mouse and keyboard.
7With the browser and computer toolsets in the Python and TypeScript SDKs, you can build an agent that works in a web browser or on a desktop. It can use applications with no programmatic interface. Through the [browser use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool), Claude navigates, reads, and interacts with webpages. Through the [computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool), Claude receives screenshots of a desktop and uses the mouse and keyboard.
88 
99The SDK connects Claude to your browser or desktop. It runs the checks you configure, such as a URL policy for `navigate` or an approval callback. It sends each call that passes to your driver and builds the `tool_result` from what the driver returns. The [tool runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner) can run the agentic loop for you.
1010 
from line 89
8989 </Card>
9090</CardGroup>
9191 
92Our partners also publish code on GitHub: the [Browser Use quickstart](https://github.com/browser-use/browser-use/tree/main/examples/integrations/toolsets-for-claude), the [Browserbase toolset](https://github.com/browserbase/claude-cua-toolset), and the [E2B example](https://github.com/e2b-dev/e2b-cookbook/tree/main/examples/anthropic-computer-use-orangehrm-js).
92Partner code is also available on GitHub: the [Browser Use quickstart](https://github.com/browser-use/browser-use/tree/main/examples/integrations/toolsets-for-claude), the [Browserbase toolset](https://github.com/browserbase/claude-cua-toolset), and the [E2B example](https://github.com/e2b-dev/e2b-cookbook/tree/main/examples/anthropic-computer-use-orangehrm-js).
9393 
9494<Warning>
9595 Do these two things before you run a driver against anything but a throwaway browser:
from line 173
173173 
174174A driver is your subclass of `BetaAbstractBrowserToolset20260801`. In it, override the members your browser supports. A member you don't implement is sent to the API as disabled. If Claude calls it anyway, the SDK returns an error, and the run continues. Overriding `execute` changes which members are sent as disabled ([Add before and after hooks](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#add-before-and-after-hooks)). Each member receives the call context and the member's input as a typed object, such as `BetaBrowserNavigateInput`. The input types come from `anthropic.types.beta` (typescript: `@anthropic-ai/sdk/resources/beta`). [Member tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#member-tools) lists each input's fields.
175175 
176In TypeScript, write members as methods, not arrow-function fields, because the SDK finds them on the prototype. Spell the `type` member `type_` in TypeScript. In Python, it's `type`.
176In TypeScript, spell the `type` member `type_`, and write members as methods, not arrow-function fields, because the SDK finds them on the prototype.
177177 
178178### Return results
179179 
from line 191
191191 
192192The SDK calls `_browser_state` (typescript: `browserState`) after each call that returns a result, including refused and failed calls. Return every open tab, and what changed since the last report:
193193 
194* Opened tabs and download events.
195* A `BetaNavigationRefused` for each navigation your [request hook](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#intercept-requests-in-the-driver) blocked.
196* A `BetaDialogDismissed` for each native dialog your driver dismissed.
194* Opened tabs and download events
195* A `BetaNavigationRefused` for each navigation your [request hook](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#intercept-requests-in-the-driver) blocked
196* A `BetaDialogDismissed` for each native dialog your driver dismissed
197197 
198Put all of these in `state_changes`. In Python, `BetaNavigationRefused()` and `BetaDialogDismissed(kind=..., message=...)` come from `anthropic.tools.browser`. In TypeScript, they're `{ type: "navigation_refused" }` and `{ type: "dialog_dismissed", kind, message }`.
198Put all of these in `state_changes`. A refused navigation is `anthropic.tools.browser.BetaNavigationRefused()` (typescript: `{ type: "navigation_refused" }`), and a dismissed dialog is `anthropic.tools.browser.BetaDialogDismissed(kind=..., message=...)` (typescript: `{ type: "dialog_dismissed", kind, message }`).
199199 
200200The last two aren't API state changes. The SDK reports them to Claude as text outside the `browser_state` block: one line for all refused navigations, which doesn't include a URL, and a line for each of the first three dismissed dialogs, then a count of any others.
201201 
202202When any tab is open, exactly one must be active. Every member that takes a `tab_id` must act on the tab it names. The API's limits on the report are listed under [Track tabs with `browser_state`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#track-tabs-and-page-state).
203203 
204Claude reads each tab's URL, each download's URL, and the URL that your `navigate` returns, as your driver wrote them. The SDK doesn't parse these URLs. It turns line breaks and other control characters into spaces, trims the ends, and cuts each URL at 4,096 characters. So a `data:` URL's contents, a `file:` URL's path, and a user name or password in a URL all reach Claude.
204Claude reads each tab's URL, each download's URL, and the URL that your `navigate` returns, as your driver wrote them. The SDK doesn't parse these URLs. It turns line breaks and other control characters into spaces, trims the ends, and cuts each URL at 4,096 characters. So a `data:` URL's contents, a `file:` URL's path, and a username or password in a URL all reach Claude.
205205 
206206### Handle errors
207207 
208| Raised by a member or the SDK | Claude reads | The run |
209| ----------------------------- | ------------------------------------------------------------------------------------ | --------- |
210| `ToolError` | Its message, as an error result | Continues |
211| `ToolsetUsageError` | Nothing | Stops |
212| Any other exception | `ClassName: message` in Python or `Error: message` in TypeScript, as an error result | Continues |
208| Raised by a member or the SDK | Claude reads | The run |
209| ----------------------------- | ----------------------------------------------------------------------- | --------- |
210| `ToolError` | Its message, as an error result | Continues |
211| `ToolsetUsageError` | Nothing | Stops |
212| Any other exception | `ClassName: message` (typescript: `Error: message`), as an error result | Continues |
213213 
214214The SDK raises `ToolsetUsageError` for a configuration error, a misuse of the SDK during a call, or a call after `close`. It also raises one when `_browser_state` (typescript: `browserState`) raises any exception, even a `ToolError`. The tool runner and `tool_result` (typescript: `toolResult`) don't catch it, so it reaches their caller.
215215 
from line 227
227227 
228228* **The checks still run first:** The SDK calls your URL policy, your file policy, and `confirm` before a call runs. With early start, it can call `confirm` while the response is still streaming.
229229* **Calls still run one at a time:** A toolset runs its calls in the order Claude wrote them. A failed call still stops that toolset's later calls in the turn.
230* **A call that has started can't be taken back:** If the response is then cut off, for example at `max_tokens`, or your loop stops early, the action still happens, and Claude never reads its result.
230* **A call that has started can't be taken back:** If the response is then cut off, for example at `max_tokens`, or your loop stops early, the action still occurs, and Claude never reads its result.
231231 
232232### Run without the tool runner
233233 
234Pass the instance in `tools` (`browser.toJSON()` in TypeScript), and answer each member call with `tool_result` (typescript: `toolResult`). The browser use tool requires you to stop at the first failed call ([Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#batch-actions)).
234Pass `browser` (typescript: `browser.toJSON()`) in `tools`, and answer each member call with `tool_result` (typescript: `toolResult`). The browser use tool requires you to stop at the first failed call ([Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#batch-actions)).
235235 
236236This loop uses `MyBrowser` and the URL policy from the [advanced example](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#quick-start). After a failed call, it answers the turn's later calls without running them:
237237 
from line 567
567567 
568568## Run the toolset safely
569569 
570Claude's next action depends on the pages it reads. A page, or text injected into one, can try to reach internal services or pull files off the host. It can also try to trigger actions with real effects. Before you run a driver against anything but a throwaway browser, take these six steps:
570Claude's next action depends on the pages it reads. A page, or text injected into one, can attempt to reach internal services or pull files off the host. It can also attempt to trigger actions with real effects. Before you run a driver against anything but a throwaway browser, take these six steps:
571571 
5725721. [Write a URL policy](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#write-a-url-policy) that refuses every `navigate` URL the task doesn't need.
5735732. [Intercept requests in the driver](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#intercept-requests-in-the-driver), and check each request with the same rules.
from line 587
587587<Warning>
588588 Without a URL policy, the SDK checks no URL, and the API doesn't filter the URLs Claude opens. Even with a policy, a link Claude clicks or a redirect can take the browser to loopback (`localhost`, `127.0.0.1`), to link-local addresses such as the cloud metadata address `169.254.169.254`, and to private network ranges. [Egress rules on the container](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#put-egress-policy-on-the-container) can block the link-local and private addresses. Rules enforced outside the container can't block loopback.
589589 
590 The SDK doesn't check a URL's scheme, so your driver must refuse every scheme it doesn't mean to open, such as `javascript:`, `view-source:`, `data:`, and `file:`. Most drivers need only `http` and `https`. The example policy below allows only `http` and `https` URLs, plus `about:blank`.
590 The SDK doesn't check a URL's scheme, so your driver must refuse every scheme it doesn't mean to open, such as `javascript:`, `view-source:`, `data:`, and `file:`. Most drivers need only `http` and `https`. The example policy later in this section allows only `http` and `https` URLs, plus `about:blank`.
591591 
592592 A `file:` URL lets Claude read files on the browser host. A `javascript:` URL runs script in the current page, even when `javascript_exec` is off. Egress rules don't stop either one.
593593</Warning>
from line 676
676676 
677677### Intercept requests in the driver
678678 
679The URL policy judges only the URL in a `navigate` call. A link Claude clicks, a form it submits, a redirect, or an image or script on an allowed page can still reach a host the policy would refuse. Use [egress rules](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#put-egress-policy-on-the-container) to block those hosts.
679The URL policy checks only the URL in a `navigate` call. A link Claude clicks, a form it submits, a redirect, or an image or script on an allowed page can still reach a host the policy would refuse. Use [egress rules](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#put-egress-policy-on-the-container) to block those hosts.
680680 
681681A driver with request interception can also check those requests in its request hook, the function your automation library calls before each request. Call the function that your policy uses, so that you write the rules once:
682682 
from line 868
868868 
869869Each call to `make_confirm()` (typescript: `makeConfirm()`) returns a callable with no approvals. Call it once for each toolset, and give each user their own toolset.
870870 
871An approval covers the page as the last state report showed it, and the page can change before the call runs. Purchases, sent messages, and accepted terms happen through ordinary members such as `left_click` and `type`, so `confirm` can't pick them out by name. To have a person approve them, ask about those members too.
871An approval covers the page as the last state report showed it, and the page can change before the call runs. Purchases, sent messages, and accepted terms go through ordinary members such as `left_click` and `type`, so `confirm` can't pick them out by name. To have a person approve them, ask about those members too.
872872 
873873Don't enable `javascript_exec` unless [egress rules](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#put-egress-policy-on-the-container) limit the browser's outbound connections to the hosts the task needs. A script can send the page's content to any address that the browser can reach.
874874 
from line 899
899899 
900900The shipped path checks don't protect a remote browser. `BetaLocalFilePolicy` (typescript: `BetaNodeFilePolicy`) checks paths on the filesystem of the process that runs the SDK, and the browser reads and writes its own filesystem.
901901 
902The SDK can't detect that a browser is remote. So for a remote browser, keep `file_upload` off unless your driver checks upload paths where the browser runs, with a `BetaFilePolicy` of its own. A `BetaFilePolicy` vets each upload's paths and document IDs, and decides whether Claude sees a download's path.
902The SDK can't detect that a browser is remote. So for a remote browser, keep `file_upload` off unless your driver checks upload paths where the browser runs, with a `BetaFilePolicy` of its own. A `BetaFilePolicy` vets each upload's paths and document IDs, and determines whether Claude sees a download's path.
903903 
904904Have a remote browser refuse downloads, unless its own host has the download setup from [Confine uploads and downloads](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#confine-uploads-and-downloads).
905905 
from line 907
907907 
908908## Computer toolset
909909 
910`BetaAbstractComputerToolset20260801` is the class for the [computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool). A driver is a subclass with one method per tool, such as `screenshot` or `left_click`. Start from a partner's driver under [Partner integrations](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#partner-integrations). To write your own, the claude-quickstarts repository has a [minimal VNC example](https://github.com/anthropics/claude-quickstarts/tree/main/computer-toolset) in Python and TypeScript. It controls a desktop over VNC, and it isn't production code.
910`BetaAbstractComputerToolset20260801` is the class for the [computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool). A driver is a subclass with one method for each tool, such as `screenshot` or `left_click`. Start from a partner's driver under [Partner integrations](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#partner-integrations). To write your own, the claude-quickstarts repository has a [minimal VNC example](https://github.com/anthropics/claude-quickstarts/tree/main/computer-toolset) in Python and TypeScript. It controls a desktop over VNC, and it isn't production code.
911911 
912912The class takes `configs`, `confirm`, and `tool_configs` (typescript: `toolConfigs`), and you pass them as you do for the browser class. [Customize a driver](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#customize-a-driver), [Handle errors](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#handle-errors), [Start calls while the response streams](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#start-calls-while-the-response-streams), and [Run without the tool runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#run-without-the-tool-runner) apply to it too, with these differences:
913913 
from line 1165
11651165 
11661166Don't rely on the SDK to check a call's input. Have your driver check the fields it uses and refuse a call it can't run: raise `ToolError` (throw it in TypeScript). Claude reads the message and can send a corrected call.
11671167 
1168Neither SDK limits a `duration`, a `repeat` count, or a `scroll_amount`. Step 4 under [Run the computer toolset safely](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#run-the-computer-toolset-safely) covers them.
1168The SDK doesn't limit a `duration`, a `repeat` count, or a `scroll_amount`. Step 4 under [Run the computer toolset safely](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-sdk#run-the-computer-toolset-safely) covers them.
11691169 
11701170What a tool returns determines what Claude reads:
11711171 
from line 1177
11771177 
11781178### Run the computer toolset safely
11791179 
1180What's on the screen steers Claude's next action. A page or a notification can try to make Claude type into the wrong window, or trigger an action with real effects.
1180What's on the screen steers Claude's next action. A page or a notification can attempt to make Claude type into the wrong window, or trigger an action with real effects.
11811181 
11821182<Warning>
11831183 A driver that implements `type`, `key`, or `hold_key` needs a `confirm` callable. Without one, the constructor raises a configuration error, unless `configs` turns those tools off. The SDK itself asks no one: it runs every call that your `confirm` approves, and with no `confirm` it runs every call, including every click. Every computer tool you implement is on by default.

agents-and-tools/tool-use/browser-use-tool Changed · +34 / -34 lines

from line 29
2929 
3030The browser use tool lets Claude navigate, read, and interact with webpages in a browser that your application runs. Claude works with the page both through its structure (the accessibility tree, elements, forms, and tabs) and through screenshots and viewport coordinates.
3131 
32The tool is an Anthropic-defined [client toolset](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets): one `browser_toolset_20260801` entry in `tools` gives Claude 27 member tools by default, such as `navigate`, `read_page`, `left_click`, and `screenshot`, plus four more when you [enable them](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#enable-optional-member-tools). Your application runs every call against its own browser automation; nothing runs on Anthropic's side. The tool isn't currently available in [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/tools).
32The tool is an Anthropic-defined [client toolset](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets): one `browser_toolset_20260801` entry in `tools` gives Claude 27 member tools by default, such as `navigate`, `read_page`, `left_click`, and `screenshot`, plus four more when you [enable optional members](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#enable-optional-member-tools). Your application runs every call against its own browser automation; nothing runs on Anthropic's side. The tool isn't currently available in [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/tools).
3333 
3434Choose browser use when the task stays inside webpages and means acting on them, or when pages build their content with JavaScript. When a task needs a whole desktop, use the [computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool), which works through screenshots and coordinates alone. For reading pages you can point Claude to, or finding sources on the web, the [web fetch tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool) and [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) are lighter. They're [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools) that the API runs for you, with no browser to operate.
3535 
from line 236
236236}
237237```
238238 
239Your executor (the part of your application that drives the browser and produces tool results) runs `navigate`, then `read_page`. Your application returns one `tool_result` per block in its next request, echoing `toolset_name` on each. The `navigate` result reports the tab it loaded in a `browser_state` block; the `read_page` result is text in which every element carries a reference:
239Your executor (the part of your application that drives the browser and produces tool results) runs `navigate`, then `read_page`. Your application returns one `tool_result` for each block in its next request, echoing `toolset_name` on each. The `navigate` result reports the tab it loaded in a `browser_state` block; the `read_page` result is text in which every element carries a reference:
240240 
241241```json
242242{
from line 295
295295 
296296 <Step title="Run the calls in order and return results">
297297 * Iterate every `tool_use` block in `response.content` (don't assume there's exactly one) and run them sequentially, in the order they appear, because later calls usually depend on earlier ones.
298 * Return one `tool_result` per block in a new `user` message, matched by `tool_use_id`, and echo `"toolset_name": "browser"` on each. Every call must be answered or the next request is rejected.
298 * Return one `tool_result` for each block in a new `user` message, matched by `tool_use_id`, and echo `"toolset_name": "browser"` on each. Answer every call, or the next request is rejected.
299299 * If a call fails, return `is_error: true` with a text description for that block, then apply the halt rule in [Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#batch-actions) to every later block in the turn.
300300 </Step>
301301 
from line 1087
10871087 
10881088You don't need to return a screenshot after every call. Claude typically ends a batch with an observation call (`screenshot`, `read_page`, or `get_page_text`), and your application can also attach its own observation, such as a fresh screenshot or accessibility tree, as an extra content block on the last result in the batch to save a round trip. Because a tab-management result must be exactly one `browser_state` block, attach it to the last result that isn't a tab-management call.
10891089 
1090If your executor can run only one call per round trip, set `disable_parallel_tool_use` to `true` in `tool_choice` and Claude returns at most one member call per turn, at the cost of more round trips ([Disable parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use#disable-parallel-tool-use)). The rest of the contract under [Batch actions for the computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions) carries over, including one `tool_result` for every `tool_use` in the next `user` message, except for two things: the halt text and what a successful result's `content` holds. Result content follows [Member tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#member-tools) on this page instead: a `new_tab`, `switch_tab`, `close_tab`, or `list_tabs` result is exactly one `browser_state` block with no text or image ([Tab management results](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#tab-management-results)), and any other member's result may add a `browser_state` block to its text or image ([Tab context on other results](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#tab-context-on-other-results)). Where cache breakpoints inside a batch take effect is described in the `cache_control` row of the computer use tool's [Tool parameters](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#tool-parameters).
1090If your executor can run only one call for each round trip, set `disable_parallel_tool_use` to `true` in `tool_choice` and Claude returns at most one member call for each turn, at the cost of more round trips ([Disable parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use#disable-parallel-tool-use)). The rest of the contract under [Batch actions for the computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions) carries over, including one `tool_result` for every `tool_use` in the next `user` message, except for two things: the halt text and what a successful result's `content` holds. Result content follows [Member tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#member-tools) on this page instead: a `new_tab`, `switch_tab`, `close_tab`, or `list_tabs` result is exactly one `browser_state` block with no text or image ([Tab management results](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#tab-management-results)), and any other member's result may add a `browser_state` block to its text or image ([Tab context on other results](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#tab-context-on-other-results)). Where cache breakpoints inside a batch take effect is described in the `cache_control` row of the computer use tool's [Tool parameters](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#tool-parameters).
10911091 
10921092### Targets and coordinates
10931093 
from line 1098
10981098| `CoordinateTarget` | `"coordinate"` | `x`, `y` (integers, viewport pixels) | `left_click`, `right_click`, `middle_click`, `double_click`, `triple_click`, `hover`, `left_click_drag` (`from` and `target`), `left_mouse_down`, `left_mouse_up`, `mouse_move`, `scroll` |
10991099| `RefTarget` | `"ref"` | `ref` (an element reference such as `"ref_2"`) | `left_click`, `right_click`, `middle_click`, `double_click`, `triple_click`, `hover`, `scroll_to`, `form_input`, `file_upload` |
11001100 
1101**Coordinates are viewport pixels**, the pixel space of a full-viewport `screenshot` with the origin at the top left of the rendered page; there's no surrounding desktop or window frame. The toolset declares no display dimensions and Claude infers the viewport size from the screenshots you return, so keep them one consistent size. A `zoom` doesn't change the frame, so its `region` and any coordinates Claude emits after seeing the zoomed image are still full-viewport pixels.
1101**Coordinates are viewport pixels**, the pixel space of a full-viewport `screenshot` with the origin at the top left of the rendered page; there's no surrounding desktop or window frame. The toolset declares no display dimensions and Claude infers the viewport size from the screenshots you return, so keep them one consistent size. A `zoom` doesn't change the frame, so its `region` and any coordinates Claude emits after receiving the zoomed image are still full-viewport pixels.
11021102 
11031103**Screenshots must fit the image limits.** The API doesn't downscale toolset images: a screenshot or zoom image over your model's [image size limits](https://platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size), or over the stricter per-image limit that applies once a request holds [more than 20 images](https://platform.claude.com/docs/en/build-with-claude/vision#request-limits), is rejected. Resize before returning, and scale Claude's coordinates back up by the inverse of your factor before dispatching them ([Size screenshots to fit image limits](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#handle-coordinate-scaling-for-higher-resolutions)).
11041104 
from line 1118
11181118 
11191119Claude uses both targeting styles and switches between them based on what the page exposes; your prompt and what your executor returns steer the choice:
11201120 
1121* **Prefer references where the page has a usable accessibility tree.** A reference survives layout shifts and reflows that make pixel coordinates fragile, and lets Claude act on controls that are hard to hit with a pointer.
1121* **Prefer references where the page has a usable accessibility tree.** A reference survives layout shifts and reflows that make pixel coordinates fragile, and lets Claude act on controls that are hard to click with a pointer.
11221122* **Fall back to coordinates for content the tree doesn't describe.** Canvas-rendered interfaces, embedded video or remote-desktop surfaces, heavily virtualized lists, and elements inside cross-origin iframes often have no useful node, so Claude works from `screenshot` and `zoom` and clicks by coordinate; your executor resolves which frame a coordinate lands in.
11231123* **Scope reads, and read the tree before you screenshot.** On large pages, `read_page` with `filter: "interactive"` or the `ref` of a container returns a focused subtree, and a tree read of a typical page often costs fewer input tokens than a screenshot while giving Claude references it can act on immediately. Screenshots remain the right observation when visual layout, images, or rendering state matter.
11241124 
from line 1141
11411141 
11421142Anthropic has trained the model to resist these prompt injections and has added an extra layer of defense. If you use the browser use tool, classifiers will automatically scan what the browser returns, such as page text or screenshots, to flag potential prompt injections. When these classifiers identify a potential prompt injection, they will automatically steer the model to check whether the instruction really came from you before acting on it.
11431143 
1144This extra protection won't be ideal for every use case (for example, use cases without a human in the loop), so if you'd like to opt out and turn it off, [contact support](https://support.claude.com/en/). The precautions above remain important even with these classifiers in place.
1144This extra protection isn't ideal for every use case (for example, use cases without a human in the loop), so if you'd like to opt out and turn it off, [contact support](https://support.claude.com/en/). The precautions listed earlier remain important even with these classifiers in place.
11451145 
11461146Because the browser runs in your environment, the sites Claude visits see your executor's network identity, and page content reaches the API only as the tool results you return. Inform end users of the relevant risks and obtain their consent before enabling browser use in your products.
11471147 
11481148## Member tools
11491149 
1150The `browser_toolset_20260801` entry declares 31 member tools; each call's `input` is exactly the parameters listed here, and `tab_id`, where optional, defaults to the active tab. `Target`, `CoordinateTarget`, and `RefTarget` are the shapes described in [Targets and coordinates](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#targets-and-coordinates). Four members (`javascript_exec`, `file_upload`, `read_console`, and `read_network`) are disabled by default and appear only when you [enable them](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#enable-optional-member-tools). The input bounds and output conventions noted in each member's row are stated to Claude, not enforced by the API, so validate inputs (including coordinates against your viewport) and apply the conventions in your executor.
1150The `browser_toolset_20260801` entry declares 31 member tools; each call's `input` is exactly the parameters listed here, and `tab_id`, where optional, defaults to the active tab. `Target`, `CoordinateTarget`, and `RefTarget` are the shapes described in [Targets and coordinates](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#targets-and-coordinates). Four members (`javascript_exec`, `file_upload`, `read_console`, and `read_network`) are disabled by default and appear only when you enable them (see [Enable optional members](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#enable-optional-member-tools)). The input bounds and output conventions noted in each member's row are stated to Claude, not enforced by the API, so validate inputs (including coordinates against your viewport) and apply the conventions in your executor.
11511151 
1152Only `screenshot` and `zoom` require an [`image` block](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls#handling-results-from-client-tools) in their result, and the four tab-management members (`new_tab`, `list_tabs`, `switch_tab`, and `close_tab`) return exactly one `browser_state` block (see [Tab management results](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#tab-management-results)). Every other member returns a `text` block: either a short acknowledgment such as `Clicked element ref_2.` or the member's output. Any result other than a tab-management result may also carry an `image` block, typically a screenshot taken after the action, so Claude sees the outcome without a separate `screenshot` call; [Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#batch-actions) shows where to attach one in a batch. A member `tool_result` may contain only `text`, `image`, and `browser_state` content blocks.
1152Only `screenshot` and `zoom` require an [`image` block](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls#handling-results-from-client-tools) in their result, and the four tab-management members (`new_tab`, `list_tabs`, `switch_tab`, and `close_tab`) return exactly one `browser_state` block (see [Tab management results](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#tab-management-results)). Every other member returns a `text` block: either a short acknowledgment such as `Clicked element ref_2.` or the member's output. Any result other than a tab-management result may also carry an `image` block, typically a screenshot taken after the action, so Claude receives the outcome without a separate `screenshot` call; [Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#batch-actions) shows where to attach one in a batch. A member `tool_result` may contain only `text`, `image`, and `browser_state` content blocks.
11531153 
11541154### Navigation and capture
11551155 
from line 1190
11901190| Member | Input | Description |
11911191| --------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
11921192| `read_page` | `filter?`, `depth?`, `ref?`, `tab_id?` | Return the page's accessibility tree as text with each element tagged with a reference such as `[ref_2]`. With `filter` omitted, return every visible element; with `"interactive"`, only visible interactive elements; with `"all"`, also elements outside the viewport. `depth` caps the tree depth (minimum 1, default 15) and `ref` scopes the read to that element's subtree. Cap the output at 50,000 characters and say so in the text; Claude then narrows with a smaller `depth` or a `ref`. |
1193| `find` | `query`, `tab_id?` | Search for elements matching a natural-language description such as `"search field"` or `"add to cart button"`, and return up to 20 matches in the same tagged format as `read_page`. |
1193| `find` | `query`, `tab_id?` | Find elements matching a natural-language description such as `"search field"` or `"add to cart button"`, and return up to 20 matches in the same tagged format as `read_page`. |
11941194| `get_page_text` | `tab_id?` | Return the page's visible text as plain text, prioritizing the main article content; suited to articles, documentation, and other text-heavy pages. |
11951195 
11961196### Forms and files
from line 1244
12441244}
12451245```
12461246 
1247A disabled member disappears from the definition Claude sees; that doesn't guarantee Claude never names it, so your executor still answers such a call with an [error result](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#return-errors-from-your-executor).
1247A disabled member disappears from the definition Claude receives; that doesn't guarantee Claude never names it, so your executor still answers such a call with an [error result](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#return-errors-from-your-executor).
12481248 
12491249### Combine with other tools
12501250 
from line 1285
12851285 
12861286### Read console and network activity
12871287 
1288`read_console` returns the tab's console entries and `read_network` returns its network requests, each as text with one line per entry accumulated since the previous read of that tab. A console line carries a log, warning, or error entry; a network line carries the method, URL, status, MIME type, and timing. Entries exist only from the moment your browser automation attached to the tab, so an empty result doesn't mean a tab that was already open had no traffic.
1288`read_console` returns the tab's console entries and `read_network` returns its network requests, each as text with one line for each entry accumulated since the previous read of that tab. A console line carries a log, warning, or error entry; a network line carries the method, URL, status, MIME type, and timing. Entries exist only from the moment your browser automation attached to the tab, so an empty result doesn't mean a tab that was already open had no traffic.
12891289 
1290These members let Claude diagnose a misbehaving page (a failed request behind a spinner, a script error behind a dead button) without repeated screenshots. Console and network entries are page-controlled and often contain secrets such as tokens in request URLs, so redact credential-like values you don't want in Claude's context and truncate very long entries before returning them.
1290These members let Claude diagnose a misbehaving page (a failed request behind a spinner, a script error behind an unresponsive button) without repeated screenshots. Console and network entries are page-controlled and often contain secrets such as tokens in request URLs, so redact credential-like values you don't want in Claude's context and truncate very long entries before returning them.
12911291 
12921292## Track tabs with `browser_state`
12931293 
1294Claude addresses tabs by `tab_id`, your application is the source of truth for which tabs exist, and you report that state in a `browser_state` content block that Claude never sees directly: the API renders the text Claude reads from it.
1294Claude addresses tabs by `tab_id`, your application is the source of truth for which tabs exist, and you report that state in a `browser_state` content block that Claude never receives directly: the API renders the text Claude reads from it.
12951295 
12961296```json
12971297{
from line 1309
13091309```
13101310 
13111311* `tabs` is the full inventory of open tabs after the call, not a delta. It may be empty; whenever it isn't, exactly one entry carries `"active": true`.
1312* `state_changes` (not shown here) reports side effects of the call: a `tab_opened` entry for each tab the call opened that's still open when it finishes, whose `tab_id` must also appear in `tabs`, and [download events](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#report-downloads). Omit the field when there's nothing to report; an empty array is rejected.
1313* Send the block only on results that answer a browser member call, at most once per `tool_result`, and never on a result with `is_error: true`. You express "no tab state to report" by omitting the block.
1312* `state_changes` (not shown here) reports side effects of the call: a `tab_opened` entry for each tab the call opened that's still open when it completes, whose `tab_id` must also appear in `tabs`, and [download events](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#report-downloads). Omit the field when there's nothing to report; an empty array is rejected.
1313* Send the block only on results that answer a browser member call, at most once for each `tool_result`, and never on a result with `is_error: true`. You express "no tab state to report" by omitting the block.
13141314* The API renders `tabs`, and any download entries in `state_changes`, into text for Claude. The next two sections and [Report downloads](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#report-downloads) show that text.
13151315 
13161316**You assign `tab_id` values.** Any stable string works, such as your automation library's page identifier or your own counter, as long as you don't reuse a `tab_id` while a tab with that identifier is still listed as open in an earlier result. The API enforces these limits on the block:
from line 1320
13201320* The same limits apply to the `tab_id` Claude passes to `switch_tab` and `close_tab`, because the API renders it into the result text, so answer a call whose `tab_id` violates them with an error result instead of a `browser_state` block.
13211321 
13221322<Warning>
1323 Tab titles and URLs come from the page and render into text Claude reads, so they're a prompt-injection surface. The API renders tab URLs verbatim, so sanitize page-supplied URLs before populating `tabs`. It escapes double quotes and backslashes in titles when it renders them, so don't pre-escape titles (a pre-escaped title reaches Claude double-escaped); truncating or dropping suspicious titles is still worthwhile. A download entry's `url`, `path`, and `error` also render into text Claude reads, so treat them as untrusted too; the API quotes and escapes them as it does titles. The length and character limits the API enforces are a floor, not a defense.
1323 Tab titles and URLs come from the page and render into text Claude reads, so they're a prompt-injection surface. The API renders tab URLs verbatim, so sanitize page-supplied URLs before populating `tabs`. It escapes double quotes and backslashes in titles when it renders them, so don't pre-escape titles (a pre-escaped title reaches Claude double-escaped); truncating or dropping suspicious titles is still worthwhile. A download entry's `url`, `path`, and `error` also render into text Claude reads, so treat them as untrusted too; the API quotes and escapes them as it does titles. The length and character limits the API enforces are a minimum, not a defense.
13241324</Warning>
13251325 
13261326### Tab management results
13271327 
1328For `new_tab`, `switch_tab`, `close_tab`, and `list_tabs`, a successful result's `content` is exactly one `browser_state` block with no text or image, and the API writes the text Claude sees. A `new_tab` result's block must also carry exactly one `tab_opened` state change whose `tab_id` matches the entry marked `active: true`.
1328For `new_tab`, `switch_tab`, `close_tab`, and `list_tabs`, a successful result's `content` is exactly one `browser_state` block with no text or image, and the API writes the text Claude receives. A `new_tab` result's block must also carry exactly one `tab_opened` state change whose `tab_id` matches the entry marked `active: true`.
13291329 
1330| Member | Text Claude sees |
1330| Member | Text Claude receives |
13311331| ------------ | --------------------------------------------------------------------------------------------------------------------------- |
13321332| `switch_tab` | `Switched to tab {tab_id}`, taken from the call's `input.tab_id` |
13331333| `close_tab` | `Closed tab {tab_id}`, taken from the call's `input.tab_id` |
from line 1370
13701370}
13711371```
13721372 
1373Claude sees `Created new tab with tab_id: tab-3, URL: about:blank. It is now the current tab.` Report the URL the tab was opened at, as here, not one it later redirects to; later results report the tab's then-current URL.
1373Claude receives `Created new tab with tab_id: tab-3, URL: about:blank. It is now the current tab.` Report the URL the tab was opened at, as here, not one it later redirects to; later results report the tab's then-current URL.
13741374 
13751375### Tab context on other results
13761376 
from line 1389
13891389Three cases render no footer even when the block is present:
13901390 
13911391* Any `zoom` result.
1392* A result with no `text` block (an image-only `screenshot` result, for example). Nothing is rendered or remembered for that result; the tab context appears on the next result that carries both text and a `browser_state` block, so include a short text block alongside the image when you want Claude to see a tab change on that same result. The exception is a result whose block reports a [download event](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#report-downloads). The API adds the download lines as a text block, and the footer follows them as it would on any result with text.
1392* A result with no `text` block (an image-only `screenshot` result, for example). Nothing is rendered or remembered for that result; the tab context appears on the next result that carries both text and a `browser_state` block, so include a short text block alongside the image when you want the tab change to reach Claude on that same result. The exception is a result whose block reports a [download event](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#report-downloads). The API adds the download lines as a text block, and the footer follows them as it would on any result with text.
13931393* A result whose `tabs` list is empty on a call that carried no `tab_id`, because there's no tab to name.
13941394 
13951395For example, when Claude clicked the "Pricing" link (`ref_5`) earlier in this session, the page opened it in a new tab Claude didn't ask for, and without a report Claude would have to call `list_tabs` to discover it. Return the click's acknowledgment plus a block whose `state_changes` names the opened tab, marking whichever tab your executor left active:
from line 1423
14231423}
14241424```
14251425 
1426Claude sees `Clicked element ref_5.` followed by the Tab Context footer shown earlier. A tab opened during a call that failed gets no `tab_opened` entry, because error results carry no `browser_state`; it appears in the `tabs` inventory of the next successful result instead. In a batch, attach the block to the result of the call during which the change happened, and give every successful tab-management result its own block even when an earlier result in the same turn reported the same state.
1426Claude receives `Clicked element ref_5.` followed by the Tab Context footer shown earlier. A tab opened during a call that failed gets no `tab_opened` entry, because error results carry no `browser_state`; it appears in the `tabs` inventory of the next successful result instead. In a batch, attach the block to the result of the call during which the change occurred, and give every successful tab-management result its own block even when an earlier result in the same turn reported the same state.
14271427 
14281428### Report downloads
14291429 
1430When a click or navigation starts a file download, report it in `state_changes` on the result of the call during which it happened, correlated across results by a `download_id` you assign. Downloads run asynchronously and can span several results, so there are three event types:
1430When a click or navigation starts a file download, report it in `state_changes` on the result of the call during which it occurred, correlated across results by a `download_id` you assign. Downloads run asynchronously and can span several results, so there are three event types:
14311431 
1432| `type` | Fields | When to send |
1433| -------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1434| `download_started` | `download_id`, `url` | On the result of the call during which the download began. `url` is the final URL the file is served from, after redirects. |
1435| `download_completed` | `download_id`, `url`, `path?`, `size_bytes?` | On the result of whichever later call is running when the download finishes. Include `path` only when another tool in the same environment (for example, the [bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool) or `file_upload`) can read the file there; otherwise `download_id` is the download's only identifier. |
1436| `download_failed` | `download_id`, `url`, `error?` | When the download fails or is canceled, with the reason in `error` if the browser provides one. |
1432| `type` | Fields | When to send |
1433| -------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1434| `download_started` | `download_id`, `url` | On the result of the call during which the download started. `url` is the final URL the file is served from, after redirects. |
1435| `download_completed` | `download_id`, `url`, `path?`, `size_bytes?` | On the result of whichever later call is running when the download completes. Include `path` only when another tool in the same environment (for example, the [bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool) or `file_upload`) can read the file there; otherwise `download_id` is the download's only identifier. |
1436| `download_failed` | `download_id`, `url`, `error?` | When the download fails or is canceled, with the reason in `error` if the browser provides one. |
14371437 
14381438The API renders each entry as one line of text for Claude, in the order the entries appear. It adds the lines after the result's text, separated by a blank line, and before any Tab Context footer. Every kind of member result carries the lines, including `zoom` and tab-management results. A result with no `text` block gets them as a text block of its own. Each line gives the `download_id` and `url`, plus `path` and `size_bytes` (for `download_completed`) or `error` (for `download_failed`) when you send them. You don't need to describe the download in your own text. The API wraps `url`, `path`, and `error` in double quotes and escapes double quotes and backslashes inside them, so don't pre-escape these values.
14391439 
from line 1463
14631463}
14641464```
14651465 
1466Claude sees `Screenshot captured.` followed by a blank line and a line like this:
1466Claude receives `Screenshot captured.` followed by a blank line and a line like this:
14671467 
14681468```text wrap
14691469Download completed with download_id: dl-1, URL: "https://example.com/pricing/price-list.csv". Saved to "/home/user/downloads/price-list.csv". Size: 48213 bytes.
from line 1471
14711471 
14721472Download reports follow these rules:
14731473 
1474* At most one entry per `download_id` in a single block, so a download that starts and finishes during the same call reports only `download_completed`.
1474* Send at most one entry for each `download_id` in a single block, so a download that starts and finishes during the same call reports only `download_completed`.
14751475* Never send `state_changes` on an `is_error: true` result; report a download event that occurred during a failed call on the next successful result.
14761476* `state_changes` isn't an inventory of downloads in progress; report each event once.
14771477* Each entry carries only the fields its `type` declares. `size_bytes` is a non-negative integer, `download_id` is non-empty, and `download_id`, `url`, `path`, and `error` are each at most 4,096 characters with no control characters or Unicode line or paragraph separators. The `url` comes from the remote server and often carries signed query-string credentials after redirects, so strip query parameters you don't want in Claude's context and sanitize it before reporting it or using it in a filesystem path.

agents-and-tools/tool-use/build-a-tool-using-agent Changed · +13 / -13 lines

from line 770
770770 # Send the user's request along with the tool definition. Claude decides
771771 # whether to call the tool based on the request and the tool description.
772772 response = client.messages.create(
773 model: "claude-opus-5-5",
773 model: Anthropic::Model::CLAUDE_OPUS_5_5,
774774 max_tokens: 1024,
775775 tools: tools,
776776 tool_choice: tool_choice,
from line 795
795795 # its tool_use_id must match the id from the tool_use block above. The
796796 # assistant's previous response is included so Claude has the full history.
797797 followup = client.messages.create(
798 model: "claude-opus-5-5",
798 model: Anthropic::Model::CLAUDE_OPUS_5_5,
799799 max_tokens: 1024,
800800 tools: tools,
801801 tool_choice: tool_choice,
from line 840
840840 
841841Ring 1 assumed Claude would call the tool exactly once. Real tasks often need several calls: Claude might create an event, read the confirmation, then create another. The fix is a `while` loop that keeps running tools and feeding results back until `stop_reason` is no longer `"tool_use"`.
842842 
843The other change is conversation history. Instead of rebuilding the `messages` array from scratch on each request, keep a running list and append to it. Every turn sees the complete prior context.
843The other change is conversation history. Instead of rebuilding the `messages` array on each request, keep a running list and append to it. Each request then includes the complete prior context.
844844 
845845<CodeGroup exclude="shell:cURL, shell:CLI">
846846 <CodeGroupItem language="cURL">
from line 1551
15511551 ]
15521552 
15531553 response = client.messages.create(
1554 model: "claude-opus-5-5",
1554 model: Anthropic::Model::CLAUDE_OPUS_5_5,
15551555 max_tokens: 1024,
15561556 tools: tools,
15571557 tool_choice: tool_choice,
from line 1577
15771577 }
15781578 
15791579 response = client.messages.create(
1580 model: "claude-opus-5-5",
1580 model: Anthropic::Model::CLAUDE_OPUS_5_5,
15811581 max_tokens: 1024,
15821582 tools: tools,
15831583 tool_choice: tool_choice,
from line 2369
23692369 ]
23702370 
23712371 response = client.messages.create(
2372 model: "claude-opus-5-5",
2372 model: Anthropic::Model::CLAUDE_OPUS_5_5,
23732373 max_tokens: 1024,
23742374 tools: tools,
23752375 messages: messages
from line 2390
23902390 messages << {role: "user", content: tool_results}
23912391 
23922392 response = client.messages.create(
2393 model: "claude-opus-5-5",
2393 model: Anthropic::Model::CLAUDE_OPUS_5_5,
23942394 max_tokens: 1024,
23952395 tools: tools,
23962396 messages: messages
from line 3261
32613261 ]
32623262 
32633263 response = client.messages.create(
3264 model: "claude-opus-5-5",
3264 model: Anthropic::Model::CLAUDE_OPUS_5_5,
32653265 max_tokens: 1024,
32663266 tools: tools,
32673267 messages: messages
from line 3290
32903290 messages << {role: "user", content: tool_results}
32913291 
32923292 response = client.messages.create(
3293 model: "claude-opus-5-5",
3293 model: Anthropic::Model::CLAUDE_OPUS_5_5,
32943294 max_tokens: 1024,
32953295 tools: tools,
32963296 messages: messages
from line 3309
33093309I tried to schedule the all-hands but the calendar only allows 10 attendees per event. I can split this into two sessions, or you can let me know which 10 people to prioritize.
33103310```
33113311 
3312The `is_error` flag is the only difference from a successful result. Claude sees the flag and the error text, and responds accordingly. See [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) for the full error-handling reference.
3312The `is_error` flag is the only difference from a successful result. Claude receives the flag and the error text, and responds accordingly. See [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) for the full error-handling reference.
33133313 
33143314## Ring 5: The Tool Runner SDK abstraction
33153315 
33163316Rings 2 through 4 wrote the same loop by hand: call the API, check `stop_reason`, run tools, append results, repeat. The Tool Runner does this for you. Define each tool as a function, pass the list to `client.beta.messages.tool_runner()` (typescript: `client.beta.messages.toolRunner()`; java: `client.beta().messages().toolRunner()`; php: `$client->beta->messages->toolRunner()`; csharp: `client.Beta.Messages.ToolRunner()`; go: `client.Beta.Messages.NewToolRunner()`), and retrieve the final message once the loop completes. Error wrapping, result formatting, and conversation management are handled internally.
33173317 
3318Each SDK provides a helper that turns an ordinary function into a runnable tool and derives the input schema from its signature; the following tabs show the idiomatic form for each language.
3318The SDK provides a helper that turns an ordinary function into a runnable tool and derives the input schema from its signature; the following example shows the idiomatic form.
33193319 
33203320<CodeGroup exclude="shell:cURL, shell:CLI">
33213321 <CodeGroupItem language="cURL">
from line 3905
39053905 # The runner calls the API, runs requested tools, and feeds results back
39063906 # until Claude produces a final answer.
39073907 runner = client.beta.messages.tool_runner(
3908 model: "claude-opus-5-5",
3908 model: Anthropic::Model::CLAUDE_OPUS_5_5,
39093909 max_tokens: 1024,
39103910 tools: [CreateCalendarEvent.new, ListCalendarEvents.new],
39113911 messages: [
from line 3931
39313931I checked your calendar for Monday, March 30 and found an existing meeting from 2pm to 3pm. I've scheduled the planning session for 10am to 11am to avoid the conflict.
39323932```
39333933 
3934The output is identical to Ring 3. The difference is in the code: roughly half the lines, no manual loop, and the schema lives next to the implementation.
3934The output is identical to Ring 3. The difference is in the code: roughly half the lines, no manual loop, and a schema that lives next to the implementation.
39353935 
39363936## What you built
39373937 

agents-and-tools/tool-use/code-execution-tool Changed · +38 / -38 lines

from line 1
11---
22title: Code execution tool
33url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool
4description: Run Python and bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
4description: Run Python and Bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
55featureMetadata:
66 status: ga
77 zdr: not-eligible
from line 40
4040Code execution also powers dynamic filtering in the [web search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) and [web fetch](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool) tools: Claude filters results inside the code execution environment before they reach the context window. When dynamic filtering runs, the API provisions the code execution it needs for the request automatically, so you don't add the code execution tool to your request for it.
4141 
4242<Note>
43 Reach out through the [feedback form](https://forms.gle/LTAU6Xn2puCJMi1n6) to share your feedback on this feature.
43 Use the [feedback form](https://forms.gle/LTAU6Xn2puCJMi1n6) to share your feedback on this feature.
4444</Note>
4545 
4646## Tool versions
from line 49
4949 
5050* `code_execution_20250825` supports Bash commands and file operations.
5151* `code_execution_20260120` adds REPL state persistence and [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) from within the sandbox. Claude Haiku 4.5 accepts the `code_execution_20260120` and `code_execution_20260521` tool types, but programmatic tool calling and the REPL state persistence that depends on it aren't available on it, so the newer versions behave like `code_execution_20250825` there.
52* `code_execution_20260521` is the same runtime as `code_execution_20260120`. The difference is that the tool description tells Claude about the 90-second wall-clock limit on each Python cell in programmatic tool calling, so Claude can budget long-running cells. A cell that exceeds the limit returns a normal code execution result with a non-zero `return_code` and a `detection_timeout` status message in its output. This is separate from the `execution_time_exceeded` [error code](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#errors), which the API returns when a whole tool invocation exceeds the maximum execution time.
52* `code_execution_20260521` is the same runtime as `code_execution_20260120`. The difference is that the tool description tells Claude about the 90-second wall-clock limit on each Python cell in programmatic tool calling, so Claude can budget long-running cells. A cell that exceeds the limit returns a normal code execution result with a non-zero `return_code` and a `detection_timeout` status message in its output. This is separate from the `execution_time_exceeded` [error code](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#errors), which the API returns when a whole tool call exceeds the maximum execution time.
5353 
5454None of the three tool versions requires an `anthropic-beta` header. The legacy code execution beta headers remain valid opt-ins.
5555 
from line 230
230230 
231231When you add the code execution tool to your API request:
232232 
2331. Claude evaluates whether code execution would help answer your question
2331. Claude evaluates whether code execution would help answer your question.
234234 
2352352. The tool automatically provides Claude with the following capabilities:
236236 
from line 237
237237 * **Bash commands:** Run shell commands for system operations
238238 * **File operations:** Create, view, and edit files directly, including writing code
239239 
2403. Claude can use any combination of these capabilities in a single request
2403. Claude can use any combination of these capabilities in a single request.
241241 
2424. All operations run in a secure, sandboxed container. The container has no internet access, so Claude can't download packages at runtime: only the [pre-installed libraries](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#pre-installed-libraries) are available
2424. All operations run in a secure, sandboxed container. The container has no internet access, so Claude can't download packages at runtime: only the [pre-installed libraries](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#pre-installed-libraries) are available.
243243 
2445. The API runs every command server-side and returns the results to Claude within the same request, so you never execute code or send back `tool_result` blocks yourself. One exception is when Claude calls one of your client tools alongside code execution: the API returns the code execution call without its result. The result arrives in a later response, after you send back the `tool_result` blocks for your client tools
2445. The API runs every command server-side and returns the results to Claude within the same request, so you never run code or send back `tool_result` blocks yourself. One exception is when Claude calls one of your client tools alongside code execution: the API returns the code execution call without its result. The result arrives in a later response, after you send back the `tool_result` blocks for your client tools.
245245 
2466. Each request runs in a new container unless you pass an earlier response's container ID back (see [Container reuse](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#container-reuse))
2466. Each request runs in a new container unless you pass an earlier response's container ID back (see [Container reuse](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#container-reuse)).
247247 
2487. Claude provides results with any generated charts, calculations, or analysis
2487. Claude provides results with any generated charts, calculations, or analysis.
249249 
250250The container has Python pre-installed. Claude writes Python with the file operations sub-tool and runs it with a Bash command. With `code_execution_20260120` or later and [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), the Python interpreter state (such as variable bindings) also persists across requests that reuse the container.
251251 
from line 256
256256* Non-trivial math (large numbers, many steps, precision-sensitive results)
257257* Data analysis, file parsing, or visualization
258258* Algorithm execution or simulation
259* Explicit requests to "run", "compute", or "execute"
259* Explicit requests to "run," "compute," or "execute"
260260 
261261Claude answers directly without running code for:
262262 
from line 283
283283 
284284#### Upload and analyze files
285285 
2861. **Upload your file** using the [Files API](https://platform.claude.com/docs/en/build-with-claude/files)
2872. **Reference the file** in your message using a `container_upload` content block
2883. **Include the code execution tool** in your API request
2861. **Upload your file** using the [Files API](https://platform.claude.com/docs/en/build-with-claude/files).
2872. **Reference the file** in your message using a `container_upload` content block.
2883. **Include the code execution tool** in your API request.
289289 
290290<CodeGroup>
291291 ```bash cURL
from line 894
894894 
895895#### How generated files are captured
896896 
897Each `bash_code_execution` call gets a new, empty directory, available to the command as `$OUTPUT_DIR`. When the command finishes, the files at the top level of that directory are captured and returned as the `file_id` entries in the result's `content` list. Files written anywhere else stay in the container and aren't returned.
897Each `bash_code_execution` call gets a new, empty directory, available to the command as `$OUTPUT_DIR`. When the command completes, the files at the top level of that directory are captured and returned as the `file_id` entries in the result's `content` list. Files written anywhere else stay in the container and aren't returned.
898898 
899The tool description tells Claude to share files by copying them into `$OUTPUT_DIR`. If your application depends on receiving a file, prompt Claude to copy it into `$OUTPUT_DIR` and list the directory in the same command, so the `ls` output confirms the capture (Claude doesn't see the `content` list):
899The tool description tells Claude to share files by copying them into `$OUTPUT_DIR`. If your application depends on receiving a file, prompt Claude to copy it into `$OUTPUT_DIR` and list the directory in the same command, so the `ls` output confirms the capture (Claude doesn't receive the `content` list):
900900 
901901```bash
902902python /tmp/make_report.py && cp /tmp/report.pdf "$OUTPUT_DIR/" && ls "$OUTPUT_DIR"
from line 1073
10731073 
10741074**Error codes by tool type:**
10751075 
1076| Tool | Error code | Description |
1077| ------------ | ------------------------- | ------------------------------------------------------- |
1078| All tools | `unavailable` | The tool is temporarily unavailable |
1079| All tools | `execution_time_exceeded` | The tool invocation exceeded the maximum execution time |
1080| All tools | `invalid_tool_input` | Invalid parameters provided to the tool |
1081| All tools | `too_many_requests` | Rate limit exceeded for tool usage |
1082| bash | `output_file_too_large` | Command output exceeded the maximum size |
1083| text\_editor | `file_not_found` | File doesn't exist (for view/edit operations) |
1076| Tool | Error code | Description |
1077| ------------ | ------------------------- | ------------------------------------------------- |
1078| All tools | `unavailable` | The tool is temporarily unavailable |
1079| All tools | `execution_time_exceeded` | The tool call exceeded the maximum execution time |
1080| All tools | `invalid_tool_input` | Invalid parameters provided to the tool |
1081| All tools | `too_many_requests` | Rate limit exceeded for tool usage |
1082| bash | `output_file_too_large` | Command output exceeded the maximum size |
1083| text\_editor | `file_not_found` | File doesn't exist (for view/edit operations) |
10841084 
10851085An expired container can't be reused: requests that reference it return an error instead of restoring it. Send the request again without the `container` parameter to get a new container.
10861086 
from line 1103
11031103* **Memory:** 5 GiB RAM
11041104* **Disk space:** 5 GiB workspace storage
11051105* **CPU:** 1 CPU
1106* **Execution time:** A tool invocation that runs past the maximum execution time returns an `execution_time_exceeded` [error](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#errors). With [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), each REPL cell also has a 90-second wall-clock limit
1106* **Execution time:** A tool call that runs past the maximum execution time returns an `execution_time_exceeded` [error](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#errors). With [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), each REPL cell also has a 90-second wall-clock limit
11071107 
11081108### Networking and security
11091109 
11101110* **Internet access:** Completely disabled for security
1111* **External connections:** No outbound network requests permitted
1111* **External connections:** No outbound network requests allowed
11121112* **Sandbox isolation:** Full isolation from host system and other containers
11131113* **File access:** Limited to workspace directory only
11141114* **Workspace scoping:** Like the [Files API](https://platform.claude.com/docs/en/build-with-claude/files), containers are scoped to the request's workspace
from line 1423
14231423 
14241424## Using code execution with other execution tools
14251425 
1426When you provide code execution alongside client-provided tools that also run code (such as a [Bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool) or custom REPL), Claude is operating in a multicomputer environment. The code execution tool runs in Anthropic's sandboxed container, while your client-provided tools run in a separate environment that you control. Claude can sometimes confuse these environments, attempting to use the wrong tool or assuming state is shared between them.
1426When you provide code execution alongside client-provided tools that also run code (such as a [Bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool) or custom REPL), Claude is operating in a multicomputer environment. The code execution tool runs in Anthropic's sandboxed container, whereas your client-provided tools run in a separate environment that you control. Claude can sometimes use the wrong tool or act as if state is shared between these environments.
14271427 
14281428To avoid this, add instructions to your system prompt that clarify the distinction:
14291429 
from line 1435
14351435- If you need to pass results between environments, explicitly include outputs in subsequent tool calls rather than assuming shared state
14361436```
14371437 
1438This is especially important when combining code execution with [web search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) or [web fetch](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool), which enable code execution automatically. If your application already provides a client-side shell tool, the automatic code execution creates a second execution environment that Claude needs to distinguish between.
1438This is especially important when combining code execution with [web search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) or [web fetch](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool), which enable code execution automatically. If your application already provides a client-side shell tool, the automatic code execution creates a second execution environment that Claude needs to distinguish from the first.
14391439 
14401440When Claude calls one of your client tools alongside code execution, the API returns the code execution call without its result. The result arrives in a later response, after you send back the `tool_result` blocks for your client tools.
14411441 
from line 1468
14681468 
14691469When used without these tools, code execution is billed by execution time, tracked separately from token usage:
14701470 
1471* Execution time has a minimum of 5 minutes
1472* Each organization receives **1,550 free hours** of usage per month
1473* Additional usage beyond 1,550 hours is billed at **$0.05 USD per hour, per container**
1474* If files are included in the request, execution time is billed even if the tool is not called, because files are preloaded onto the container
1471* Execution time has a minimum of 5 minutes.
1472* Each organization receives **1,550 free hours** of usage per month.
1473* Additional usage beyond 1,550 hours is billed at **$0.05 USD per hour, per container**.
1474* If files are included in the request, execution time is billed even if the tool is not called, because files are preloaded onto the container.
14751475 
14761476Code execution usage is tracked in the response:
14771477 
from line 1518
15181518 
15191519**Review response handling** (if parsing responses programmatically):
15201520 
1521* The API no longer sends the previous blocks for Python execution responses
1522* Instead, the API sends new response types for Bash and file operations (see [Response format](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#response-format))
1521* The API no longer sends the previous blocks for Python execution responses.
1522* Instead, the API sends new response types for Bash and file operations (see [Response format](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#response-format)).
15231523 
15241524## Data retention
15251525 

agents-and-tools/tool-use/computer-use-tool Changed · +20 / -20 lines

from line 37
3737 
3838Claude can interact with computer environments through the computer use tool, which provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
3939 
40The computer use tool is an Anthropic-defined [client toolset](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets): one `{"type": "computer_toolset_20260801"}` entry in `tools` gives Claude 17 member tools such as `screenshot`, `left_click`, `type`, and `zoom`, and your application runs every call in an environment you control. It isn't currently available in [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/tools). Claude's calls are `tool_use` blocks whose `name` is the member and which carry `"toolset_name": "computer"`, often several per turn (a [batch action](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions)).
40The computer use tool is an Anthropic-defined [client toolset](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets): one `{"type": "computer_toolset_20260801"}` entry in `tools` gives Claude 17 member tools such as `screenshot`, `left_click`, `type`, and `zoom`, and your application runs every call in an environment you control. It isn't currently available in [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/tools). Claude's calls are `tool_use` blocks whose `name` is the member and which carry `"toolset_name": "computer"`, often several in one turn (a [batch action](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions)).
4141 
4242For tasks that stay inside webpages, the [browser use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool) is the closer fit: its member tools read and act on the page itself, and it doesn't need a full desktop environment.
4343 
from line 60
6060 4. Asking a human to confirm decisions that might result in meaningful real-world consequences and any tasks requiring affirmative consent, such as accepting cookies, completing financial transactions, or agreeing to terms of service.
6161</Warning>
6262 
63In some circumstances, Claude will follow commands found in content even when they conflict with your instructions. For example, instructions on webpages or contained in images might override your instructions or cause Claude to make mistakes. Take precautions to isolate Claude from sensitive data and actions to avoid risks related to prompt injection.
63In some circumstances, Claude follows commands found in content even when they conflict with your instructions. For example, instructions on webpages or contained in images might override your instructions or cause Claude to make mistakes. Take precautions to isolate Claude from sensitive data and actions to avoid risks related to prompt injection.
6464 
6565Anthropic has trained the model to resist these prompt injections and has added an extra layer of defense. If you use the computer use tools, classifiers will automatically scan what the tools return, such as screenshots, to flag potential prompt injections. When these classifiers identify a potential prompt injection, they will automatically steer the model to check whether the instruction really came from you before acting on it.
6666 
67This extra protection won't be ideal for every use case (for example, use cases without a human in the loop), so if you'd like to opt out and turn it off, [contact support](https://support.claude.com/en/). The precautions above remain important even with these classifiers in place.
67This extra protection isn't ideal for every use case (for example, use cases without a human in the loop), so if you'd like to opt out and turn it off, [contact support](https://support.claude.com/en/). The precautions listed earlier remain important even with these classifiers in place.
6868 
6969Inform end users of relevant risks and obtain their consent prior to enabling computer use in your own products.
7070 
from line 275
275275 ```
276276</CodeGroup>
277277 
278When Claude acts on the desktop, the response has a `stop_reason` of `tool_use` and contains one or more member `tool_use` blocks, each naming a member tool and carrying `"toolset_name": "computer"`. Partway through this task, after Claude has seen a screenshot of the desktop, a response might look like this:
278When Claude acts on the desktop, the response has a `stop_reason` of `tool_use` and contains one or more member `tool_use` blocks, each naming a member tool and carrying `"toolset_name": "computer"`. Partway through this task, after Claude has received a screenshot of the desktop, a response might look like this:
279279 
280280```json Output
281281{
from line 308
308308}
309309```
310310 
311Your application runs each call in order in your own environment, returns one `tool_result` block per `tool_use` block, and calls the API again; [How computer use works](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#how-computer-use-works) describes that loop, and the rest of this page shows how to implement it.
311Your application runs each call in order in your own environment, returns one `tool_result` block for each `tool_use` block, and calls the API again; [How computer use works](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#how-computer-use-works) describes that loop, and the rest of this page shows how to implement it.
312312 
313313***
314314 
from line 328
328328 
329329 <Step title="Run the calls in order and return results">
330330 * Iterate over every `tool_use` block in the response, in order. For each one, dispatch on the member `name` together with `toolset_name`, and perform that action with the block's `input` on your container or virtual machine.
331 * Continue the conversation with a new `user` message that contains one `tool_result` block per `tool_use` block, matched by `tool_use_id` and each echoing `"toolset_name": "computer"`. Return an image for `screenshot` and `zoom`; a short text such as `OK` is enough for the other actions.
331 * Continue the conversation with a new `user` message that contains one `tool_result` block for each `tool_use` block, matched by `tool_use_id` and each echoing `"toolset_name": "computer"`. Return an image for `screenshot` and `zoom`; a short text such as `OK` is enough for the other actions.
332332 * If an action fails, return `is_error: true` for that block and answer the rest of the batch as described in [Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions).
333333 </Step>
334334 
335335 <Step title="Claude continues until the task is complete">
336336 * Claude analyzes the tool results to determine if more actions are needed or the task has been completed.
337 * If Claude determines more actions are needed, it responds with another `tool_use` `stop_reason` and you should return to step 3.
337 * If Claude determines more actions are needed, it responds with another `tool_use` `stop_reason`; return to step 3.
338338 * Otherwise, it returns a text response to the user.
339339 </Step>
340340</Steps>
from line 376
376376}
377377```
378378 
379Return one `tool_result` block for each `tool_use` block, matched by `tool_use_id`, all in the next `user` message. Every result for a member tool must carry `"toolset_name": "computer"`; a result that omits it, or that names a different toolset than its `tool_use` block, is rejected. Only `screenshot` and `zoom` results need an image; for the other members, a short text acknowledgment such as `OK` is enough (`cursor_position` returns the coordinates as text):
379Return one `tool_result` block for each `tool_use` block, matched by `tool_use_id`, all in the next `user` message. Every result for a member tool must carry `"toolset_name": "computer"`; a result that omits it, or that names a different toolset from its `tool_use` block, is rejected. Only `screenshot` and `zoom` results need an image; for the other members, a short text acknowledgment such as `OK` is enough (`cursor_position` returns the coordinates as text):
380380 
381381```json
382382{
from line 429
429429}
430430```
431431 
432Claude then sees which actions succeeded, which one failed, and which were skipped, and replans on its next turn. A request that leaves any `tool_use` block in the batch unanswered is rejected with an `invalid_request_error`, so an agent loop that reads only the first block fails on its next call. If your application asks a human to confirm consequential actions, make that check before each block runs, because a batch can complete a multistep action within one turn.
432Claude then reads which actions succeeded, which one failed, and which were skipped, and replans on its next turn. A request that leaves any `tool_use` block in the batch unanswered is rejected with an `invalid_request_error`, so an agent loop that reads only the first block fails on its next call. If your application asks a human to confirm consequential actions, make that check before each block runs, because a batch can complete a multistep action within one turn.
433433 
434Claude typically finishes a batch with `screenshot` so it can observe the outcome before determining what to do next. When a batch doesn't end with one, your application can attach a screenshot as an extra `image` block on the last result in the batch so that Claude always sees the current state of the screen, which saves a round trip compared with waiting for Claude to ask. You can also prompt Claude to end every batch with a screenshot (see [Optimize model performance with prompting](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#optimize-model-performance-with-prompting)).
434Claude typically finishes a batch with `screenshot` so it can observe the outcome before determining what to do next. When a batch doesn't end with one, your application can attach a screenshot as an extra `image` block on the last result in the batch so that Claude always receives the current state of the screen, which saves a round trip compared with waiting for Claude to ask. You can also prompt Claude to end every batch with a screenshot (see [Optimize model performance with prompting](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#optimize-model-performance-with-prompting)).
435435 
436436### The computing environment
437437 
438438Computer use requires a sandboxed computing environment where Claude can safely interact with applications and the web. This environment includes:
439439 
4401. **Virtual display:** A virtual X11 display server (using Xvfb) that renders the desktop interface Claude will see through screenshots and control with mouse/keyboard actions.
4401. **Virtual display:** A virtual X11 display server (using Xvfb) that renders the desktop interface Claude sees through screenshots and controls with mouse/keyboard actions.
441441 
4424422. **Desktop environment:** A lightweight UI with window manager (Mutter) and panel (Tint2) running on Linux, which provides a consistent graphical interface for Claude to interact with.
443443 
from line 468
468468 
469469### Understand the agent loop
470470 
471The core of computer use is the "agent loop": a cycle where Claude requests tool actions, your application runs them, and returns results to Claude. The loop uses the client you created in the [Quick start](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#quick-start), a `tools` array that declares only the computer use toolset, and the tool-call processing helper under [Implement the computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#implement-the-computer-use-tool). If you also declare other tools, such as the Quick start's bash and text editor tools, dispatch their `tool_use` blocks in the same pass; the helper answers only computer use member calls, and the loop treats a turn with no answered calls as finished. Here's a simplified example:
471The core of computer use is the "agent loop": a cycle where Claude requests tool actions, and your application runs them and returns results to Claude. The loop uses the client you created in the [Quick start](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#quick-start), a `tools` array that declares only the computer use toolset, and the tool-call processing helper under [Implement the computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#implement-the-computer-use-tool). If you also declare other tools, such as the Quick start's bash and text editor tools, dispatch their `tool_use` blocks in the same pass; the helper answers only computer use member calls, and the loop treats a turn with no answered calls as complete. Here's a simplified example:
472472 
473473<CodeGroup exclude="shell">
474474 ```python Python
from line 862
862862}
863863```
864864 
865If your agent loop can run only one action per round trip, set `disable_parallel_tool_use` to `true` in `tool_choice`; Claude then returns at most one member `tool_use` block per turn (see [Disable parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use#disable-parallel-tool-use)).
865If your agent loop can run only one action for each round trip, set `disable_parallel_tool_use` to `true` in `tool_choice`; Claude then returns at most one member `tool_use` block for each turn (see [Disable parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use#disable-parallel-tool-use)).
866866 
867867The entry rejects these parameters from earlier tool versions, and a request that includes any of them returns an `invalid_request_error`:
868868 
from line 1565
15651565 </Step>
15661566 
15671567 <Step title="Implement the agent loop">
1568 Wrap the two previous steps in a loop that sends the results back and repeats until Claude returns no member tool calls; [Understand the agent loop](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#understanding-the-agentic-loop) shows this loop in each language.
1568 Wrap the two previous steps in a loop that sends the results back and repeats until Claude returns no member tool calls; [Understand the agent loop](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#understanding-the-agentic-loop) shows this loop.
15691569 </Step>
15701570</Steps>
15711571 
from line 1594
15941594 
15951595### Size screenshots to fit image limits
15961596 
1597Screenshots and zoom images that you return to the computer use toolset must already fit within your model's [image size limits](https://platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size): the toolset takes no display dimensions and the API doesn't downscale for you, so an oversized `tool_result` image is rejected with a validation error. Because Claude returns coordinates in the pixel space of the image it sees, keep the scale factor you used so you can map those coordinates back to your screen.
1597Screenshots and zoom images that you return to the computer use toolset must already fit within your model's [image size limits](https://platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size): the toolset takes no display dimensions and the API doesn't downscale for you, so an oversized `tool_result` image is rejected with a validation error. Because Claude returns coordinates in the pixel space of the image it receives, keep the scale factor you used so you can map those coordinates back to your screen.
15981598 
15991599<Note>
1600 Limits vary by model. Claude Opus 4.7 and later models, including every model that supports `computer_toolset_20260801`, accept up to 2576 pixels on the long edge and 4784 visual tokens total (`⌈width / 28⌉ × ⌈height / 28⌉`, approximately 3.75 megapixels); earlier models accept up to 1568 pixels on the long edge and approximately 1.15 megapixels total (see [Resolution and token cost](https://platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size) for each model's tier). The following example uses the earlier-model 1568 px / 1.15 MP limits. For a high-resolution-tier model, size to the visual-token limit rather than a pixel total, for example with the resize helper in [Resize your image before uploading](https://platform.claude.com/docs/en/build-with-claude/vision-coordinates#resize-your-image-before-uploading).
1600 Limits vary by model. Claude Opus 4.7 and later models, including every model that supports `computer_toolset_20260801`, accept up to 2576 pixels on the long edge and 4,784 visual tokens total (`⌈width / 28⌉ × ⌈height / 28⌉`, approximately 3.75 megapixels); earlier models accept up to 1568 pixels on the long edge and approximately 1.15 megapixels total (see [Resolution and token cost](https://platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size) for each model's tier). The following example uses the earlier-model 1568 px / 1.15 MP limits. For a high-resolution-tier model, size to the visual-token limit rather than a pixel total, for example with the resize helper in [Resize your image before uploading](https://platform.claude.com/docs/en/build-with-claude/vision-coordinates#resize-your-image-before-uploading).
16011601</Note>
16021602 
16031603If your screen is larger than the limit, resize each screenshot before returning it and scale Claude's returned coordinates back to the original screen space. Because the toolset takes no display dimensions, the resize and the coordinate scaling in your application code are all you need:
from line 1816
18161816 
18171817To keep [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) effective while bounding context:
18181818 
1819* Place one `cache_control` breakpoint after the system prompt and tool definitions, and up to three more on the last `tool_result` block of each of the most recent turns, advancing them each turn. Within a [batch action](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions), markers on several blocks act as a single breakpoint but each still counts toward the limit of four, so use one per turn.
1819* Place one `cache_control` breakpoint after the system prompt and tool definitions, and up to three more on the last `tool_result` block of each of the most recent turns, advancing them each turn. Within a [batch action](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions), markers on several blocks act as a single breakpoint but each still counts toward the limit of four, so use one for each turn.
18201820* Prune old screenshots in *batches*, not one each turn. Dropping a screenshot every turn changes the prefix every turn and invalidates the cache. A reasonable default is to keep the last three screenshots and prune every 25 turns, so the prefix stays byte-identical between prune events; if your screenshots exceed 2000 px on either side, choose an interval that keeps each request at 20 or fewer images.
18211821* On Claude Fable 5.1, Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5, avoid pruning on the client: removing an earlier screenshot [invalidates every later thinking block](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-in-conversation) in every request that still carries those turns. Resize screenshots to 2000 px or less per side instead, and use server-side [tool result clearing](https://platform.claude.com/docs/en/build-with-claude/context-editing#tool-result-clearing) to drop old ones from the context. If you must prune, keep [`prefix_mismatch_behavior: "drop_block"`](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-thinking-controls) set from then on; after each prune, Claude continues without the thinking produced since the pruned screenshot, on that request and every later one. On Claude Sonnet 5.5, `block_binding` works only with `thinking: {"type": "adaptive"}`. With `between_tools`, keep the history append-only, or strip the thinking blocks from the edited turn on. On Claude Haiku 5.5, `block_binding` works only with `thinking: {"type": "adaptive"}`; with `thinking: {"type": "disabled"}`, keep the history append-only, or strip the thinking blocks from the edited turn on.
18221822 
from line 2111
211121112. **Change the `tools` entry.** Set `type` to `computer_toolset_20260801` and delete `name`, `display_width_px`, `display_height_px`, `display_number`, and `enable_zoom`. The toolset rejects each of these fields.
211221123. **Choose whether to keep zoom enabled.** Zoom is enabled by default on the toolset, whereas `enable_zoom` defaults to `false`. If your environment doesn't implement zoom, add `"configs": {"zoom": {"enabled": false}}` to keep the previous behavior; otherwise implement it (see [Available actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#available-actions)).
211321134. **Handle every block in a turn.** Update your agent loop to iterate over every `tool_use` block in a response rather than reading only the first, and to dispatch on the block's `name` together with `toolset_name` instead of on `input.action`. Member inputs no longer contain an `action` field; the remaining fields are unchanged.
21145. **Run blocks in order and use the halt text.** Run the blocks sequentially, stop at the first failure, and answer the remaining blocks with `Not executed: an earlier computer action in this turn failed.` as described in [Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions). If your loop can't run batches yet, [Tool parameters](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#tool-parameters) explains how to limit Claude to one action per turn.
21145. **Run blocks in order and use the halt text.** Run the blocks sequentially, stop at the first failure, and answer the remaining blocks with `Not executed: an earlier computer action in this turn failed.` as described in [Batch actions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions). If your loop can't run batches yet, [Tool parameters](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#tool-parameters) explains how to limit Claude to one action for each turn.
211521156. **Echo `toolset_name` on results.** Add `"toolset_name": "computer"` to every `tool_result` that answers a member call. Results may contain only `text` and `image` content.
211621167. **Support `repeat` on `key`.** The `key` member accepts an optional `repeat` count from 1 to 100. A handler that ignores unrecognized fields would press the key once, so make your `key` handler honor `repeat`.
211721178. **Resize screenshots yourself.** The toolset rejects a screenshot or zoom image that exceeds the model's image limits instead of downscaling it. Resize before returning the image and keep scaling coordinates as described in [Size screenshots to fit image limits](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#handle-coordinate-scaling-for-higher-resolutions).
from line 2227
22272227 </Card>
22282228 
22292229 <Card title="Tool use with Claude" icon="tool" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">
2230 Connect Claude to external tools and APIs. See where tools execute, when Claude calls them, and which tool fits your task.
2230 Connect Claude to external tools and APIs. See where tools run, when Claude calls them, and which tool fits your task.
22312231 </Card>
22322232 
22332233 <Card title="Best practices in detail" icon="book" href="https://claude.com/blog/best-practices-for-computer-and-browser-use-with-claude">

agents-and-tools/tool-use/define-tools Changed · +21 / -21 lines

from line 17
1717 
1818Client tools are specified in the `tools` top-level parameter of the API request. Anthropic-schema client tools, such as the bash and text editor tools, are declared by a date-versioned `type`; see each tool's page, linked from the [Tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference), for the fields it accepts. The computer use and browser use tools are [client toolsets](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets): a single entry with no `name` that declares a fixed set of member tools. A user-defined tool definition includes:
1919 
20| Parameter | Description |
21| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22| `name` | The name of the tool. Must match the regex `^[a-zA-Z0-9_-]{1,128}$`. |
23| `description` | A detailed plaintext description of what the tool does, when it should be used, and how it behaves. |
24| `input_schema` | A [JSON Schema](https://json-schema.org/) object defining the expected parameters for the tool. |
25| `input_examples` | (Optional) An array of example input objects to help Claude understand how to use the tool. See [Providing tool use examples](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#providing-tool-use-examples). |
20| Parameter | Description |
21| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22| `name` | The name of the tool. Must match the regex `^[a-zA-Z0-9_-]{1,128}$`. |
23| `description` | A detailed plain text description of what the tool does, when it should be used, and how it behaves. |
24| `input_schema` | A [JSON Schema](https://json-schema.org/) object defining the expected parameters for the tool. |
25| `input_examples` | (Optional) An array of example input objects that show Claude how to use the tool. See [Providing tool use examples](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#providing-tool-use-examples). |
2626 
27For the full set of optional properties available on any single tool definition, including `cache_control`, `strict`, `defer_loading`, and `allowed_callers`, see the [Tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#tool-definition-properties). A client toolset entry accepts `cache_control` and `allowed_callers` on the entry and sets `defer_loading` per member; see [Client toolsets](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets).
27For the full set of optional properties available on any single tool definition, including `cache_control`, `strict`, `defer_loading`, and `allowed_callers`, see [Tool definition properties](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#tool-definition-properties). A client toolset entry accepts `cache_control` and `allowed_callers` on the entry and sets `defer_loading` for each member; see [Client toolsets](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets).
2828 
2929<Accordion title="Example simple tool definition">
3030 ```json JSON
from line 85
8585 
8686* **Design tool responses to return only high-signal information.** Return semantic, stable identifiers (for example, slugs or UUIDs) rather than opaque internal references, and include only the fields Claude needs to reason about its next step. Bloated responses waste context and make it harder for Claude to extract what matters.
8787 
88* **Ask for an explanation, not reasoning.** If a parameter asks Claude why it is making the call, ask for a short explanation or the supporting evidence. A parameter that asks for the model's thinking or step-by-step reasoning may lead to a `reasoning_extraction` refusal. See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
88* **Ask for an explanation, not reasoning.** If a parameter asks Claude why it is making the call, ask for a short explanation or the supporting evidence. A parameter that asks for the model's thinking or step-by-step reasoning might lead to a `reasoning_extraction` refusal. See [Keep reasoning in thinking blocks](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks).
8989 
9090<AccordionGroup>
9191 <Accordion title="Example of a good tool description">
from line 134
134134 
135135## Providing tool use examples
136136 
137You can provide concrete examples of valid tool inputs to help Claude understand how to use your tools more effectively. This is particularly useful for complex tools with nested objects, optional parameters, or format-sensitive inputs.
137You can provide concrete examples of valid tool inputs to show Claude how to use your tools more effectively. This is particularly useful for complex tools with nested objects, optional parameters, or format-sensitive inputs.
138138 
139139### Basic usage
140140 
from line 538
538538 ```
539539</CodeGroup>
540540 
541Examples are included in the prompt alongside your tool schema, showing Claude concrete patterns for well-formed tool calls. This helps Claude understand when to include optional parameters, what formats to use, and how to structure complex inputs.
541Examples are included in the prompt alongside your tool schema, showing Claude concrete patterns for well-formed tool calls. These patterns indicate when to include optional parameters, what formats to use, and how to structure complex inputs.
542542 
543543### Requirements and limitations
544544 
545* **Schema validation** - Each example must be valid according to the tool's `input_schema`. Invalid examples return a 400 error
546* **Not supported for server-side tools or client toolsets** - Input examples work on user-defined and Anthropic-schema client tools other than the [computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) and [browser use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool) toolsets, but not on server tools such as web search or code execution
547* **Token cost** - Examples add to prompt tokens: \~20–50 tokens for simple examples, \~100–200 tokens for complex nested objects
545* **Schema validation** - Each example must be valid according to the tool's `input_schema`. Invalid examples return a 400 error.
546* **Not supported for server-side tools or client toolsets** - Input examples work on user-defined and Anthropic-schema client tools other than the [computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) and [browser use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool) toolsets, but not on server tools such as web search or code execution.
547* **Token cost** - Examples add to prompt tokens: \~20–50 tokens for simple examples, \~100–200 tokens for complex nested objects.
548548 
549549## Controlling Claude's output
550550 
551551### Forcing tool use
552552 
553In some cases, you may want Claude to use a specific tool to answer the user's question, even if Claude would otherwise answer directly without calling a tool. You can do this by specifying the tool in the `tool_choice` field of the request.
553In some cases, you might want Claude to use a specific tool to answer the user's question, even if Claude would otherwise answer directly without calling a tool. You can do this by specifying the tool in the `tool_choice` field of the request.
554554 
555Not every model and setting supports forced tool use. Where it isn't supported, `tool_choice: {"type": "any"}` and `tool_choice: {"type": "tool", "name": "..."}` fail, while `tool_choice: {"type": "auto"}` (the default) and `tool_choice: {"type": "none"}` still work:
555Not every model and setting supports forced tool use. Where it isn't supported, `tool_choice: {"type": "any"}` and `tool_choice: {"type": "tool", "name": "..."}` fail, whereas `tool_choice: {"type": "auto"}` (the default) and `tool_choice: {"type": "none"}` still work:
556556 
557557| Model or setting | Restriction | What to use instead |
558558| --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
from line 836
836836 
837837When working with the `tool_choice` parameter, there are four possible options:
838838 
839* `auto` allows Claude to determine whether to call any provided tools or not. This is the default value when `tools` are provided.
839* `auto` allows Claude to determine whether to call any provided tools. This is the default value when `tools` are provided.
840840* `any` tells Claude that it must use one of the provided tools, but doesn't force a particular tool.
841841* `tool` forces Claude to always use a particular tool.
842842* `none` prevents Claude from using any tools. This is the default value when no `tools` are provided.
from line 889
889889 
890890This natural response style helps users understand what Claude is doing and creates a more conversational interaction. You can guide the style and content of these responses through your system prompts and by providing `<examples>` in your prompts.
891891 
892It's important to note that Claude may use various phrasings and approaches when explaining its actions. Your code should treat these responses like any other assistant-generated text, and not rely on specific formatting conventions.
892It's important to note that Claude might use various phrasings and approaches when explaining its actions. Your code should treat these responses like any other assistant-generated text, and not rely on specific formatting conventions.
893893 
894894## Next steps
895895 
896896<CardGroup>
897897 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls" title="Handle tool calls">
898 Parse tool\_use blocks and format tool\_result responses.
898 Parse `tool_use` blocks and format `tool_result` responses.
899899 </Card>
900900 
901 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner" title="Tool Runner (SDK)">
901 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner" title="Tool runner (SDK)">
902902 Let the SDK handle the agentic loop automatically.
903903 </Card>
904904 

agents-and-tools/tool-use/fine-grained-tool-streaming Changed · +6 / -6 lines

from line 486
486486 
487487The accumulation contract:
488488 
4891. On `content_block_start` with `type: "tool_use"`, initialize an empty string: `input_json = ""`
4902. For each `content_block_delta` with `type: "input_json_delta"`, append: `input_json += event.delta.partial_json`
4913. On `content_block_stop`, parse the accumulated string
4891. On `content_block_start` with `type: "tool_use"`, initialize an empty string: `input_json = ""`.
4902. For each `content_block_delta` with `type: "input_json_delta"`, append: `input_json += event.delta.partial_json`.
4913. On `content_block_stop`, parse the accumulated string.
492492 
493Guard the parse, as the following SDK examples do. A response can also stop at `max_tokens` midway through a parameter. Check the [stop reason](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons) and decide whether to retry the request with a higher `max_tokens` or repair the partial input.
493Guard the parse, as the following example does. A response can also stop at `max_tokens` midway through a parameter. Check the [stop reason](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons) and decide whether to retry the request with a higher `max_tokens` or repair the partial input.
494494 
495495The type mismatch between the initial `input: {}` (object) and `partial_json` (string) is by design. The empty object marks the slot in the content array. The delta strings build the real value.
496496 
from line 931
931931 </Card>
932932 
933933 <Card title="Handle tool calls" icon="arrows-left-right" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls">
934 Parse tool\_use blocks, format tool\_result responses, and handle errors with is\_error.
934 Parse `tool_use` blocks, format `tool_result` responses, and handle errors with `is_error`.
935935 </Card>
936936 
937937 <Card title="Tool reference" icon="book" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference">

agents-and-tools/tool-use/handle-tool-calls Changed · +19 / -19 lines

from line 14
1414 
1515## Handling results from client tools
1616 
17The response will have a `stop_reason` of `tool_use` and one or more `tool_use` content blocks that include:
17The response has a `stop_reason` of `tool_use` and one or more `tool_use` content blocks that include:
1818 
19* `id`: A unique identifier for this particular tool use block. This will be used to match up the tool results later.
19* `id`: A unique identifier for this particular tool use block. This is used to match up the tool results later.
2020* `name`: The name of the tool being used.
2121* `input`: An object containing the input being passed to the tool, conforming to the tool's `input_schema`.
2222 
from line 49
4949 
50501. Extract the `name`, `id`, and `input` from the `tool_use` block.
5151 
522. Run the actual tool in your codebase corresponding to that tool name, passing in the tool `input`.
522. Run the actual tool in your code base corresponding to that tool name, passing in the tool `input`.
5353 
54543. Continue the conversation by sending a new message with the `role` of `user`, and a `content` block containing the `tool_result` type and the following information:
5555 
from line 63
6363 **Important formatting requirements:**
6464 
6565 * Tool result blocks must immediately follow their corresponding tool use blocks in the message history. You cannot include any messages between the assistant's tool use message and the user's tool result message.
66 * In the user message containing tool results, the tool\_result blocks must come FIRST in the content array. Any text must come AFTER all tool results.
66 * In the user message containing tool results, the `tool_result` blocks must come FIRST in the content array. Any text must come AFTER all tool results.
6767 * If the assistant turn also called a [server tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools) that has no result block yet, the user message must contain only `tool_result` blocks. Text after the results ends the turn early; for a server tool Claude called directly, the request then fails with a 400 error that names the unresolved server tool. See [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use).
6868 
69 For example, this will cause a 400 error:
69 For example, this causes a 400 error:
7070 
7171 ```json
7272 {
from line 90
9090 }
9191 ```
9292 
93 If you receive an error like "tool\_use ids were found without tool\_result blocks immediately after", check that your tool results are formatted correctly.
93 If you receive an error such as "tool\_use ids were found without tool\_result blocks immediately after", check that your tool results are formatted correctly.
9494</Note>
9595 
9696<Warning>
97 Tool results often carry content from sources outside your control: web pages, inbound email, user uploads, third-party APIs. Treat that content as untrusted: an attacker who can influence it may embed instructions that try to redirect Claude (indirect prompt injection). Keep untrusted content inside `tool_result` blocks rather than `system` prompts or plain user `text` blocks, and see [Mitigate jailbreaks and prompt injections](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks#indirect-prompt-injection) for further hardening.
97 Tool results often carry content from sources outside your control: webpages, inbound email, user uploads, third-party APIs. Treat that content as untrusted: an attacker who can influence it might embed instructions that try to redirect Claude (indirect prompt injection). Keep untrusted content inside `tool_result` blocks rather than `system` prompts or plain user `text` blocks, and see [Mitigate jailbreaks and prompt injections](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks#indirect-prompt-injection) for further hardening.
9898</Warning>
9999 
100100<AccordionGroup>
from line 182
182182 
183183## Handling results from server tools
184184 
185Claude executes the tool internally and incorporates the results directly into its response without requiring additional user interaction.
185Claude runs the tool internally and incorporates the results directly into its response without requiring additional user interaction.
186186 
187187<Note>
188 A response can contain both a client `tool_use` block and a `server_tool_use` block that has no result block. That server tool call is not finished yet, and its result block arrives in a later response. Reply with a user message that contains only the `tool_result` blocks for the client tools and keep the same `tools` array; for a server tool Claude called directly, the API runs it on that request and the next response starts with its result block. See [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use).
188 A response can contain both a client `tool_use` block and a `server_tool_use` block that has no result block. That server tool call is not complete yet, and its result block arrives in a later response. Reply with a user message that contains only the `tool_result` blocks for the client tools and keep the same `tools` array; for a server tool Claude called directly, the API runs it on that request and the next response starts with its result block. See [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use).
189189</Note>
190190 
191191<Tip>
from line 193
193193 
194194 Unlike APIs that separate tool use or use special roles like `tool` or `function`, the Claude API integrates tools directly into the `user` and `assistant` message structure.
195195 
196 Messages contain arrays of `text`, `image`, `tool_use`, and `tool_result` blocks. `user` messages include client content and `tool_result`, while `assistant` messages contain AI-generated content and `tool_use`.
196 Messages contain arrays of `text`, `image`, `tool_use`, and `tool_result` blocks. `user` messages include client content and `tool_result`, whereas `assistant` messages contain AI-generated content and `tool_use`.
197197</Tip>
198198 
199199## Handling errors with is\_error
from line 221
221221 Claude will then incorporate this error into its response to the user. For example: "I'm sorry, I was unable to retrieve the current weather because the weather service API is not available. Please try again later."
222222 
223223 <Tip>
224 Write instructive error messages. Instead of generic errors like `"failed"`, include what went wrong and what Claude should try next (for example, `"Rate limit exceeded. Retry after 60 seconds."`). This gives Claude the context it needs to recover or adapt without guessing.
224 Write instructive error messages. Instead of generic errors such as `"failed"`, include what went wrong and what Claude should try next (for example, `"Rate limit exceeded. Retry after 60 seconds."`). This gives Claude the context it needs to recover or adapt without guessing.
225225 </Tip>
226226 </Accordion>
227227 
228228 <Accordion title="Invalid tool name">
229 If Claude's attempted use of a tool is invalid (for example, missing required parameters), it usually means that there wasn't enough information for Claude to use the tool correctly. Your best bet during development is to try the request again with more-detailed `description` values in your tool definitions.
229 If Claude's attempted use of a tool is invalid (for example, missing required parameters), it usually means that there wasn't enough information for Claude to use the tool correctly. The best approach during development is to try the request again with more-detailed `description` values in your tool definitions.
230230 
231 However, you can also continue the conversation forward with a `tool_result` that indicates the error, and Claude will try to use the tool again with the missing information filled in:
231 However, you can also continue the conversation forward with a `tool_result` that indicates the error, and Claude will attempt to use the tool again with the missing information filled in:
232232 
233233 ```json JSON
234234 {
from line 244
244244 }
245245 ```
246246 
247 If a tool request is invalid or missing parameters, Claude will retry 2-3 times with corrections before apologizing to the user.
247 If a tool request is invalid or missing parameters, Claude will retry 2–3 times with corrections before apologizing to the user.
248248 
249249 <Tip>
250 To eliminate invalid tool calls entirely, use [strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use) with `strict: true` on your tool definitions. This guarantees that tool inputs will always match your schema exactly, preventing missing parameters and type mismatches.
250 To eliminate invalid tool calls entirely, use [strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use) with `strict: true` on your tool definitions. This guarantees that tool inputs always match your schema exactly, preventing missing parameters and type mismatches.
251251 </Tip>
252252 </Accordion>
253253 
254254 <Accordion title="Server tool errors">
255 When server tools encounter errors (for example, network issues with Web Search), Claude will transparently handle these errors and attempt to provide an alternative response or explanation to the user. Unlike client tools, you do not need to handle `is_error` results for server tools.
255 When server tools encounter errors (for example, network issues with web search), Claude will transparently handle these errors and attempt to provide an alternative response or explanation to the user. Unlike client tools, you do not need to handle `is_error` results for server tools.
256256 
257257 For web search specifically, possible error codes include:
258258 
from line 271
271271 Handle responses where Claude calls several tools in a single turn.
272272 </Card>
273273 
274 <Card title="Tool Runner (SDK)" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner">
274 <Card title="Tool runner (SDK)" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner">
275275 Let the SDK manage the `tool_use` loop, result formatting, and retries for you.
276276 </Card>
277277 

agents-and-tools/tool-use/how-tool-use-works Changed · +10 / -10 lines

from line 1
11---
22title: How tool use works
33url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works
4description: Understand the tool use loop, where tools execute, and when to use tools instead of prose.
4description: Understand the tool use loop, where tools run, and when to use tools instead of prose.
55---
66 
77This page explains the concepts behind tool use: where tools run, how the agentic loop works, and when tool use is the right approach. For hands-on guidance, start with the [Build a tool-using agent](https://platform.claude.com/docs/en/agents-and-tools/tool-use/build-a-tool-using-agent) tutorial or the [Define tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools) guide.
from line 8
88 
99## The tool-use contract
1010 
11Tool use is a contract between your application and the model. You specify what operations are available and what shape their inputs and outputs take; Claude determines when and how to call them. The model never executes anything on its own. It emits a structured request, your code (or Anthropic's servers) runs the operation, and the result flows back into the conversation.
11Tool use is a contract between your application and the model. You specify what operations are available and what shape their inputs and outputs take; Claude determines when and how to call them. The model never runs anything on its own. It emits a structured request, your code (or Anthropic's servers) runs the operation, and the result flows back into the conversation.
1212 
1313This contract makes the model behave less like a text generator and more like a function you call. Engineers with classical API experience can integrate tool use the same way they would any other typed interface: define the schema, handle the callback, return a result. The difference is that the caller on the other side is a language model choosing which function to call based on the conversation.
1414 
1515## Where tools run
1616 
17The primary axis along which tools differ is where the code executes. Every tool falls into one of three buckets, and the bucket determines what your application is responsible for.
17The primary axis along which tools differ is where the code runs. Every tool falls into one of three buckets, and the bucket determines what your application is responsible for.
1818 
1919### User-defined tools (client-executed)
2020 
21You write the schema, you execute the code, you return the results. This is the most common case: the vast majority of tool-use traffic is [user-defined tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools) calling into application-specific logic.
21You write the schema, run the code, and return the results. This is the most common case: the vast majority of tool-use traffic is [user-defined tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools) calling into application-specific logic.
2222 
23When Claude calls one of your tools, the API response contains a `tool_use` block with the tool name and a JSON object of arguments. Your application extracts those arguments, runs the operation (a database query, an HTTP call, a file write, whatever the tool does), and sends the output back in a `tool_result` block on the next request. Claude never sees your implementation; it only sees the schema you provided and the result you returned.
23When Claude calls one of your tools, the API response contains a `tool_use` block with the tool name and a JSON object of arguments. Your application extracts those arguments, runs the operation (a database query, an HTTP call, a file write, whatever the tool does), and sends the output back in a `tool_result` block on the next request. Claude never receives your implementation; it only receives the schema you provided and the result you returned.
2424 
2525### Anthropic-schema tools (client-executed)
2626 
from line 30
3030 
3131### Server-executed tools
3232 
33For [`web_search`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool), [`web_fetch`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool), [`code_execution`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool), and [`tool_search`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool), Anthropic runs the code. You enable the tool in your request and the server handles everything else. You never construct a `tool_result` block for these tools. When a turn calls only [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), the server-side loop executes the operation and feeds the output back to the model before the response reaches you, unless the loop stops before it finishes, most often because it pauses.
33For [`web_search`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool), [`web_fetch`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool), [`code_execution`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool), and [`tool_search`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool), Anthropic runs the code. You enable the tool in your request and the server handles everything else. You never construct a `tool_result` block for these tools. When a turn calls only [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), the server-side loop runs the operation and feeds the output back to the model before the response reaches you, unless the loop stops before it completes, most often because it pauses.
3434 
3535The response you receive contains `server_tool_use` blocks showing what ran and what came back. In the common case, execution is already complete by the time you see them, and your application's job is to enable the tool and read the final answer rather than to participate in the execution loop; the main exceptions are a paused loop ([`pause_turn`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works#the-server-side-loop)) and a turn that also calls a client tool.
3636 
from line 42
4242 
43431. Send a request with your `tools` array and the user message.
44442. Claude responds with `stop_reason: "tool_use"` and one or more `tool_use` blocks.
453. Execute each tool. Format the outputs as `tool_result` blocks.
453. Run each tool. Format the outputs as `tool_result` blocks.
46464. Send a new request containing the original messages, the assistant's response, and a user message with the `tool_result` blocks.
47475. Repeat from step 2 while `stop_reason` is `"tool_use"`.
4848 
49In practice this reads as: while `stop_reason == "tool_use"`, execute the tools and continue the conversation. The loop exits on any other stop reason (`"end_turn"`, `"max_tokens"`, `"stop_sequence"`, or `"refusal"`), which means Claude has either produced a final answer or stopped for another reason that your application should handle.
49In practice this reads as: while `stop_reason == "tool_use"`, run the tools and continue the conversation. The loop exits on any other stop reason (`"end_turn"`, `"max_tokens"`, `"stop_sequence"`, or `"refusal"`), which means Claude has either produced a final answer or stopped for another reason that your application should handle.
5050 
5151For the mechanics of building requests, handling parallel tool calls, and formatting results, see [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls).
5252 
from line 54
5454 
5555Server-executed tools run their own loop inside Anthropic's infrastructure. A single request from your application might trigger several web searches or code executions before a response comes back. The model searches, reads results, determines whether to search again, and iterates until it has what it needs, all without your application participating.
5656 
57This internal loop has an iteration limit. If the model is still iterating when it hits the cap, the response comes back with `stop_reason: "pause_turn"` instead of `"end_turn"`. A paused turn means the work isn't finished; re-send the conversation (including the paused response) to let the model continue where it left off. See [Server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools) for the continuation pattern.
57This internal loop has an iteration limit. If the model is still iterating when it hits the cap, the response comes back with `stop_reason: "pause_turn"` instead of `"end_turn"`. A paused turn means the work isn't complete; re-send the conversation (including the paused response) to let the model continue where it left off. See [Server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools) for the continuation pattern.
5858 
5959The loop also hands control back to you before a server tool runs if Claude calls that server tool and a client tool in the same group of parallel tool calls. The response then comes back with `stop_reason: "tool_use"` and a `server_tool_use` block that has no result block yet; the API runs it after you return the client tool results. See [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use) for the exact contract.
6060 
from line 72
7272Tool use doesn't fit when:
7373 
7474* The model can answer from training alone. Summarization, translation, and general-knowledge questions don't need a tool round trip.
75* The interaction is one-shot Q\&A with no side effects. If there's nothing to execute, there's nothing for a tool to do.
75* The interaction is one-shot Q\&A with no side effects. If there's nothing to run, there's nothing for a tool to do.
7676* Tool-calling latency would dominate a trivial response. Every tool call is at least one extra round trip; for lightweight tasks the overhead can exceed the work.
7777 
7878## Choosing between approaches

agents-and-tools/tool-use/manage-tool-context Changed · +5 / -5 lines

from line 1
11---
22title: Manage tool context
33url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/manage-tool-context
4description: Choose between tool search, programmatic tool calling, prompt caching, and context editing to manage context bloat.
4description: Choose among tool search, programmatic tool calling, prompt caching, and context editing to manage context bloat.
55---
66 
7Tool definitions and accumulated `tool_result` blocks consume your context window. Long-running agents with many tools or many turns can exhaust available context before the task is finished. Four approaches address this at different points in the pipeline.
7Tool definitions and accumulated `tool_result` blocks consume your context window. Long-running agents with many tools or many turns can exhaust available context before the task is complete. Four approaches address this at different points in the pipeline.
88 
99## The four approaches
1010 
from line 13
1313| Approach | What it reduces | When it fits | Learn more |
1414| ------------------------- | --------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
1515| Tool search | Tool definitions loaded upfront | Large toolsets (20+ tools) where most tools aren't needed every turn | [Tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) |
16| Programmatic tool calling | `tool_result` roundtrips | Chains of tool calls that can execute as a single script | [Programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) |
16| Programmatic tool calling | `tool_result` roundtrips | Chains of tool calls that can run as a single script | [Programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) |
1717| Prompt caching | Token cost of repeated tool definitions | Stable toolsets across many requests | [Tool use with prompt caching](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-use-with-prompt-caching) |
1818| Context editing | Old `tool_result` blocks in history | Long conversations where early results are no longer relevant | [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) |
1919 
from line 31
3131 
3232### Context editing
3333 
34Context editing removes old `tool_result` blocks from the conversation history once they've served their purpose. A long agent loop might produce hundreds of intermediate results that were useful at the time but are now dead weight. Context editing lets you trim them without restarting the conversation.
34Context editing removes old `tool_result` blocks from the conversation history once they've served their purpose. A long agent loop might produce hundreds of intermediate results that were useful at the time but are no longer needed. Context editing lets you trim them without restarting the conversation.
3535 
3636## Combining approaches
3737 
from line 39
3939 
4040A reasonable starting point for a high-volume agent:
4141 
421. Enable prompt caching on your tool definitions from day one. Cache writes carry a 25% markup over base input pricing, which pays back on the second request that hits the cache.
421. Enable prompt caching on your tool definitions from the start. Cache writes carry a 25 percent markup over base input pricing, which pays back on the second request that hits the cache.
43432. Add tool search once your toolset grows past roughly 20 tools or your baseline context usage becomes noticeable.
44443. Add context editing once individual conversations start running long enough that early results become irrelevant.
45454. Consider programmatic tool calling if you notice repetitive chains of small tool calls that could run as a single batch.

agents-and-tools/tool-use/memory-tool Changed · +10 / -10 lines

from line 8
88 
99Memory supports just-in-time context retrieval. Rather than loading all relevant information up front, an agent records what it learns in memory files and reads them back on demand. This keeps the active context focused on the current task, which matters for long-running sessions that would otherwise overwhelm the context window. See [Effective context engineering](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) for the broader pattern.
1010 
11The memory tool operates client-side: Claude requests file operations, and your application executes them. You control where and how the data is stored through your own infrastructure.
11The memory tool operates client-side: Claude requests file operations, and your application runs them. You control where and how the data is stored through your own infrastructure.
1212 
1313<Note>
14 Reach out through the [feedback form](https://forms.gle/YXC2EKGMhjN1c4L88) to share your feedback on this feature.
14 Use the [feedback form](https://forms.gle/YXC2EKGMhjN1c4L88) to share your feedback on this feature.
1515</Note>
1616 
1717<Note>
from line 28
2828 
2929When the memory tool is enabled, Claude automatically checks its memory directory before starting a task. As it works, Claude stores what it learns in files under `/memories` and reads them back in later conversations to continue earlier work.
3030 
31Because the memory tool is client-side, Claude only requests memory operations. Your application executes each request against storage you control and returns the result in a `tool_result` block (see [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls)). The `/memories` path is a prefix that your handler maps onto real storage, such as a per-user directory or keys in a database. Memory lives entirely in your application. A later conversation continues from the same memory when it sends the same `tools` entry and your handler serves the same store. For security, restrict all memory operations to the `/memories` directory (see [Path traversal protection](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool#path-traversal-protection)).
31Because the memory tool is client-side, Claude only requests memory operations. Your application runs each request against storage you control and returns the result in a `tool_result` block (see [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls)). The `/memories` path is a prefix that your handler maps onto real storage, such as a per-user directory or keys in a database. Memory lives entirely in your application. A later conversation continues from the same memory when it sends the same `tools` entry and your handler serves the same store. For security, restrict all memory operations to the `/memories` directory (see [Path traversal protection](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool#path-traversal-protection)).
3232 
3333### Example: How memory tool calls work
3434 
from line 279
279279 
280280## Implement the memory handler
281281 
282Claude's reply to a request like the previous one ends with a `tool_use` block that requests a memory operation, such as `view /memories`. Your application executes the operation and returns the result in a `tool_result` block, then sends the conversation back so Claude can continue: the standard [tool-use loop](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls).
282Claude's reply to a request like the previous one ends with a `tool_use` block that requests a memory operation, such as `view /memories`. Your application runs the operation and returns the result in a `tool_result` block, then sends the conversation back so Claude can continue: the standard [tool-use loop](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls).
283283 
284284Four SDKs provide memory tool helpers that handle the tool interface and the loop. Subclass `BetaAbstractMemoryTool` (Python and C#), use `betaMemoryTool` (TypeScript), or implement `BetaMemoryToolHandler` (Java) to back memory with your own storage, such as files on disk, a database, cloud storage, or encrypted files. Python and TypeScript also ship a ready-made local-filesystem implementation, `BetaLocalFilesystemMemoryTool`. The helper and tool-runner surfaces live in your SDK's beta namespace even though the memory tool itself doesn't require a beta header. The Go and Ruby SDKs have no memory helper, so those examples run the tool-use loop themselves, and PHP wraps your handler closure in its generic `BetaRunnableTool`. All three use an in-memory store that you replace with your own storage.
285285 
from line 733
733733 
734734#### Return values
735735 
736**For directories:** Return a listing that shows files and directories with their sizes:
736**For directories:** Return a list that shows files and directories with their sizes:
737737 
738738```text
739739Here're the files and directories up to 2 levels deep in {path}, excluding hidden items and node_modules:
from line 747
747747* Excludes hidden items (files starting with `.`) and `node_modules`
748748* Uses a tab character between the size and the path
749749 
750The first `view` of `/memories` on an empty store is not an error. Where your SDK ships a local-filesystem memory tool, `BetaLocalFilesystemMemoryTool`, it creates the memory root before Claude's first call and returns the listing header followed by a single size-and-path line for the empty directory itself.
750The first `view` of `/memories` on an empty store is not an error. Where your SDK ships a local-filesystem memory tool, `BetaLocalFilesystemMemoryTool`, it creates the memory root before Claude's first call and returns the list header followed by a single size-and-path line for the empty directory itself.
751751 
752752**For files:** Return file contents with a header and line numbers:
753753 
from line 929
929929 
930930## Security considerations
931931 
932Your application executes every file operation Claude requests, so these safeguards are your responsibility:
932Your application runs every file operation Claude requests, so these safeguards are your responsibility:
933933 
934934### Sensitive information
935935 
from line 986
986986 
987987### How the pattern works
988988 
9891. **Initializer session:** The first session sets up the memory files before any substantive work begins. This includes a progress log (tracking what has been done and what comes next), a feature checklist (defining the scope of work), and a reference to any startup or initialization script the project needs.
9891. **Initializer session:** The first session sets up the memory files before any substantive work starts. This includes a progress log (tracking what has been done and what comes next), a feature checklist (defining the scope of work), and a reference to any startup or initialization script the project needs.
990990 
9919912. **Subsequent sessions:** Each new session opens by reading those memory files. This restores the project state without re-exploring the code base or retracing earlier decisions.
992992 
from line 997
997997Work on one feature at a time. Mark a feature complete only after end-to-end verification confirms it works, not when the code is written. This keeps the progress log accurate from session to session.
998998 
999999<Tip>
1000 For a detailed case study of this pattern in practice, including the initializer script, progress file structure, and git-based recovery, see [Effective harnesses for long-running agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents).
1000 For a detailed case study of this pattern in practice, including the initializer script, progress file structure, and Git-based recovery, see [Effective harnesses for long-running agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents).
10011001</Tip>
10021002 
10031003## Next steps
from line 1004
10041004 
10051005<CardGroup cols={2}>
10061006 <Card title="Bash tool" icon="terminal" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool">
1007 Execute shell commands in a persistent bash session.
1007 Run shell commands in a persistent bash session.
10081008 </Card>
10091009 
10101010 <Card title="Context editing" icon="edit" href="https://platform.claude.com/docs/en/build-with-claude/context-editing">

agents-and-tools/tool-use/overview Changed · +12 / -12 lines

from line 1
11---
22title: Tool use with Claude
33url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview
4description: Connect Claude to external tools and APIs. See where tools execute, when Claude calls them, and which tool fits your task.
4description: Connect Claude to external tools and APIs. See where tools run, when Claude calls them, and which tool fits your task.
55---
66 
7Tool use (also called function calling) lets Claude call functions that you define or that Anthropic provides. Claude determines when to call a tool based on the user's request and the tool's description. It then returns a structured call that your application executes (client tools) or that Anthropic executes (server tools).
7Tool use (also called function calling) lets Claude call functions that you define or that Anthropic provides. Claude determines when to call a tool based on the user's request and the tool's description. It then returns a structured call that your application runs (client tools) or that Anthropic runs (server tools).
88 
9Here's a minimal example using a server tool, the [Web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool), which Anthropic executes for you:
9Here's a minimal example using a server tool, the [Web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool), which Anthropic runs for you:
1010 
1111<CodeGroup>
1212 ```bash cURL
from line 134
134134 ```
135135</CodeGroup>
136136 
137Claude runs the search on Anthropic's infrastructure and returns the cited results in the same response. To have Claude call a function that you define, pass a tool with an `input_schema`, then execute the call when Claude returns a `tool_use` block. [How tool use works](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview#how-tool-use-works) shows that round trip end to end. Learn more about [defining tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools) and [handling tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls).
137Claude runs the search on Anthropic's infrastructure and returns the cited results in the same response. To have Claude call a function that you define, pass a tool with an `input_schema`, then run the call when Claude returns a `tool_use` block. The [client tool example](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview#how-tool-use-works) shows that round trip end to end. Learn more about [defining tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools) and [handling tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls).
138138 
139139## How tool use works
140140 
141Tools differ primarily by where the code executes. **Client tools** (including user-defined tools and tools with Anthropic-defined schemas, such as `bash` and `text_editor`) run in your application. Claude responds with `stop_reason: "tool_use"` and one or more `tool_use` blocks. Your code executes the operation and sends back a `tool_result`. **Server tools** (such as `web_search`, `web_fetch`, `code_execution`, and `tool_search`) run on Anthropic's infrastructure: you see the results directly without handling execution, unless Claude calls the tool in the same group of parallel tool calls as one of your client tools (see [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use)).
141Tools differ primarily by where the code runs. **Client tools** (including user-defined tools and tools with Anthropic-defined schemas, such as `bash` and `text_editor`) run in your application. Claude responds with `stop_reason: "tool_use"` and one or more `tool_use` blocks. Your code runs the operation and sends back a `tool_result`. **Server tools** (such as `web_search`, `web_fetch`, `code_execution`, and `tool_search`) run on Anthropic's infrastructure: you see the results directly without handling execution, unless Claude calls the tool in the same group of parallel tool calls as one of your client tools (see [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use)).
142142 
143143Here's that round trip in full for a client tool. The first request defines a `get_weather` tool, and Claude answers the question by calling it: the response carries a `tool_use` block, your code runs the lookup, and a second request sends the result back in a `tool_result` block so Claude can reply with the answer.
144144 
from line 627
627627The current weather in San Francisco is 15 degrees Celsius with partly cloudy skies.
628628```
629629 
630[Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) covers each step in detail, including result formatting and error signaling; [Parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use) covers responses that call several tools at once. To skip writing this round trip yourself, use [Tool Runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner): the SDK executes your tools and sends the results back automatically.
630[Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) covers each step in detail, including result formatting and error signaling; [Parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use) covers responses that call several tools at once. To skip writing this round trip yourself, use [Tool Runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner): the SDK runs your tools and sends the results back automatically.
631631 
632632For the full conceptual model including the agentic loop and when to choose each approach, see [How tool use works](https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works).
633633 
from line 672
672672 
673673### Your own tools
674674 
675For tools you define, you write the schema and your application executes each call.
675For tools you define, you write the schema and your application runs each call.
676676 
677677<CardGroup cols={2}>
678678 <Card title="Define tools" icon="hammer" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools">
from line 686
686686 
687687### Anthropic-schema client tools
688688 
689Anthropic publishes the schema and trains Claude on it. Your application still executes each call and returns the `tool_result`.
689Anthropic publishes the schema and trains Claude on it. Your application still runs each call and returns the `tool_result`.
690690 
691691<CardGroup cols={2}>
692692 <Card title="Memory tool" icon="brain" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool">
from line 720
720720 </Card>
721721 
722722 <Card title="Web fetch tool" icon="download" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool">
723 Retrieve the full content of specified web pages and PDF documents.
723 Retrieve the full content of specified webpages and PDF documents.
724724 </Card>
725725 
726726 <Card title="Code execution tool" icon="code" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool">
727 Run Python and bash code in a sandboxed container to analyze data and generate files.
727 Run Python and Bash code in a sandboxed container to analyze data and generate files.
728728 </Card>
729729 
730730 <Card title="Advisor tool" icon="lightbulb" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool">
from line 797
797797 
798798<CardGroup cols={3}>
799799 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works" title="How tool use works" icon="compass">
800 Understand the tool use loop, where tools execute, and when to use tools instead of prose.
800 Understand the tool use loop, where tools run, and when to use tools instead of prose.
801801 </Card>
802802 
803803 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/build-a-tool-using-agent" title="Tutorial: Build a tool-using agent" icon="graduation-cap">

agents-and-tools/tool-use/parallel-tool-use Changed · +8 / -8 lines

from line 738
738738 
739739 puts "Requesting parallel tool calls..."
740740 response = client.messages.create(
741 model: "claude-opus-5-5",
741 model: Anthropic::Model::CLAUDE_OPUS_5_5,
742742 max_tokens: 1024,
743743 messages: [
744744 { role: "user", content: "What's the weather in SF and NYC, and what time is it there?" }
from line 776
776776 
777777 puts "\nGetting final response..."
778778 final_response = client.messages.create(
779 model: "claude-opus-5-5",
779 model: Anthropic::Model::CLAUDE_OPUS_5_5,
780780 max_tokens: 1024,
781781 messages: [
782782 { role: "user", content: "What's the weather in SF and NYC, and what time is it there?" },
from line 847
847847 
848848### At most one tool call
849849 
850When `tool_choice` type is `auto` (the default), setting `disable_parallel_tool_use: true` means Claude calls at most one tool per response. Claude can still answer in plain text without calling any tool. The highlighted lines are the only change from a standard tool use request:
850When `tool_choice` type is `auto` (the default), setting `disable_parallel_tool_use: true` means Claude calls at most one tool in each response. Claude can still answer in plain text without calling any tool. The highlighted lines are the only change from a standard tool use request:
851851 
852852<CodeGroup>
853853 ```bash cURL
from line 1099
10991099 client = Anthropic::Client.new
11001100 
11011101 response = client.messages.create(
1102 model: "claude-opus-5-5",
1102 model: Anthropic::Model::CLAUDE_OPUS_5_5,
11031103 max_tokens: 1024,
11041104 tools: [
11051105 {
from line 1380
13801380 client = Anthropic::Client.new
13811381 
13821382 response = client.messages.create(
1383 model: "claude-opus-5",
1383 model: Anthropic::Model::CLAUDE_OPUS_5,
13841384 max_tokens: 1024,
13851385 tools: [
13861386 {
from line 1575
15751575## Next steps
15761576 
15771577<CardGroup cols={3}>
1578 <Card title="Tool Runner (SDK)" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner">
1579 Use the SDK's Tool Runner abstraction to handle the agentic loop, error wrapping, and type safety automatically.
1578 <Card title="Tool runner (SDK)" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner">
1579 Use the SDK's tool runner abstraction to handle the agentic loop, error wrapping, and type safety automatically.
15801580 </Card>
15811581 
15821582 <Card title="Handle tool calls" icon="arrows-left-right" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls">
1583 Parse tool\_use blocks, format tool\_result responses, and handle errors with is\_error.
1583 Parse `tool_use` blocks, format `tool_result` responses, and handle errors with `is_error`.
15841584 </Card>
15851585 
15861586 <Card title="Define tools" icon="hammer" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools">

agents-and-tools/tool-use/programmatic-tool-calling Changed · +80 / -80 lines

from line 32
3232 - Claude Haiku 4.5 accepts the `code_execution_20260120` and later tool versions but doesn't support programmatic tool calling.
3333---
3434 
35Programmatic tool calling allows Claude to write code that calls your tools programmatically within a [code execution](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) container, rather than requiring round trips through the model for each tool invocation. This reduces latency for multi-tool workflows and decreases token consumption by allowing Claude to filter or process data before it reaches the model's context window. On agentic search benchmarks like [BrowseComp](https://arxiv.org/abs/2504.12516) and [DeepSearchQA](https://github.com/google-deepmind/deepsearchqa), which test multistep web research and complex information retrieval, adding programmatic tool calling on top of basic search tools improved performance by an average of 11% while using 24% fewer input tokens (see [Improved web search with dynamic filtering](https://claude.com/blog/improved-web-search-with-dynamic-filtering)).
35Programmatic tool calling allows Claude to write code that calls your tools programmatically within a [code execution](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) container, rather than requiring round trips through the model for each tool call. This reduces latency for multi-tool workflows and decreases token consumption by allowing Claude to filter or process data before it reaches the model's context window. On agentic search benchmarks such as [BrowseComp](https://arxiv.org/abs/2504.12516) and [DeepSearchQA](https://github.com/google-deepmind/deepsearchqa), which test multistep web research and complex information retrieval, adding programmatic tool calling on top of basic search tools improved performance by an average of 11 percent while using 24 percent fewer input tokens (see [Improved web search with dynamic filtering](https://claude.com/blog/improved-web-search-with-dynamic-filtering)).
3636 
37Consider checking budget compliance across 20 employees: the traditional approach requires 20 separate model round-trips, pulling thousands of expense line items into the context along the way. With programmatic tool calling, a single script runs all 20 lookups, filters the results, and returns only the employees who exceeded their limits, shrinking what Claude needs to reason over from hundreds of kilobytes down to a handful of lines.
37Consider checking budget compliance across 20 employees: the traditional approach requires 20 separate model round-trips, pulling thousands of expense line items into the context along the way. With programmatic tool calling, a single script runs all 20 lookups, filters the results, and returns only the employees who exceeded their limits, shrinking what Claude needs to reason over from hundreds of kilobytes down to a few lines.
3838 
3939<Tip>
4040 For a deeper look at the inference and context costs that programmatic tool calling addresses, see [Advanced tool use](https://www.anthropic.com/engineering/advanced-tool-use).
from line 49
4949<CodeGroup>
5050 ```bash cURL
5151 curl https://api.anthropic.com/v1/messages \
52 --header "x-api-key: $ANTHROPIC_API_KEY" \
53 --header "anthropic-version: 2023-06-01" \
54 --header "content-type: application/json" \
55 --data '{
52 -H "x-api-key: $ANTHROPIC_API_KEY" \
53 -H "anthropic-version: 2023-06-01" \
54 -H "content-type: application/json" \
55 -d '{
5656 "model": "claude-opus-5-5",
5757 "max_tokens": 4096,
5858 "messages": [
from line 326
326326 client = Anthropic::Client.new
327327 
328328 message = client.messages.create(
329 model: "claude-opus-5-5",
329 model: Anthropic::Model::CLAUDE_OPUS_5_5,
330330 max_tokens: 4096,
331331 messages: [
332332 {
from line 361
361361 ```
362362</CodeGroup>
363363 
364The response stops with `stop_reason: "tool_use"`, a `container` ID, and a `tool_use` block for `query_database` whose `caller` field identifies the code execution run that called it. Return the result as shown in [Step 3 of the example workflow](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling#step-3-provide-tool-result) so the code can finish.
364The response stops with `stop_reason: "tool_use"`, a `container` ID, and a `tool_use` block for `query_database` whose `caller` field identifies the code execution run that called it. Return the result as shown in [Step 3 of the example workflow](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling#step-3-provide-tool-result) so the code can complete.
365365 
366366## How programmatic tool calling works
367367 
368368When you configure a tool to be callable from code execution and Claude determines that tool is needed:
369369 
3701. Claude writes Python code that invokes the tool as a function, potentially including multiple tool calls and pre/post-processing logic
3712. Claude runs this code in a sandboxed container through code execution
3723. When a tool function is called, code execution pauses and the API returns a `tool_use` block
3734. You provide the tool result, and code execution continues (intermediate results are not loaded into Claude's context window)
3745. Once all code execution completes, Claude receives the final output and continues working on the task
3701. Claude writes Python code that invokes the tool as a function, potentially including multiple tool calls and pre/post-processing logic.
3712. Claude runs this code in a sandboxed container through code execution.
3723. When a tool function is called, code execution pauses and the API returns a `tool_use` block.
3734. You provide the tool result, and code execution continues (intermediate results are not loaded into Claude's context window).
3745. Once all code execution completes, Claude receives the final output and continues working on the task.
375375 
376376This approach is particularly useful for:
377377 
378* **Large data processing:** Filter or aggregate tool results before they reach Claude's context
379* **Multistep workflows:** Save tokens and latency by calling tools serially or in a loop without sampling Claude in-between tool calls
380* **Conditional logic:** Make decisions based on intermediate tool results
378* **Large data processing:** Filter or aggregate tool results before they reach Claude's context.
379* **Multistep workflows:** Save tokens and latency by calling tools serially or in a loop without sampling Claude in-between tool calls.
380* **Conditional logic:** Make decisions based on intermediate tool results.
381381 
382382<Note>
383383 Tools that allow a code execution caller are exposed to Claude's code as async Python functions, so Claude can run them in parallel with `asyncio.gather`. Each function takes a single dict of arguments and returns a string: the text of the `tool_result` you send back. Claude's code awaits these functions with top-level `await` and parses results that it needs as structured data, for example `rows = json.loads(await query_database({"sql": "<sql>"}))`.
from line 387
387387 
388388### The `allowed_callers` field
389389 
390The `allowed_callers` field specifies which contexts can invoke a tool:
390The `allowed_callers` field specifies which contexts can call a tool:
391391 
392392```json
393393{
from line 402
402402 
403403**Possible values:**
404404 
405* `["direct"]` - Claude is guided to call this tool directly (default if omitted)
406* `["code_execution_20260120"]` - Claude is guided to call this tool only from within code execution
407* `["direct", "code_execution_20260120"]` - Claude may call this tool directly or from within code execution
405* `["direct"]` - Claude is guided to call this tool directly (default if omitted).
406* `["code_execution_20260120"]` - Claude is guided to call this tool only from within code execution.
407* `["direct", "code_execution_20260120"]` - Claude may call this tool directly or from within code execution.
408408 
409409Both `"code_execution_20260120"` and `"code_execution_20260521"` are accepted in `allowed_callers` and are interchangeable: a request using either code-execution tool version satisfies tools that list either caller. Response blocks always tag the caller as `code_execution_20260120` regardless of which version the request declared.
410410 
from line 413
413413</Tip>
414414 
415415<Note>
416 `allowed_callers` controls how the tool is presented to Claude and is validated against `tool_choice`, but it is not a hard API-level block on direct invocation. Claude is strongly guided to respect it, but your client should still be prepared to handle a direct `tool_use` for any tool it defines. Do not rely on `allowed_callers` as a security boundary.
416 `allowed_callers` controls how the tool is presented to Claude and is validated against `tool_choice`, but it is not a hard API-level block on direct calls. Claude is strongly guided to respect it, but your client should still be prepared to handle a direct `tool_use` for any tool it defines. Do not rely on `allowed_callers` as a security boundary.
417417</Note>
418418 
419419### The `caller` field in responses
420420 
421Every tool use block includes a `caller` field indicating how it was invoked:
421Every tool use block includes a `caller` field indicating how it was called:
422422 
423**Direct invocation (traditional tool use):**
423**Direct call (traditional tool use):**
424424 
425425```json
426426{
from line 432
432432}
433433```
434434 
435**Programmatic invocation:**
435**Programmatic call:**
436436 
437437```json
438438{
from line 453
453453 
454454Programmatic tool calling uses the same containers as code execution:
455455 
456* **Container creation:** A new container is created for each request unless you reuse an existing one
457* **Container ID:** Returned in responses in the `container` field, along with an `expires_at` timestamp
456* **Container creation:** A new container is created for each request unless you reuse an existing one.
457* **Container ID:** Returned in responses in the `container` field, along with an `expires_at` timestamp.
458458* **Reuse:** Pass the container ID back on the next request to keep state. While a programmatic tool call is waiting for your result, the container ID is required on that request, not optional: the API rejects the request without it.
459459* **Expiration:** `expires_at` tells you how long the container has left. Idle containers are currently reclaimed after about 5 minutes, and no container can be reused more than 30 days after it was created.
460460 
from line 526
526526<CodeGroup>
527527 ```bash cURL
528528 curl https://api.anthropic.com/v1/messages \
529 --header "x-api-key: $ANTHROPIC_API_KEY" \
530 --header "anthropic-version: 2023-06-01" \
531 --header "content-type: application/json" \
532 --data '{
529 -H "x-api-key: $ANTHROPIC_API_KEY" \
530 -H "anthropic-version: 2023-06-01" \
531 -H "content-type: application/json" \
532 -d '{
533533 "model": "claude-opus-5-5",
534534 "max_tokens": 4096,
535535 "container": "container_xyz789",
from line 1203
12031203 
12041204This pattern:
12051205 
1206* Reduces model round-trips from N (one per region) to 1
1206* Reduces model round-trips from N (one for each region) to 1
12071207* Processes large result sets programmatically before returning to Claude
12081208* Saves tokens by only returning aggregated conclusions instead of raw data
12091209 
from line 1301
13011301 
13021302### Common errors
13031303 
1304| Error | Where it appears | Description | Solution |
1305| ------------------------------------------ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
1306| `invalid_tool_input` | `error_code` on the `code_execution_tool_result` error block in the response | Invalid parameters were passed to the code execution tool | See the [code execution tool errors](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#errors) |
1307| `invalid_request_error` (on `tool_choice`) | HTTP 400 error response | `tool_choice` names a tool whose `allowed_callers` does not include `"direct"` | Either add `"direct"` to that tool's `allowed_callers`, or remove the tool from `tool_choice` and let Claude invoke it from code |
1304| Error | Where it appears | Description | Solution |
1305| ------------------------------------------ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
1306| `invalid_tool_input` | `error_code` on the `code_execution_tool_result` error block in the response | Invalid parameters were passed to the code execution tool | See the [code execution tool errors](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#errors) |
1307| `invalid_request_error` (on `tool_choice`) | HTTP 400 error response | `tool_choice` names a tool whose `allowed_callers` does not include `"direct"` | Either add `"direct"` to that tool's `allowed_callers`, or remove the tool from `tool_choice` and let Claude call it from code |
13081308 
13091309### Container expiration during tool call
13101310 
1311If your tool result doesn't arrive within about 4 minutes, the pending call raises a `TimeoutError` inside Claude's running code. Claude sees the error in `stderr` and typically retries the call:
1311If your tool result doesn't arrive within about 4 minutes, the pending call raises a `TimeoutError` inside Claude's running code. Claude receives the error in `stderr` and typically retries the call:
13121312 
13131313```json
13141314{
from line 1326
13261326 
13271327To prevent timeouts:
13281328 
1329* Monitor the `expires_at` field in responses
1330* Implement timeouts for your tool execution
1331* Consider breaking long operations into smaller chunks
1329* Monitor the `expires_at` field in responses.
1330* Implement timeouts for your tool execution.
1331* Consider breaking long operations into smaller chunks.
13321332 
13331333### Tool execution errors
13341334 
from line 1348
13481348 
13491349### Feature incompatibilities
13501350 
1351* **Structured outputs:** Tools with `strict: true` are not supported with programmatic calling
1352* **Tool choice:** You cannot force programmatic calling of a specific tool through `tool_choice`
1353* **Parallel tool use:** `disable_parallel_tool_use: true` is not supported with programmatic calling
1351* **Structured outputs:** Tools with `strict: true` are not supported with programmatic calling.
1352* **Tool choice:** You cannot force programmatic calling of a specific tool through `tool_choice`.
1353* **Parallel tool use:** `disable_parallel_tool_use: true` is not supported with programmatic calling.
13541354 
13551355### Input schema limitations
13561356 
from line 1374
13741374 
13751375**Tool result only responses:** If there are pending programmatic tool calls waiting for results, your response message must contain **only** `tool_result` blocks. You cannot include any text content, even after the tool results.
13761376 
1377Invalid - Cannot include text when responding to programmatic tool calls:
1377Invalid (cannot include text when responding to programmatic tool calls):
13781378 
13791379```json
13801380{
from line 1390
13901390}
13911391```
13921392 
1393Valid - Only tool results when responding to programmatic tool calls:
1393Valid (only tool results when responding to programmatic tool calls):
13941394 
13951395```json
13961396{
from line 1411
14111411 
14121412### Rate limits
14131413 
1414Programmatic tool calls are subject to the same rate limits as regular tool calls. Each tool call from code execution counts as a separate invocation.
1414Programmatic tool calls are subject to the same rate limits as regular tool calls. Each tool call from code execution counts toward those limits individually.
14151415 
14161416### Validate tool results before use
14171417 
14181418When implementing user-defined tools that will be called programmatically:
14191419 
1420* **Tool results are returned as strings:** They can contain any content, including code snippets or executable commands that may be processed by the execution environment.
1421* **Validate external tool results:** If your tool returns data from external sources or accepts user input, be aware of code injection risks if the output will be interpreted or executed as code.
1420* **Tool results are returned as strings:** They can contain any content, including code snippets or executable commands that might be processed by the execution environment.
1421* **Validate external tool results:** If your tool returns data from external sources or accepts user input, be aware of code injection risks if the output is interpreted or run as code.
14221422 
14231423## Token efficiency
14241424 
from line 1425
14251425Programmatic tool calling reduces token consumption in three ways:
14261426 
14271427* **Tool results from programmatic calls are not added to Claude's context** - only the final code output is
1428* **Intermediate processing happens in code** - filtering, aggregation, and other transformations don't consume model tokens
1428* **Intermediate processing occurs in code** - filtering, aggregation, and other transformations don't consume model tokens
14291429* **Multiple tool calls in one code execution** - reduces overhead compared to separate model turns
14301430 
14311431For example, calling 10 tools directly uses \~10x the tokens of calling them programmatically and returning a summary.
from line 1432
14321432 
14331433In Anthropic's internal evaluations on a production Claude model:
14341434 
1435* On a 75-tool project-management agent benchmark, enabling programmatic tool calling reduced billed input tokens by roughly 38% with no change in task accuracy.
1436* On [τ²-bench](https://arxiv.org/abs/2506.07982) (airline, retail, and telecom domains), where each turn makes one or two sequential tool calls, programmatic tool calling left scores unchanged and cost roughly 8% more. Sequential single-call workflows do not benefit.
1437* Across production API traffic, requests whose `tools` array contains 10 to 49 tool definitions see typical token savings of 20% to 40% with programmatic tool calling enabled.
1435* On a 75-tool project-management agent benchmark, enabling programmatic tool calling reduced billed input tokens by roughly 38 percent with no change in task accuracy.
1436* On [τ²-bench](https://arxiv.org/abs/2506.07982) (airline, retail, and telecom domains), where each turn makes one or two sequential tool calls, programmatic tool calling left scores unchanged and cost roughly 8 percent more. Sequential single-call workflows do not benefit.
1437* Across production API traffic, requests whose `tools` array contains 10 to 49 tool definitions see typical token savings of 20 to 40 percent with programmatic tool calling enabled.
14381438 
14391439Actual savings vary with workload shape. See [When to use programmatic calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling#when-to-use-programmatic-calling).
14401440 
from line 1443
14431443Programmatic tool calling uses the same pricing as code execution. See the [code execution pricing](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing) for details.
14441444 
14451445<Note>
1446 Token counting for programmatic tool calls: Tool results from programmatic invocations do not count toward your input/output token usage. Only the final code execution result and Claude's response count.
1446 Token counting for programmatic tool calls: Tool results from programmatic calls do not count toward your input/output token usage. Only the final code execution result and Claude's response count.
14471447</Note>
14481448 
14491449## Best practices
from line 1450
14501450 
14511451### Tool design
14521452 
1453* **Provide detailed output descriptions:** Because Claude deserializes tool results in code, document the format (JSON structure and field types)
1454* **Return structured data:** JSON or other machine-readable formats work best for programmatic processing
1455* **Keep responses concise:** Return only necessary data to minimize processing overhead
1453* **Provide detailed output descriptions:** Because Claude deserializes tool results in code, document the format (JSON structure and field types).
1454* **Return structured data:** JSON or other machine-readable formats work best for programmatic processing.
1455* **Keep responses concise:** Return only necessary data to minimize processing overhead.
14561456 
14571457### When to use programmatic calling
14581458 
1459Programmatic tool calling trades a small fixed overhead (container startup, script generation) for large savings on tool-result tokens and model round-trips. Whether that trade pays off depends on workload shape.
1459Programmatic tool calling trades a small fixed overhead (container startup, script generation) for large savings on tool-result tokens and model round-trips. Whether that trade is worthwhile depends on workload shape.
14601460 
14611461**Strong fit:**
14621462 
from line 1474
14741474 
14751475### Performance optimization
14761476 
1477* **Reuse containers** when making multiple related requests to maintain state
1478* **Batch similar operations** in a single code execution when possible
1477* **Reuse containers** when making multiple related requests to maintain state.
1478* **Batch similar operations** in a single code execution when possible.
14791479 
14801480## Troubleshooting
14811481 
from line 1483
14831483 
14841484**`invalid_request_error` when setting `tool_choice`**
14851485 
1486* `tool_choice` cannot name a tool whose `allowed_callers` omits `"direct"`. Either add `"direct"` to that tool's `allowed_callers`, or remove the tool from `tool_choice` and let Claude invoke it from code.
1486* `tool_choice` cannot name a tool whose `allowed_callers` omits `"direct"`. Either add `"direct"` to that tool's `allowed_callers`, or remove the tool from `tool_choice` and let Claude call it from code.
14871487 
14881488**Container expiration**
14891489 
14901490* Respond to each programmatic tool call well before the paused response's `expires_at` timestamp. Claude's code stops waiting for a result after about 4 minutes, and idle containers are currently reclaimed after about 5 minutes.
1491* Consider implementing faster tool execution
1491* Consider implementing faster tool execution.
14921492 
14931493**Tool result not parsed correctly**
14941494 
1495* Ensure your tool returns string data that Claude can deserialize
1496* Provide clear output format documentation in your tool description
1495* Ensure your tool returns string data that Claude can deserialize.
1496* Provide clear output format documentation in your tool description.
14971497 
14981498### Debugging tips
14991499 
15001. **Log all tool calls and results** to track the flow
15012. **Check the `caller` field** to confirm programmatic invocation
15023. **Monitor container IDs** to ensure proper reuse
15034. **Test tools independently** before enabling programmatic calling
15001. **Log all tool calls and results** to track the flow.
15012. **Check the `caller` field** to confirm a programmatic call.
15023. **Monitor container IDs** to ensure proper reuse.
15034. **Test tools independently** before enabling programmatic calling.
15041504 
15051505## Why programmatic tool calling works
15061506 
15071507Claude is trained on large amounts of code, so presenting tools as callable Python functions lets it use that strength:
15081508 
1509* **Tool composition:** Chained calls, loops, and conditionals are ordinary Python control flow instead of a series of model round trips
1510* **Result processing:** Claude's code filters and aggregates large tool outputs, or writes them to files, and only the final output enters the context window
1511* **Latency:** The model is not re-sampled between the tool calls inside one code execution
1509* **Tool composition:** Chained calls, loops, and conditionals are ordinary Python control flow instead of a series of model round trips.
1510* **Result processing:** Claude's code filters and aggregates large tool outputs, or writes them to files, and only the final output enters the context window.
1511* **Latency:** The model is not re-sampled between the tool calls inside one code execution.
15121512 
15131513## Alternative implementations
15141514 
from line 1516
15161516 
15171517### Client-side direct execution
15181518 
1519Provide Claude with a code execution tool and describe what functions are available in that environment. When Claude invokes the tool with code, your application executes it locally where those functions are defined.
1519Provide Claude with a code execution tool and describe what functions are available in that environment. When Claude calls the tool with code, your application runs it locally where those functions are defined.
15201520 
15211521**Advantages:**
15221522 
from line 1525
15251525 
15261526**Disadvantages:**
15271527 
1528* Executes untrusted code outside of a sandbox
1529* Tool invocations can be vectors for code injection
1528* Runs untrusted code outside of a sandbox
1529* Tool calls can be vectors for code injection
15301530 
1531**Use when:** Your application can safely execute arbitrary code, you want the smallest implementation, and Anthropic's managed offering doesn't fit your needs.
1531**Use when:** Your application can safely run arbitrary code, you want the smallest implementation, and Anthropic's managed offering doesn't fit your needs.
15321532 
15331533### Self-managed sandboxed execution
15341534 
1535Same approach from Claude's perspective, but code runs in a sandboxed container with security restrictions (for example, no network egress). If your tools require external resources, you'll need a protocol for executing tool calls outside the sandbox.
1535Same approach from Claude's perspective, but code runs in a sandboxed container with security restrictions (for example, no network egress). If your tools require external resources, you'll need a protocol for running tool calls outside the sandbox.
15361536 
15371537**Advantages:**
15381538 
from line 1548
15481548 
15491549### Anthropic-managed execution
15501550 
1551Anthropic's programmatic tool calling is a managed version of sandboxed execution with an opinionated Python environment tuned for Claude. Anthropic handles container management, code execution, and secure tool invocation communication.
1551Anthropic's programmatic tool calling is a managed version of sandboxed execution with an opinionated Python environment tuned for Claude. Anthropic handles container management, code execution, and secure tool call communication.
15521552 
15531553**Advantages:**
15541554 
from line 1572
15721572 </Card>
15731573 
15741574 <Card title="Code execution tool" icon="code" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool">
1575 Run Python and bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
1575 Run Python and Bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
15761576 </Card>
15771577 
15781578 <Card title="Tool use with Claude" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">
1579 Connect Claude to external tools and APIs. See where tools execute, when Claude calls them, and which tool fits your task.
1579 Connect Claude to external tools and APIs. See where tools run, when Claude calls them, and which tool fits your task.
15801580 </Card>
15811581 
15821582 <Card title="Define tools" icon="hammer" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools">

agents-and-tools/tool-use/server-tools Changed · +11 / -11 lines

from line 1
11---
22title: Server tools
33url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools
4description: "Work with Anthropic-executed tools: server_tool_use blocks, pause_turn continuation, mixed server and client tool turns, and domain filtering."
4description: "Work with tools that Anthropic runs: server_tool_use blocks, pause_turn continuation, mixed server and client tool turns, and domain filtering."
55---
66 
7Server-executed tools share these mechanics: the `server_tool_use` block, `pause_turn` continuation, turns that mix server and client tools, Zero Data Retention (ZDR) eligibility, and domain filtering. For individual tools, see the [tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference).
7Server-executed tools share these mechanics: the `server_tool_use` block, `pause_turn` continuation, turns that mix server and client tools, Zero Data Retention (ZDR) eligibility, and domain filtering. For individual tools, see the [Tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference).
88 
99## The server\_tool\_use block
1010 
from line 19
1919}
2020```
2121 
22The API executes the tool internally. You see the call and its result in the response, but you don't handle execution. Unlike client `tool_use` blocks, you don't need to respond with a `tool_result`. The tool's result block (for example, `web_search_tool_result` for web search) follows the `server_tool_use` block in the same assistant turn, paired by `tool_use_id`. If Claude calls one of your client tools at the same time, the `server_tool_use` block appears without its result, and the response ends with `stop_reason: "tool_use"`. The API runs the tool when you return the client `tool_result` blocks in your next request.
22The API runs the tool internally. You see the call and its result in the response, but you don't handle execution. Unlike client `tool_use` blocks, you don't need to respond with a `tool_result`. The tool's result block (for example, `web_search_tool_result` for web search) follows the `server_tool_use` block in the same assistant turn, paired by `tool_use_id`. If Claude calls one of your client tools at the same time, the `server_tool_use` block appears without its result, and the response ends with `stop_reason: "tool_use"`. The API runs the tool when you return the client `tool_result` blocks in your next request.
2323 
2424## The server-side loop and pause\_turn
2525 
from line 395
395395 
396396## Mixing server tools and client tools in one turn
397397 
398Claude can call a server tool and a client tool in the same group of parallel tool calls, for example, `web_fetch` together with a user-defined tool. A client tool is any tool that your code executes and that produces a `tool_use` block, whether it is user-defined or an Anthropic-schema client tool such as the [Bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool). When that happens, the API does not run the server tool. It returns immediately so that you can run the client tool first:
398Claude can call a server tool and a client tool in the same group of parallel tool calls, for example, `web_fetch` together with a user-defined tool. A client tool is any tool that your code runs and that produces a `tool_use` block, whether it is user-defined or an Anthropic-schema client tool such as the [Bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool). When that occurs, the API does not run the server tool. It returns immediately so that you can run the client tool first:
399399 
400400* `stop_reason` is `"tool_use"`, not `"pause_turn"`.
401* `content` contains the `server_tool_use` block and the client `tool_use` block, but no result block for the server tool: that call is not finished.
401* `content` contains the `server_tool_use` block and the client `tool_use` block, but no result block for the server tool: that call is not complete.
402402* There is no other marker. Detect the state by looking for a `server_tool_use` block whose `id` has no matching result block in the response. An `mcp_tool_use` block from the [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) behaves the same way. Server tool calls that already have their result block in the same response are complete and need nothing from you.
403403 
404404<Note>
405 With [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), the same response shape means something different. The client `tool_use` block comes from code that is running in the `code_execution` tool rather than from Claude directly, and its `caller` field names the `code_execution` block that called it. That code has already started: it is paused waiting for your `tool_result` blocks, and sending them resumes the execution instead of starting a deferred tool. The `code_execution` block's own result block arrives once the code finishes, which can take more than one round of tool results. The follow-up user message itself is the same in both cases; with programmatic tool calling, also pass back the `id` from the response's `container` field, as that page shows.
405 With [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), the same response shape means something different. The client `tool_use` block comes from code that is running in the `code_execution` tool rather than from Claude directly, and its `caller` field names the `code_execution` block that called it. That code has already started: it is paused waiting for your `tool_result` blocks, and sending them resumes the execution instead of starting a deferred tool. The `code_execution` block's own result block arrives once the code completes, which can take more than one round of tool results. The follow-up user message itself is the same in both cases; with programmatic tool calling, also pass back the `id` from the response's `container` field, as that page shows.
406406</Note>
407407 
408408```json
from line 444
444444}
445445```
446446 
447The API attaches your results to the still-open assistant turn, runs the deferred server tool (for paused code execution, resumes it), and then lets Claude continue. For a server tool Claude called directly, the next response begins with the result block that answers the previous response's `server_tool_use` `id`, followed by the newly generated content and a fresh `stop_reason`:
447The API attaches your results to the still-open assistant turn, runs the deferred server tool (for paused code execution, resumes it), and then lets Claude continue. For a server tool Claude called directly, the next response starts with the result block that answers the previous response's `server_tool_use` `id`, followed by the newly generated content and a fresh `stop_reason`:
448448 
449449```json
450450{
from line 1021
10211021}
10221022```
10231023 
1024This restricts the tool to direct invocation only, bypassing the internal code execution step.
1024This restricts the tool to direct calls only, bypassing the internal code execution step.
10251025 
1026`allowed_callers` controls how a tool can be invoked: directly by Claude (`"direct"`), from inside a code execution container (for example, `"code_execution_20260120"`), or both. The `_20260209` versions of the web tools default to the code execution caller only; earlier versions default to `["direct"]`. On models that don't support programmatic tool calling, these versions require `allowed_callers: ["direct"]`; without it the API returns a validation error that says to set it.
1026`allowed_callers` controls how a tool can be called: directly by Claude (`"direct"`), from inside a code execution container (for example, `"code_execution_20260120"`), or both. The `_20260209` versions of the web tools default to the code execution caller only; earlier versions default to `["direct"]`. On models that don't support programmatic tool calling, these versions require `allowed_callers: ["direct"]`; without it the API returns a validation error that says to set it.
10271027 
10281028<Note>
10291029 Even when web fetch is used in a ZDR-eligible configuration, website publishers might retain any parameters passed to the URL if Claude fetches content from their site.
from line 1106
11061106 </Card>
11071107 
11081108 <Card title="Code execution tool" icon="terminal" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool">
1109 Run Python and bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
1109 Run Python and Bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
11101110 </Card>
11111111 
11121112 <Card title="Tool search tool" icon="compass" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool">

agents-and-tools/tool-use/text-editor-tool Changed · +29 / -29 lines

from line 225
225225 
226226<Steps>
227227 <Step title="Provide Claude with the text editor tool and a user prompt">
228 * Include the text editor tool in your API request
229 * Provide a user prompt that may require examining or modifying files, such as "Can you fix the syntax error in my code?"
228 * Include the text editor tool in your API request.
229 * Provide a user prompt that might require examining or modifying files, such as "Can you fix the syntax error in my code?"
230230 </Step>
231231 
232232 <Step title="Claude uses the tool to examine files or directories">
233 * Claude assesses what it needs to look at and uses the `view` command to examine file contents or list directory contents
234 * The API response will contain a `tool_use` content block with the `view` command
233 * Claude assesses what it needs to look at and uses the `view` command to examine file contents or list directory contents.
234 * The API response contains a `tool_use` content block with the `view` command.
235235 </Step>
236236 
237 <Step title="Execute the view command and return results">
238 * Extract the file or directory path from Claude's tool use request
239 * Read the file's contents or list the directory contents
240 * If a `max_characters` parameter was specified in the tool configuration, truncate the file contents to that length
241 * Return the results to Claude by continuing the conversation with a new `user` message containing a `tool_result` content block
237 <Step title="Run the view command and return results">
238 * Extract the file or directory path from Claude's tool use request.
239 * Read the file's contents or list the directory contents.
240 * If you specified a `max_characters` parameter in the tool configuration, truncate the file contents to that length.
241 * Return the results to Claude by continuing the conversation with a new `user` message containing a `tool_result` content block.
242242 </Step>
243243 
244244 <Step title="Claude uses the tool to modify files">
245 * After examining the file or directory, Claude may use a command such as `str_replace` to make changes or `insert` to add text at a specific line number.
246 * If Claude uses the `str_replace` command, Claude constructs a properly formatted tool use request with the old text and new text to replace it with
245 * After examining the file or directory, Claude might use a command such as `str_replace` to make changes or `insert` to add text at a specific line number.
246 * If Claude uses the `str_replace` command, Claude constructs a properly formatted tool use request with the old text and new text to replace it with.
247247 </Step>
248248 
249 <Step title="Execute the edit and return results">
250 * Extract the file path, old text, and new text from Claude's tool use request
251 * Perform the text replacement in the file
252 * Return the results to Claude
249 <Step title="Make the edit and return results">
250 * Extract the file path, old text, and new text from Claude's tool use request.
251 * Perform the text replacement in the file.
252 * Return the results to Claude.
253253 </Step>
254254 
255255 <Step title="Claude provides its analysis and explanation">
256 * After examining and possibly editing the files, Claude provides a complete explanation of what it found and what changes it made
256 * After examining and possibly editing the files, Claude provides a complete explanation of what it found and what changes it made.
257257 </Step>
258258</Steps>
259259 
from line 1484
14841484 
14851485<Steps>
14861486 <Step title="Initialize your editor implementation">
1487 Create helper functions to handle file operations like reading, writing, and modifying files. Consider implementing backup functionality to recover from mistakes.
1487 Create helper functions to handle file operations such as reading, writing, and modifying files. Consider implementing backup functionality to recover from mistakes.
14881488 </Step>
14891489 
14901490 <Step title="Handle editor tool calls">
from line 1773
17731773 
17741774### Handle errors
17751775 
1776When using the text editor tool, various errors may occur. Here is guidance on how to handle them:
1776When using the text editor tool, various errors might occur. Here is guidance on how to handle them:
17771777 
17781778<AccordionGroup>
17791779 <Accordion title="File not found">
1780 If Claude tries to view or modify a file that doesn't exist, return an appropriate error message in the `tool_result`:
1780 If Claude attempts to view or modify a file that doesn't exist, return an appropriate error message in the `tool_result`:
17811781 
17821782 ```json
17831783 {
from line 1853
18531853 
18541854<AccordionGroup>
18551855 <Accordion title="Provide clear context">
1856 When asking Claude to fix or modify code, be specific about what files need to be examined or what issues need to be addressed. Clear context helps Claude identify the right files and make appropriate changes.
1856 When asking Claude to fix or modify code, be specific about what files to examine or what issues to address. Clear context helps Claude identify the right files and make appropriate changes.
18571857 
18581858 **Less helpful prompt:** "Can you fix my code?"
18591859 
from line 2250
22502250| Date | Version | Changes |
22512251| ---------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
22522252| July 28, 2025 | `text_editor_20250728` | Release of an updated text editor tool that fixes some issues and adds an optional `max_characters` parameter. It is otherwise identical to `text_editor_20250429`. |
2253| April 29, 2025 | `text_editor_20250429` | Release of the text editor tool for Claude 4. This version removes the `undo_edit` command but maintains all other capabilities. The tool name has been updated to reflect its str\_replace-based architecture. |
2253| April 29, 2025 | `text_editor_20250429` | Release of the text editor tool for Claude 4. This version removes the `undo_edit` command but maintains all other capabilities. The tool name has been updated to reflect its `str_replace`-based architecture. |
22542254| March 13, 2025 | `text_editor_20250124` | Introduction of standalone text editor tool documentation. This version is optimized for Claude Sonnet 3.7 but has identical capabilities to the previous version. |
22552255| October 22, 2024 | `text_editor_20241022` | Initial release of the text editor tool with Claude Sonnet 3.5 (retired; see [Model deprecations](https://platform.claude.com/docs/en/about-claude/model-deprecations)). Provides capabilities for viewing, creating, and editing files through the `view`, `create`, `str_replace`, `insert`, and `undo_edit` commands. |
22562256 
from line 2258
22582258 
22592259Here are some ideas for how to use the text editor tool in more convenient and powerful ways:
22602260 
2261* **Integrate with your development workflow**: Build the text editor tool into your development tools or IDE
2262* **Create a code review system**: Have Claude review your code and make improvements
2263* **Build a debugging assistant**: Create a system where Claude can help you diagnose and fix issues in your code
2264* **Implement file format conversion**: Let Claude help you convert files from one format to another
2265* **Automate documentation**: Set up workflows for Claude to automatically document your code
2261* **Integrate with your development workflow:** Build the text editor tool into your development tools or IDE
2262* **Create a code review system:** Have Claude review your code and make improvements
2263* **Build a debugging assistant:** Create a system where Claude can help you diagnose and fix issues in your code
2264* **Implement file format conversion:** Let Claude help you convert files from one format to another
2265* **Automate documentation:** Set up workflows for Claude to automatically document your code
22662266 
2267The text editor tool enables Claude to work directly with your code base, supporting workflows from debugging to automated documentation.
2267The text editor tool allows Claude to work directly with your code base, supporting workflows from debugging to automated documentation.
22682268 
22692269<CardGroup cols={3}>
22702270 <Card title="Tool use overview" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">
from line 2272
22722272 </Card>
22732273 
22742274 <Card title="Bash tool" icon="terminal" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool">
2275 Execute shell commands with Claude.
2275 Run shell commands with Claude.
22762276 </Card>
22772277</CardGroup>
22782278 

agents-and-tools/tool-use/tool-combinations Changed · +4 / -4 lines

from line 4
44description: Common Anthropic tool pairings for research agents, coding agents, and long-running agents.
55---
66 
7Anthropic-provided tools are designed to work together. Common agent patterns pair tools that cover complementary stages of a workflow: one tool gathers or discovers, another processes or acts. The combinations below are starting points, not prescriptions. Mix them to fit your task.
7Anthropic-provided tools are designed to work together. Common agent patterns pair tools that cover complementary stages of a workflow: one tool gathers or discovers, another processes or acts. The following combinations are starting points, not prescriptions. Mix them to fit your task.
88 
99Each snippet shows only the `tools` array. See [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) for the full request shape.
1010 
from line 21
2121}
2222```
2323 
24The flow is typically search, then execute, then optionally search again if the first pass surfaced a gap. Code execution runs server-side, so there's no client-side sandbox to manage.
24The flow is typically search, then run code, then optionally search again if the first pass surfaced a gap. Code execution runs server-side, so there's no client-side sandbox to manage.
2525 
2626## Coding agent: text\_editor + bash
2727 
from line 69
6969 
7070## All-in-one: computer\_use
7171 
72The computer use tool subsumes most others by operating a full desktop. Claude sees screenshots and issues mouse and keyboard actions, which means it can drive any application a human can. Use this when the task requires arbitrary GUI interaction that more specific tools can't reach: legacy software without an API, visual verification steps, or workflows that span multiple desktop apps.
72The computer use tool subsumes most others by operating a full desktop. Claude receives screenshots and issues mouse and keyboard actions, which means it can drive any application a human can. Use this when the task requires arbitrary GUI interaction that more specific tools can't reach: legacy software without an API, visual verification steps, or workflows that span multiple desktop apps.
7373 
7474```json
7575{
from line 83
8383 
8484## Browser agent: browser\_use
8585 
86When the whole task happens inside webpages (filling forms, reading page content, working across tabs), the browser use tool is a closer fit than computer use. Your application drives a browser it controls and returns screenshots or page state; Claude calls page-aware member tools such as `read_page`, `find`, `form_input`, and `get_page_text` alongside clicks and typing, so it can act on element references in addition to pixel coordinates.
86When the whole task occurs inside webpages (filling forms, reading page content, working across tabs), the browser use tool is a closer fit than computer use. Your application drives a browser it controls and returns screenshots or page state; Claude calls page-aware member tools such as `read_page`, `find`, `form_input`, and `get_page_text` alongside clicks and typing, so it can act on element references in addition to pixel coordinates.
8787 
8888```json
8989{

agents-and-tools/tool-use/tool-reference Changed · +6 / -6 lines

from line 8
88 
99## Anthropic-provided tools
1010 
11Anthropic provides two kinds of tools: **server tools** that execute on Anthropic's infrastructure, and **client tools** where Anthropic defines the schema but your application handles execution. Both kinds appear in your request's `tools` array alongside any user-defined tools.
11Anthropic provides two kinds of tools: **server tools** that run on Anthropic's infrastructure, and **client tools** where Anthropic defines the schema but your application handles execution. Both kinds appear in your request's `tools` array alongside any user-defined tools.
1212 
1313| Tool | `type` | Execution | [Beta header](https://platform.claude.com/docs/en/api/beta-headers) |
1414| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------- |
from line 46
4646 
4747### Client toolsets
4848 
49The [computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) and [browser use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool) are Anthropic-defined client toolsets: one entry in `tools` declares a fixed set of member tools whose names, descriptions, and input schemas Anthropic defines, and your application executes every call. The entry takes no `name`, because the dated `type` fixes the member names. `configs`, `cache_control`, and `allowed_callers` (which accepts only `["direct"]`) are optional.
49The [computer use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) and [browser use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool) are Anthropic-defined client toolsets: one entry in `tools` declares a fixed set of member tools whose names, descriptions, and input schemas Anthropic defines, and your application runs every call. The entry takes no `name`, because the dated `type` fixes the member names. `configs`, `cache_control`, and `allowed_callers` (which accepts only `["direct"]`) are optional.
5050 
5151Client toolsets are Messages API tools. They aren't currently available as agent tools in [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/tools), which provides its own built-in agent toolset, MCP toolsets, and custom tools.
5252 
from line 65
6565* Keys are member names, and each value accepts only `enabled` and `defer_loading`.
6666* A member you omit keeps its defaults. An absent value, `{}`, and a restated default are equivalent.
6767* An unknown member name or any other field in a member's value is rejected, as is a `configs` that disables every member (omit the entry instead).
68* A disabled member is removed from the tools Claude sees. If Claude still names it, return an error `tool_result`.
68* A disabled member is removed from the tools Claude receives. If Claude still names it, return an error `tool_result`.
6969 
70Set `defer_loading` per member, never on the entry, and give every enabled member the same value: under [tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool#deferred-tool-loading) the toolset loads and expands as one definition. When every enabled member defers, only a [tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) that isn't itself deferred can surface the toolset, so declare one in the same request. Don't put `cache_control` on a toolset entry whose members defer; set the breakpoint on a non-deferred tool instead, because deferred definitions are not part of the cached prefix.
70Set `defer_loading` for each member, never on the entry, and give every enabled member the same value: under [tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool#deferred-tool-loading) the toolset loads and expands as one definition. When every enabled member defers, only a [tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) that isn't itself deferred can surface the toolset, so declare one in the same request. Don't put `cache_control` on a toolset entry whose members defer; set the breakpoint on a non-deferred tool instead, because deferred definitions are not part of the cached prefix.
7171 
7272`cache_control` goes on the entry only; to learn where the breakpoint lands, including markers inside a batch action, see [Tool use with prompt caching](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-use-with-prompt-caching#cache-control-on-tool-definitions).
7373 
74**Handle member tool calls.** Claude calls a member with a `tool_use` block whose `name` is the member name and whose `toolset_name` is `computer` or `browser`; `input` holds that member's parameters and no `action` field. Dispatch on the `toolset_name` and `name` pair, because a custom tool may share a member's name and the two toolsets share names such as `screenshot`. Only member results echo `toolset_name`. Several member calls in one turn form a batch action that you run in order ([computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions), [browser use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#batch-actions)). New members arrive only with a new dated `type`.
74**Handle member tool calls.** Claude calls a member with a `tool_use` block whose `name` is the member name and whose `toolset_name` is `computer` or `browser`; `input` holds that member's parameters and no `action` field. Dispatch on the `toolset_name` and `name` pair, because a custom tool might share a member's name and the two toolsets share names such as `screenshot`. Only member results echo `toolset_name`. Several member calls in one turn form a batch action that you run in order ([computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#batch-actions), [browser use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool#batch-actions)). New members arrive only with a new dated `type`.
7575 
7676**Not supported on toolset entries.** The API rejects each of these with an `invalid_request_error`:
7777 
7878* `strict: true` or `input_examples`.
79* `defer_loading` on the entry, or enabled members whose `defer_loading` values differ (set it per member in `configs`, all to the same value).
79* `defer_loading` on the entry, or enabled members whose `defer_loading` values differ (set it for each member in `configs`, all to the same value).
8080* A code execution caller in `allowed_callers` (no [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling)).
8181* The legacy `fine-grained-tool-streaming-2025-05-14` beta header. When you stream, each member's `input` arrives as one complete `input_json_delta`.
8282* A `tool_choice` of type `tool` that names the toolset or a member (use `auto`, `any`, or `none`).

agents-and-tools/tool-use/tool-runner Changed · +6 / -6 lines

from line 83
8383 
8484 TypeScript offers two approaches for defining tools:
8585 
86 **Using Zod (recommended)** - Use `betaZodTool()` for type-safe tool definitions with Zod validation (requires Zod 3.25.0 or higher):
86 **Using Zod (recommended):** Use `betaZodTool()` for type-safe tool definitions with Zod validation (requires Zod 3.25.0 or higher):
8787 
8888 ```typescript
8989 import Anthropic from "@anthropic-ai/sdk";
from line 118
118118 }
119119 ```
120120 
121 **Using JSON Schema** - Use `betaTool()` for type-safe tool definitions without Zod:
121 **Using JSON Schema:** Use `betaTool()` for type-safe tool definitions without Zod:
122122 
123123 <Note>
124124 The input generated by Claude is not validated at runtime. Perform validation inside the `run` function if needed.
from line 814
814814 
815815You take over by modifying the runner's messages from inside the loop body. The exact method depends on the SDK. See the per-language tabs that follow.
816816 
817When you take over for an iteration, the runner does not append the assistant message or tool results from that turn. You become responsible for keeping the conversation valid: append the assistant message and a tool result yourself (if you want the turn to count), modify state conditionally so the loop can still exit when there are no tool calls, and pass `max_iterations` (csharp, java, php: `maxIterations`; go: `MaxIterations`) to bound the loop. All seven SDKs support `max_iterations` (csharp, java, php: `maxIterations`; go: `MaxIterations`).
817When you take over for an iteration, the runner does not append the assistant message or tool results from that turn. You become responsible for keeping the conversation valid: append the assistant message and a tool result yourself (if you want the turn to count), modify state conditionally so the loop can still exit when there are no tool calls, and pass `max_iterations` (csharp, java, php: `maxIterations`; go: `MaxIterations`) to bound the loop. The SDK supports `max_iterations` (csharp, java, php: `maxIterations`; go: `MaxIterations`).
818818 
819819<Tabs exclude="shell">
820820 <Tab title="Python">
from line 979
979979 </Tab>
980980 
981981 <Tab title="Java">
982 Use `runner.params()` to read the current parameters and `runner.setNextParams()` to replace them for the next iteration. When you call `setNextParams()` inside the loop, the runner skips its automatic append. The just-yielded message is discarded, and the next iteration sends your new params unchanged.
982 Use `runner.params()` to read the current parameters and `runner.setNextParams()` to replace them for the next iteration. When you call `setNextParams()` inside the loop, the runner skips its automatic append. The just-yielded message is discarded, and the next iteration sends your new parameters unchanged.
983983 
984984 The following example retries a turn that hit the token limit by doubling `max_tokens`. Mutating only on the `max_tokens` branch keeps the loop converging: turns that complete normally fall through, and the runner auto-appends and exits when there are no more tool calls.
985985 
from line 1114
11141114 
11151115### Intercepting tool errors
11161116 
1117By default, tool errors are passed back to Claude, which can then respond appropriately. However, you might want to detect errors and handle them differently, for example, to stop execution early or implement custom error handling.
1117By default, the tool runner passes tool errors back to Claude, which can then respond appropriately. However, you might want to detect errors and handle them differently, for example, to stop execution early or implement custom error handling.
11181118 
11191119<Tabs exclude="shell">
11201120 <Tab title="Python">
from line 1705
17051705 </Tab>
17061706 
17071707 <Tab title="Java">
1708 Call `runner.streaming()` to get a stream for each turn. Each `StreamResponse` must be closed after use.
1708 Call `runner.streaming()` to get a stream for each turn. Close each `StreamResponse` after use.
17091709 
17101710 ```java
17111711 void main() {

agents-and-tools/tool-use/tool-search-tool Changed · +6 / -6 lines

from line 73
73732. You provide every tool definition in the `tools` array and set `defer_loading: true` on the tools that shouldn't load up front. At least one tool, normally the tool search tool itself, must stay non-deferred.
74743. Initially, Claude's context contains only the tool search tool and any non-deferred tools.
75754. When Claude needs additional tools, it searches using a tool search tool.
765. The API runs the search and returns the matching tools as `tool_reference` blocks (up to 5 by default; Claude can set a `limit` in its search input).
765. The API runs the search and returns the matching tools as `tool_reference` blocks (up to 5 by default, although Claude can set a `limit` in its search input).
77776. The API automatically expands these references into full tool definitions.
78787. Claude selects from the discovered tools and calls them.
7979 
from line 528
528528 ```
529529</CodeGroup>
530530 
531Claude searches the catalog, discovers `get_weather`, and calls it. The response ends with `stop_reason: "tool_use"`. Execute the discovered tool and return a `tool_result` as in [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls). [Response format](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool#response-format) shows the blocks you get back and what to send next.
531Claude searches the catalog, discovers `get_weather`, and calls it. The response ends with `stop_reason: "tool_use"`. Run the discovered tool and return a `tool_result` as in [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls). [Response format](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool#response-format) shows the blocks you get back and what to send next.
532532 
533533## Tool definition
534534 
from line 594
594594* Never set `defer_loading: true` on the tool search tool itself.
595595* Keep your 3–5 most frequently used tools non-deferred so Claude can call them without searching first.
596596 
597The computer use and browser use toolsets (`computer_toolset_20260801` and `browser_toolset_20260801`) take `defer_loading` per member tool inside the entry's `configs` object, not on the entry itself; a request that sets it at the entry level is rejected. Because a toolset defers and expands as a unit, `defer_loading` must resolve to the same value on every enabled member, and when Claude discovers the toolset through search, every enabled member loads at once. See [Client toolsets](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets) for the `configs` format.
597The computer use and browser use toolsets (`computer_toolset_20260801` and `browser_toolset_20260801`) take `defer_loading` for each member tool inside the entry's `configs` object, not on the entry itself; a request that sets it at the entry level is rejected. Because a toolset defers and expands as a unit, `defer_loading` must resolve to the same value on every enabled member, and when Claude discovers the toolset through search, every enabled member loads at once. See [Client toolsets](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference#client-toolsets) for the `configs` format.
598598 
599599Both tool search variants (`regex` and `bm25`) search tool names, descriptions, argument names, and argument descriptions.
600600 
from line 646
646646 
647647### Understanding the response
648648 
649* **`server_tool_use`:** Claude's call to the tool search tool. The search runs on Anthropic's servers. Never return a `tool_result` for its `srvtoolu_...` ID. The `input` holds the search (`pattern` for the regex variant, `query` for BM25) and may include an optional `limit`, an integer from 1 to 10,000 that caps how many matching tools the search returns (default: 5).
649* **`server_tool_use`:** Claude's call to the tool search tool. The search runs on Anthropic's servers. Never return a `tool_result` for its `srvtoolu_...` ID. The `input` holds the search (`pattern` for the regex variant, `query` for BM25) and might include an optional `limit`, an integer from 1 to 10,000 that caps how many matching tools the search returns (default: 5).
650650* **`tool_search_tool_result`:** the search results, in a nested `tool_search_tool_search_result` object. Keep it in the message history as is.
651651* **`tool_references`:** an array of `tool_reference` objects pointing to discovered tools. The API expands these for Claude. You never expand them yourself.
652* **`tool_use`:** Claude's call to a discovered tool. Execute it and return a `tool_result` exactly as in standard tool use.
652* **`tool_use`:** Claude's call to a discovered tool. Run it and return a `tool_result` exactly as in standard tool use.
653653 
654654The API automatically expands `tool_reference` blocks into full tool definitions before showing them to Claude. You don't need to handle this expansion yourself, as long as you provide all matching tool definitions in the `tools` parameter.
655655 
from line 818
818818 
819819### Limits
820820 
821* **Maximum deferred tools:** 10,000 tools with `defer_loading: true` per request
821* **Maximum deferred tools:** 10,000 tools with `defer_loading: true` for each request
822822* **Search results:** each search returns up to 5 matching tools by default; Claude can set `limit` in its search input to any integer from 1 to 10,000
823823* **Pattern and query length:** maximum 200 characters for regex patterns and 500 characters for BM25 queries
824824* **Model support:** see [Model compatibility](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool#model-compatibility)

agents-and-tools/tool-use/troubleshooting-tool-use Changed · +5 / -5 lines

from line 11
1111| Symptom | Likely cause | Fix |
1212| ------------------------------------------ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1313| Claude calls tool A when you wanted tool B | Description ambiguity | Sharpen descriptions. Differentiate tools by WHEN to use them, not only WHAT they do. See [Define tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools). |
14| Claude never calls your tool | Tool name collision or overly-generic schema | Check for duplicate names across your tool list. Add `input_examples` to make the intended use concrete. |
14| Claude never calls your tool | Tool name collision or overly generic schema | Check for duplicate names across your tool list. Add `input_examples` to make the intended use concrete. |
1515| Claude calls with wrong parameter types | Model guessing at ambiguous schema | Add `strict: true` (if your schema is in the supported subset) or add `input_examples`. |
1616 
1717## Claude invents tool parameters
from line 26
2626| Symptom | Likely cause | Fix |
2727| ------------------------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2828| Claude calls tools sequentially when parallel would be better | Message history formatting | Send multiple `tool_result` blocks in ONE user message, not one per turn. See [Parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use). |
29| `disable_parallel_tool_use` seems ignored | Set too late in the conversation | Must be set on the request that returns `tool_use`. Setting it on a later request has no effect on earlier tool calls. |
29| `disable_parallel_tool_use` seems ignored | Set too late in the conversation | Set it on the request that returns `tool_use`. Setting it on a later request has no effect on earlier tool calls. |
3030 
3131## Cache keeps invalidating
3232 
from line 39
3939 
4040| Error | Cause | Fix |
4141| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
42| `tool_use ids were found without tool_result blocks immediately after` | Missing `tool_result` for some `tool_use` ids, or `tool_result` is not the first content block in the user message | Return one `tool_result` for every `tool_use` block in the assistant response. Put `tool_result` blocks before any text. See [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) and [Parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use). |
43| `was found without a corresponding <name>_tool_result block` | The previous assistant turn has a `server_tool_use` block with no result block (most often, Claude called it alongside a client tool), and either your next user message ended that turn (for example, with text after the `tool_result` blocks) or the resume request no longer defines that server tool (the message then ends with `but no <name> tool was provided`) | Send a user message containing only the `tool_result` blocks for the client `tool_use` ids and keep the same `tools` array. See [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use). |
42| `tool_use ids were found without tool_result blocks immediately after` | Missing `tool_result` for some `tool_use` IDs, or `tool_result` is not the first content block in the user message | Return one `tool_result` for every `tool_use` block in the assistant response. Put `tool_result` blocks before any text. See [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) and [Parallel tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use). |
43| `was found without a corresponding <name>_tool_result block` | The previous assistant turn has a `server_tool_use` block with no result block (most often, Claude called it alongside a client tool), and either your next user message ended that turn (for example, with text after the `tool_result` blocks) or the resume request no longer defines that server tool (the message then ends with `but no <name> tool was provided`) | Send a user message containing only the `tool_result` blocks for the client `tool_use` IDs and keep the same `tools` array. See [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use). |
4444| `Unsupported regex feature in pattern field: ...` | A `pattern` in a strict tool's `input_schema` uses a regex feature that strict mode can't compile, such as a backreference, a lookaround, a word boundary, or a large `{n,m}` range | Simplify the pattern. Anchored patterns with basic quantifiers, character classes, and groups are supported; see [JSON Schema limitations](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations). |
4545| `All tools have defer_loading: true` | No tools visible to the model | At least one tool must be immediately loaded. The tool search tool itself must never have `defer_loading: true`. |
4646 
from line 70
7070 </Card>
7171 
7272 <Card title="Handle tool calls" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls">
73 Execute tools and return results in the required message format.
73 Run tools and return results in the required message format.
7474 </Card>
7575 
7676 <Card title="Tool reference" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference">

agents-and-tools/tool-use/web-fetch-tool Changed · +11 / -11 lines

from line 8
88 To learn how zero data retention (ZDR) applies to this feature, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).
99</Note>
1010 
11The web fetch tool allows Claude to retrieve full content from specified web pages and PDF documents.
11The web fetch tool allows Claude to retrieve full content from specified webpages and PDF documents.
1212 
1313The latest web fetch tool version (`web_fetch_20260318`) supports **dynamic filtering**: Claude can write and execute code to filter fetched content before it reaches the context window, keeping only relevant information and discarding the rest. This reduces token consumption while maintaining response quality. Dynamic filtering is available with Claude 4.6 and later models and [Claude Mythos Preview](https://anthropic.com/glasswing). `web_fetch_20260318` also adds [response inclusion](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#response-inclusion) control for agentic workflows. The previous versions (`web_fetch_20260309` for dynamic filtering and [cache bypass](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#cache-bypass), `web_fetch_20260209` for dynamic filtering only, `web_fetch_20250910` for basic fetch) remain available.
1414 
from line 67
6767 
6868### Dynamic filtering
6969 
70Fetching full web pages and PDFs can quickly consume tokens, especially when only specific information is needed from large documents. With `web_fetch_20260209` or later, Claude can write and execute code to filter the fetched content before loading it into context.
70Fetching full webpages and PDFs can quickly consume tokens, especially when only specific information is needed from large documents. With `web_fetch_20260209` or later, Claude can write and run code to filter the fetched content before loading it into context.
7171 
7272This dynamic filtering is particularly useful for:
7373 
7474* Extracting specific sections from long documents
75* Processing structured data from web pages
75* Processing structured data from webpages
7676* Filtering relevant information from PDFs
7777* Reducing token costs when working with large documents
7878 
from line 508
508508 
509509### Citations
510510 
511Unlike web search where citations are always enabled, citations are optional for web fetch and disabled by default. Set `"citations": {"enabled": true}` to enable Claude to cite specific passages from fetched documents.
511Unlike web search, where citations are always enabled, citations are optional for web fetch and disabled by default. Set `"citations": {"enabled": true}` to allow Claude to cite specific passages from fetched documents.
512512 
513513<Note>
514514 When displaying API outputs directly to end users, include citations to the original source. If you are making modifications to API outputs, including by reprocessing or combining them with your own material before displaying them to end users, display citations as appropriate based on consultation with your legal team.
from line 597
597597* `retrieved_at`: Timestamp when the content was retrieved
598598 
599599<Note>
600 The web fetch tool caches results to improve performance and reduce redundant requests. The content returned may not always reflect the latest version available at the URL. The cache behavior is managed automatically and may change over time to optimize for different content types and usage patterns. To fetch fresh content, set `"use_cache": false` (see [Cache bypass](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#cache-bypass)).
600 The web fetch tool caches results to improve performance and reduce redundant requests. The content returned might not always reflect the latest version available at the URL. The cache behavior is managed automatically and may change over time to optimize for different content types and usage patterns. To fetch fresh content, set `"use_cache": false` (see [Cache bypass](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#cache-bypass)).
601601</Note>
602602 
603603For PDF documents, content is returned as base64-encoded data:
from line 625
625625 
626626### Errors
627627 
628When the web fetch tool encounters an error, the Claude API returns a 200 (success) response with the error represented in the response body. Claude sees the error result and continues the turn. For example:
628When the web fetch tool encounters an error, the Claude API returns a 200 (success) response with the error represented in the response body. Claude receives the error result and continues the turn. For example:
629629 
630630```json Output
631631{
from line 668
668668 Works with `web_fetch_20250910`, `web_fetch_20260209`, `web_fetch_20260309`, and `web_fetch_20260318`.
669669</Note>
670670 
671The optional `url_sources` parameter lets you turn off any of the three allowed sources, or limit tool results to certain tools. It has one key per source, and each key defaults to `{"type": "all"}`:
671The optional `url_sources` parameter lets you turn off any of the three allowed sources, or limit tool results to certain tools. It has one key for each source, and every key defaults to `{"type": "all"}`:
672672 
673673* `user_input`: URLs in user messages. Its `type` is `"all"` or `"none"`.
674674* `client_tool_results`: URLs in client-side tool results. Its `type` is `"all"`, `"none"`, or an `"only"` or `"except"` filter that names tools, as in the following example.
from line 970
970970event: content_block_delta
971971data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"url\":\"https://example.com/article\"}"}}
972972 
973// Pause while fetch executes
973// Pause while fetch runs
974974 
975975// Fetch results streamed
976976event: content_block_start
from line 1007
10071007 
10081008Example token usage for typical content:
10091009 
1010* Average web page (10 kB): \~2,500 tokens
1010* Average webpage (10 kB): \~2,500 tokens
10111011* Large documentation page (100 kB): \~25,000 tokens
10121012* Research paper PDF (500 kB): \~125,000 tokens
10131013 
from line 1015
10151015 
10161016<CardGroup>
10171017 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool" title="Code execution tool" icon="code">
1018 Run Python and bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
1018 Run Python and Bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.
10191019 </Card>
10201020 
10211021 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools" title="Server tools" icon="cloud">
1022 Work with Anthropic-executed tools: server\_tool\_use blocks, pause\_turn continuation, and domain filtering.
1022 Work with tools that Anthropic runs: `server_tool_use` blocks, `pause_turn` continuation, and domain filtering.
10231023 </Card>
10241024 
10251025 <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference" title="Tool reference" icon="book">

agents-and-tools/tool-use/web-search-tool Changed · +10 / -10 lines

from line 219
219219 client = Anthropic::Client.new
220220 
221221 message = client.messages.create(
222 model: "claude-opus-5-5",
222 model: Anthropic::Model::CLAUDE_OPUS_5_5,
223223 max_tokens: 4096,
224224 messages: [
225225 { role: "user", content: "Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio." }
from line 391
391391 client = Anthropic::Client.new
392392 
393393 message = client.messages.create(
394 model: "claude-opus-5-5",
394 model: Anthropic::Model::CLAUDE_OPUS_5_5,
395395 max_tokens: 1024,
396396 messages: [
397397 { role: "user", content: "What's the weather in NYC?" }
from line 436
436436}
437437```
438438 
439All web search tool versions accept `allowed_callers`, which controls whether Claude calls web search directly or from code execution through [dynamic filtering](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#dynamic-filtering). On `web_search_20260209` and later it defaults to `["code_execution_20260120"]` instead of `["direct"]`. See [Server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#zdr-and-allowed-callers) for how to configure it. `web_search_20260318` and later also accept [`response_inclusion`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#response-inclusion).
439All web search tool versions accept `allowed_callers`, which controls whether Claude calls web search directly or from code execution through [dynamic filtering](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#dynamic-filtering). On `web_search_20260209` and later it defaults to `["code_execution_20260120"]` instead of `["direct"]`. See [ZDR and allowed\_callers](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#zdr-and-allowed-callers) for how to configure it. `web_search_20260318` and later also accept [`response_inclusion`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#response-inclusion).
440440 
441441### Max uses
442442 
from line 460
460460* `city`: The city name
461461* `region`: The region or state
462462* `country`: The two-letter [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code. The API rejects unsupported country codes with a 400 error.
463* `timezone`: The [IANA timezone ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
463* `timezone`: The [IANA time zone ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
464464 
465465On Claude Managed Agents, the `web_search` entry of the agent toolset accepts a `user_location` object with the same fields. The API rejects an unsupported `country` code with a 400 error when you create or update the agent, or when you create or update a session that supplies the setting. See the [web tool settings](https://platform.claude.com/docs/en/managed-agents/tools-web-restrictions#settings).
466466 
from line 551
551551}
552552```
553553 
554This example shows a direct search. When a search runs through [dynamic filtering](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#dynamic-filtering), the response also contains the [code execution tool's](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) result blocks, and each nested `server_tool_use` and `web_search_tool_result` pair carries a `caller` field identifying the code execution call that made it.
554This example shows a direct search. When a search runs through [dynamic filtering](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#dynamic-filtering), the response also contains the result blocks of the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool), and each nested `server_tool_use` and `web_search_tool_result` pair carries a `caller` field identifying the code execution call that made it.
555555 
556556### Search results
557557 
from line 619
619619 
620620## Streaming
621621 
622With streaming enabled, you'll receive search events as part of the stream. There will be a pause while the search runs:
622With streaming enabled, you'll receive search events as part of the stream. There is a pause while the search runs:
623623 
624624```sse Output
625625event: message_start
from line 637
637637event: content_block_delta
638638data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"query\":\"latest quantum computing breakthroughs 2025\"}"}}
639639 
640// Pause while search executes
640// Pause while search runs
641641 
642642// Search results streamed
643643event: content_block_start
from line 650
650650 
651651You can include the web search tool in the [Messages Batches API](https://platform.claude.com/docs/en/build-with-claude/batch-processing). Web search tool calls through the Messages Batches API are priced the same as those in regular Messages API requests.
652652 
653To protect shared capacity, the Batches API throttles web search requests per organization, so large batches with many searches might take longer to complete. You can see your organization's web search rate limit on the [Rate limits](https://platform.claude.com/usage/limits) page in the Claude Console. To request a higher limit, contact sales from that page.
653To protect shared capacity, the Batches API throttles web search requests for each organization, so large batches with many searches might take longer to complete. You can see your organization's web search rate limit on the [Rate limits](https://platform.claude.com/usage/limits) page in the Claude Console. To request a higher limit, contact sales from that page.
654654 
655655## Usage and pricing
656656 
from line 670
670670}
671671```
672672 
673Web search is available on the Claude API for **$10 per 1,000 searches**, plus standard token costs for search-generated content. Web search results retrieved throughout a conversation are counted as input tokens, in search iterations executed during a single turn and in subsequent conversation turns.
673Web search is available on the Claude API for **$10 USD per 1,000 searches**, plus standard token costs for search-generated content. Web search results retrieved throughout a conversation are counted as input tokens, in search iterations executed during a single turn and in subsequent conversation turns.
674674 
675675Each web search counts as one use, regardless of the number of results returned. If an error occurs during web search, the web search will not be billed.
676676 
from line 682
682682 </Card>
683683 
684684 <Card title="Server tools" icon="tool" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools">
685 Work with Anthropic-executed tools: server\_tool\_use blocks, pause\_turn continuation, and domain filtering.
685 Work with tools that Anthropic runs: `server_tool_use` blocks, `pause_turn` continuation, and domain filtering.
686686 </Card>
687687 
688688 <Card title="Tool reference" icon="book" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference">

api/beta-headers Changed · +6 / -6 lines

from line 22
2222content-type: application/json
2323```
2424 
25Each feature's documentation states the exact beta name to send. The [API overview](https://platform.claude.com/docs/en/api/overview) lists the APIs currently in beta.
25Each feature's documentation states the exact beta name to send. The [API overview](https://platform.claude.com/docs/en/api/overview) lists the APIs in beta.
2626 
27The following examples show the same request with cURL, the `ant` CLI, and the SDK, using the [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) beta as the example. The SDK takes beta names through `betas` (csharp, go: `Betas`; java: `.addBeta()`) and sends the `anthropic-beta` header for you:
27The following example sends a request with the [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) beta. The SDK takes beta names through `betas` (csharp, go: `Betas`; java: `.addBeta()`) and sends the `anthropic-beta` header for you:
2828 
2929<CodeGroup>
3030 ```bash cURL
from line 141
141141 client = Anthropic::Client.new
142142 
143143 message = client.beta.messages.create(
144 model: "claude-opus-5-5",
144 model: Anthropic::Model::CLAUDE_OPUS_5_5,
145145 max_tokens: 1024,
146146 messages: [{role: "user", content: "Hello, Claude"}],
147147 betas: ["context-management-2025-06-27"]
from line 185
185185On Amazon Bedrock, where beta names go depends on the API you call:
186186 
187187* [Claude in Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock) (`bedrock-mantle` endpoints) takes them in the `anthropic-beta` header.
188* The [InvokeModel API](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy) reads them from the request body, not from a header. List them in the body's `anthropic_beta` array, one name per element, for example `"anthropic_beta": ["feature1", "feature2"]`.
188* The [InvokeModel API](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy) reads them from the request body, not from a header. List them in the body's `anthropic_beta` array, one name for each element, for example `"anthropic_beta": ["feature1", "feature2"]`.
189189 
190190### Endpoint-specific headers
191191 
from line 232
232232 </Card>
233233 
234234 <Card title="API overview" icon="compass" href="https://platform.claude.com/docs/en/api/overview">
235 Explore the Claude API's features, including the APIs currently in beta.
235 Explore the Claude API's features, including the APIs in beta.
236236 </Card>
237237</CardGroup>
238238 

api/claude-code/routines-fire Changed · +2 / -2 lines

## Before you start ## Before you begin

from line 27
2727| Path namespace | `/v1/claude_code/...` | `/v1/...` |
2828| Stability | Experimental | Stable or standard beta |
2929 
30## Before you begin
30## Before you start
3131 
3232To call this endpoint, you need:
3333 
from line 156
156156## See also
157157 
158158* [Automate work with routines](https://code.claude.com/docs/en/routines) in the Claude Code documentation
159* [Errors](https://platform.claude.com/docs/en/api/errors)
159* [Claude API errors](https://platform.claude.com/docs/en/api/errors)
160160 
Feedback