Follow Discord
Sweep 20 Nov 2026 · 19:55Z Build v2.1.330 547 read Stable v2.1.323 Latest v2.1.330 Next v2.1.330 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · api

One read of Claude Developer Platformapi-20261118T153716Z

60 pages moved out of 923 read.

Pages moved 60 significant first
Pages read 923 in this capture
Captured 15:37 UTC
Corpus hash 80e78946625e corpus-hash

What this read moved

26-50 of 60, page 2 of 3

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

manage-claude/oauth-apps/organization-billing-connections Changed · +5 / -9 lines

from line 41
4141 
4242## Setup process
4343 
44You do these three steps once. They register your app with Anthropic. After them, [Which user profile to link](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#which-user-profile-to-link) explains a rule that you need before you create user profiles.
44You do these three steps once. They register your app with Anthropic. You need the Admin role in your organization for all three. After them, [Which user profile to link](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#which-user-profile-to-link) explains a rule that you need before you create user profiles.
4545 
4646### Step 1: Create the app
4747 
from line 580
580580 messages: [{ role: "user", content: "Hello, Claude" }],
581581 betas: ["user-profiles-billing-2026-10-01"],
582582 user_profile_id: "uprof_01HV9Z",
583 // @ts-expect-error: billing_policy isn't in the SDK's types yet
584583 billing_policy: { type: "billing_policy", bill_to: "user_profile" }
585584 });
586585 
from line 601
602601 Betas = ["user-profiles-billing-2026-10-01"],
603602 UserProfileID = "uprof_01HV9Z",
604603 };
605 // billing_policy isn't in the SDK's types yet
606604 var body = new Dictionary<string, JsonElement>(parameters.RawBodyData)
607605 {
608606 ["billing_policy"] = JsonSerializer.SerializeToElement(
from line 891
893891 messages: [{ role: "user", content: "Hello, Claude" }],
894892 betas: ["user-profiles-billing-2026-10-01"],
895893 user_profile_id: "uprof_01HV9Z",
896 // @ts-expect-error: billing_policy isn't in the SDK's types yet
897894 billing_policy: { type: "billing_policy", bill_to: "self" }
898895 });
899896 
from line 912
915912 Betas = ["user-profiles-billing-2026-10-01"],
916913 UserProfileID = "uprof_01HV9Z",
917914 };
918 // billing_policy isn't in the SDK's types yet
919915 var body = new Dictionary<string, JsonElement>(parameters.RawBodyData)
920916 {
921917 ["billing_policy"] = JsonSerializer.SerializeToElement(
from line 1757
17611757 
17621758 * **The spend cap for your app:** On the page for your app under [Linked platforms](https://platform.claude.com/linked-platforms), they can set or raise the spend cap. A cap set there replaces any default cap that they set for all linked platforms.
17631759 * **The organization’s Monthly spend limit:** Under [Spend limits](https://platform.claude.com/settings/billing#spend-limits), they can raise it.
1764 * **The credit balance:** On their [Billing](https://platform.claude.com/settings/billing) page, they can see their credit balance and buy credits. Some credits can’t pay for these requests: see [Which credits can pay](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#which-credits-can-pay).
1760 * **The credit balance:** On their [Billing](https://platform.claude.com/settings/billing) page, they can see their credit balance and buy credits. A purchase can take some time to apply, so a request sent soon after it can still get this 402. If so, try again later. Some credits can’t pay for these requests: see [Which credits can pay](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#which-credits-can-pay).
17651761 
17661762* `503 overloaded_error`: Anthropic couldn’t confirm right now whether the customer can be billed. Retry with backoff and honor the `retry-after` header. The request wasn’t served or billed.
17671763 
from line 1777
17811777 
17821778* **Your request.** The request must authenticate as your OAuth app’s operator service account (Step 3). A [connection’s access token](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#oauth-tokens-for-each-connection) also authenticates as that service account. A request that authenticates any other way is refused. Examples are a different service account and an API key that isn’t bound to that service account. If the `anthropic-user-profile-id` header names one of your profiles that isn’t linked, the request is refused. If the credential or the header is wrong, correct the request. A new connection doesn’t help.
17831779* **The connection.** The customer hasn’t linked through this app, or the connection has ended: an administrator of their organization or of yours ended it, or your back end did. An ended connection displays as **Unlinked** on your [User profiles](https://platform.claude.com/user-profiles) page. A profile linked only through your test app isn’t linked to your production app. Stop billing that customer until they link. A connection’s access token is limited to that connection, so after the customer links again, use the access token of the new connection. If your app has [turned off operator-only authentication](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#turn-off-operator-only-authentication), you can bill a customer only with their connection’s access token. Then a customer for whom you hold no working token of a `billing:attribution` connection displays as **Linked**, but must approve again, as [Link a customer again](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#connect-a-customer-again) describes.
1784* **The customer’s organization.** It must be an [eligible customer](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#eligible-customers-and-endpoints). You can’t see that from your side, so ask your Anthropic account team.
1780* **The customer’s organization.** It must be an [eligible customer](https://platform.claude.com/docs/en/manage-claude/oauth-apps/organization-billing-connections#eligible-customers-and-endpoints). You can’t see the organization’s status from your side. A customer’s new organization can link before it has billing set up. Until then, requests that bill it get this 403, not the out-of-credit 402. Ask the customer to buy credits on their [Billing](https://platform.claude.com/settings/billing) page in the Claude Console, and then send the request again. A purchase can take some time to apply, so if you still get this 403 or that out-of-credit 402 (`linked_organization_spend_limit_reached`), try again later. If that doesn’t help, ask your Anthropic account team.
17851781 
1786A new connection usually works at once, but it can take about 10 seconds after the exchange in Step 8. If a request is refused with `user_profile_not_billable` in those 10 seconds, send it again. After that, waiting or retrying doesn’t change the result. Log the whole `error.message` and the `request-id` response header of each refused request. If a customer whose connection displays as **Linked** is still refused and your request is correct, send a refused request’s `request-id` to your Anthropic account team, so that Anthropic can look up why it was refused.
1782A new connection usually works at once, but it can take about 10 seconds after the exchange in Step 8. If a request is refused with `user_profile_not_billable` in those 10 seconds, send it again. After that, waiting or retrying doesn’t change the result until the cause is fixed. Log the whole `error.message` and the `request-id` response header of each refused request. If a customer whose connection displays as **Linked** is still refused and your request is correct, send a refused request’s `request-id` to your Anthropic account team, so that Anthropic can look up why it was refused.
17871783 
17881784## Your customer’s view
17891785 

manage-claude/organization-webhooks Changed · +5 / -2 lines

from line 15
1515 Event delivery isn’t live: Anthropic doesn’t send the two events, so an endpoint you register receives nothing. You can register endpoints and build your handler from the event format on this page.
1616</Note>
1717 
18Any member of your organization can list and view organization webhook endpoints with the API, but only members with the admin, owner, or primary owner role can create, change, or delete them, or replace their signing secret.
19 
2018## Before you start
2119 
2220You need the following:
from line 26
2826 * An [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys).
2927 * An [OAuth bearer token](https://platform.claude.com/docs/en/manage-claude/admin-api#oauth-bearer-token) with the `org:admin` scope.
3028 * A [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) that isn’t scoped to a workspace.
29 
30With an Admin API key, you can make every request in [Manage endpoints](https://platform.claude.com/docs/en/manage-claude/organization-webhooks#manage-endpoints). With an `org:admin` token, you can make the same requests. If the token is bound to a workspace other than your organization’s [Default Workspace](https://platform.claude.com/docs/en/manage-claude/workspaces#how-workspaces-work), you can’t make any of them. With a personal or service account key, the requests you can make depend on the account’s [organization role](https://platform.claude.com/docs/en/manage-claude/admin-api#organization-roles-and-permissions):
31 
32* To list or view webhook endpoints: `claude_code_user`, `developer`, or `admin`
33* To create, change, or delete webhook endpoints, or to replace a signing secret: `admin`
3134 
3235## Event types
3336 

manage-claude/usage-cost-analytics-api Changed · +24 / -7 lines

from line 799
799799 
800800## Migrate from the Usage and Cost API
801801 
802This section is for Claude Console organizations that call the legacy [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api) (`/v1/organizations/usage_report/messages` and `/v1/organizations/cost_report`). Your Admin API key, the `anthropic-version` header, `starting_at` and `ending_at`, the bucket width values (`1m`, `1h`, `1d`), bracket notation, the pagination field names, and the token and cost field names carry over. What changes:
802This section is for organizations that call the legacy [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api) (`/v1/organizations/usage_report/messages` and `/v1/organizations/cost_report`). Your credential and the `anthropic-version` header carry over. So do the names `starting_at` and `ending_at`, the `[]` suffix on array parameters, the pagination field names, and the token and cost field names. The usage endpoint’s bucket widths (`1m`, `1h`, `1d`) carry over too. The following table lists what changes:
803803 
804804| Usage and Cost API | Usage and Cost Analytics API |
805805| ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
from line 818
818818| Cost `service_tier` is `standard` or `batch`; `amount` such as `"123.45"` | The actual tier; `amount` with six decimal places, such as `"123.450000"`, plus `list_amount`. |
819819| Code execution not in the usage report; no request counts | Code execution appears as usage rows with `model: null`; adds `requests` on both endpoints and `total_tokens` on usage rows |
820820 
821Two things differ for a Claude Enterprise organization:
822 
823* **Workspaces and API keys:** The Usage and Cost Analytics API returns `null` for `workspace_id` and `api_key_id` (see [How results are shaped](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api#how-results-are-shaped)), so the table’s row on the default workspace doesn’t apply.
824* **Usage totals:** The Usage and Cost Analytics API counts usage that the legacy usage report leaves out, so its usage totals can be higher. See [Claude Enterprise organizations](https://platform.claude.com/docs/en/manage-claude/usage-cost-api#claude-enterprise-organizations).
825 
821826To reproduce the legacy daily report, request `time_bucket_width=1d` with the same `group_by[]`, page through with `limit=1000`, then group rows by `starting_at` and fill missing days with zeros. Add `order_by=time&order=asc` to get the days in order. Daily usage by model for 1 week, before:
822827 
823828```bash cURL
from line 1295
12901295 )
12911296 
12921297 for row in rows:
1293 print(f"{row.actor.user_id}: {row.amount}")
1298 if row.actor.type == "user_actor":
1299 print(f"{row.actor.user_id}: {row.amount}")
12941300 ```
12951301 
12961302 ```typescript TypeScript
from line 1309
13031309 });
13041310 
13051311 for await (const row of rows) {
1306 console.log(`${row.actor.user_id}: ${row.amount}`);
1312 if (row.actor.type === "user_actor") {
1313 console.log(`${row.actor.user_id}: ${row.amount}`);
1314 }
13071315 }
13081316 ```
13091317 
from line 1329
13211329 
13221330 await foreach (var row in page.Paginate())
13231331 {
1324 Console.WriteLine($"{row.Actor.UserID}: {row.Amount}");
1332 if (row.Actor.TryPickBetaAnalyticsUser(out var user))
1333 {
1334 Console.WriteLine($"{user.UserID}: {row.Amount}");
1335 }
13251336 }
13261337 ```
13271338 
from line 1347
13361347 
13371348 for rows.Next() {
13381349 row := rows.Current()
1339 fmt.Printf("%s: %s\n", row.Actor.UserID, row.Amount)
1350 if user, ok := row.Actor.AsAny().(anthropic.BetaAnalyticsUserActor); ok {
1351 fmt.Printf("%s: %s\n", user.UserID, row.Amount)
1352 }
13401353 }
13411354 if err := rows.Err(); err != nil {
13421355 log.Fatal(err)
from line 1371
13581371 var rows = client.beta().organization().analytics().userCostReport().list(params);
13591372 
13601373 for (var row : rows.autoPager()) {
1361 IO.println(row.actor().userId() + ": " + row.amount());
1374 row.actor().user().ifPresent(user ->
1375 IO.println(user.userId() + ": " + row.amount())
1376 );
13621377 }
13631378 }
13641379 ```
from line 1402
13871402 )
13881403 
13891404 page.auto_paging_each do |row|
1390 puts "#{row.actor.user_id}: #{row.amount}"
1405 if row.actor.type == :user_actor
1406 puts "#{row.actor.user_id}: #{row.amount}"
1407 end
13911408 end
13921409 ```
13931410</CodeGroup>

manage-claude/usage-cost-api Changed · +34 / -11 lines

### Claude Enterprise organizations

from line 1
11---
22title: Usage and Cost API
33url: https://platform.claude.com/docs/en/manage-claude/usage-cost-api
4description: The legacy Admin API usage and cost report endpoints for Claude Console organizations. For new integrations, use the Usage and Cost Analytics API.
4description: The legacy Admin API usage and cost report endpoints. For new integrations, use the Usage and Cost Analytics API.
55---
66 
77<Tip>
from line 12
1212 The Usage and Cost API (`/v1/organizations/usage_report/messages` and `/v1/organizations/cost_report`) is a legacy API and remains supported. For new integrations, use the [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api), which reports usage and cost with more grouping and filtering dimensions. To move an existing integration, see [Migrate from the Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api#migrate-from-usage-cost-api).
1313</Note>
1414 
15The Usage and Cost Admin API provides programmatic and granular access to historical API usage and cost data for your organization. This data is similar to the information available on the [Usage](https://platform.claude.com/usage) page (`platform.claude.com/usage`) and the [Cost](https://platform.claude.com/cost) page (`platform.claude.com/cost`) in the Claude Console.
15The Usage and Cost API provides programmatic and granular access to historical API usage and cost data for your organization. For Claude Console organizations, this data is similar to what the Claude Console shows on the [Usage](https://platform.claude.com/usage) page (`platform.claude.com/usage`) and the [Cost](https://platform.claude.com/cost) page (`platform.claude.com/cost`).
1616 
1717This API allows you to better monitor, analyze, and optimize your Claude implementations:
1818 
from line 23
2323* **Advanced analysis:** Perform deeper data analysis than what’s available in Console
2424 
2525<Check>
26 **Admin API credentials required.** These endpoints are part of the Admin API. You can access them using an [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys), an OAuth token with the `org:admin` scope, or a personal or service account key that isn’t scoped to a workspace; workspace API keys don’t work. See [Authentication](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication) for details.
27</Check>
26 **Authentication**
2827 
29Claude Enterprise organizations use an Analytics API key with a different API instead; see [Which API do you need?](https://platform.claude.com/docs/en/manage-claude/usage-cost-api#which-api-do-you-need).
28 These endpoints are part of the Admin API. Claude Console organizations can access them using any of these credentials:
3029 
30 * An [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys)
31 * An OAuth token with the `org:admin` scope
32 * A personal or service account key that isn’t scoped to a workspace
33 
34 Workspace API keys don’t work. See [Authentication](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication) for details.
35 
36 Claude Enterprise organizations use an Analytics API key, and the usage endpoint leaves out some of their usage; see [Claude Enterprise organizations](https://platform.claude.com/docs/en/manage-claude/usage-cost-api#claude-enterprise-organizations).
37</Check>
38 
3139<Note>
3240 **Claude Platform on AWS:** The Usage and Cost API endpoints are not available. Use the [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api).
3341</Note>
from line 46
3846 
3947## Which API do you need?
4048 
41The API to use depends on which Claude product your organization uses:
49The APIs you can call, and the key each one takes, depend on which Claude product your organization uses:
4250 
43| Your organization | API | Key type |
44| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
45| Claude Console (Claude Platform) | The [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api) (recommended), or the legacy Usage and Cost Admin API described on this page | Admin API key (`sk-ant-admin01-...`) or another [Admin API credential](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication) |
46| Claude Enterprise (claude.ai) | The [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api) (recommended), or the [Claude Enterprise Analytics API](https://platform.claude.com/docs/en/api/beta/organization/analytics) cost and usage endpoints (legacy) | Analytics API key |
51| API | Claude Console (Claude Platform) | Claude Enterprise (claude.ai) |
52| ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
53| [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api) (recommended) | Admin API key (`sk-ant-admin01-...`) or another [Admin API credential](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication) | Analytics API key |
54| Usage and Cost API (legacy), which this page documents | Admin API key or another Admin API credential | Analytics API key |
55| [Claude Enterprise Analytics API](https://platform.claude.com/docs/en/api/beta/organization/analytics) cost and usage endpoints (legacy) | Not available | Analytics API key |
4756 
4857Claude Enterprise parent organizations do not appear in Claude Console and carry no Admin API keys, so for them the Analytics API key is the only path to this data. See [Analytics APIs](https://platform.claude.com/docs/en/manage-claude/analytics-api) for how to create each key type and which plans the Claude Enterprise cost data applies to.
58 
59### Claude Enterprise organizations
60 
61A Claude Enterprise organization uses one [Analytics API key](https://platform.claude.com/docs/en/manage-claude/analytics-api#get-access-to-the-claude-enterprise-analytics-api) for all three APIs in the table. For these APIs, the key reads only the organization it was created in. Send it in the `x-api-key` header, as the examples on this page do with an Admin API key.
62 
63For these organizations, the two endpoints don’t cover the same usage, so you can’t reconcile one against the other:
64 
65* **[Usage endpoint](https://platform.claude.com/docs/en/manage-claude/usage-cost-api#usage-api):** It leaves out usage from some Claude products, so its totals can be lower than the organization’s usage. For example, it doesn’t count the following:
66 
67 * Cowork
68 * Claude Code in the terminal, IDEs, and the desktop app
69 * Text chats in Claude on the web, desktop, and mobile
70 
71* **[Cost endpoint](https://platform.claude.com/docs/en/manage-claude/usage-cost-api#cost-api):** With a `starting_at` on or after October 1, 2025, it covers usage-based charges across Claude products, including the three in the previous list. It doesn’t include seat fees or usage that a seat covers.
4972 
5073## Partner solutions
5174 

manage-claude/user-profiles Changed · +3 / -3 lines

from line 157
157157 var profile = client.userProfiles().create(params);
158158 
159159 IO.println(profile.id());
160 // ...
160 // ...
161161 }
162162 ```
163163 
from line 399
399399 
400400Link each AWS account that sends requests to Claude in Amazon Bedrock, and each Google Cloud project that sends requests to Claude Models on Google Cloud (Google managed), to the Anthropic organization that creates your profiles:
401401 
4021. An admin or owner of that organization starts the link in the Verification Portal at `portal.anthropic.com`, under **Linked accounts**.
4021. An admin of that organization starts the link in the Verification Portal at `portal.anthropic.com`, under **Linked accounts**.
4034032. Someone who can manage IAM in the AWS account or Google Cloud project runs a command that the portal provides.
4043. The admin or owner completes the verification in the portal.
4043. The admin completes the verification in the portal.
405405 
406406Programs that apply to a profile apply to an account’s requests only after the account is linked and the portal shows it as **Linked**. Those programs include the ones an end customer’s organization is approved for after the end customer [links the profile to that organization](https://platform.claude.com/docs/en/manage-claude/user-profiles-verification-portal) and, for Cyber Verification Program access levels, turns them on for the profile in the portal.
407407 

manage-claude/wif-reference Changed · +3 / -3 lines

from line 84
8484 
8585The active profile name resolves in this order:
8686 
871. `$ANTHROPIC_PROFILE`
882. The contents of `<config_dir>/active_config` (a one-line file written by `ant profile activate <name>`)
893. The literal name `default`
871. `$ANTHROPIC_PROFILE`.
882. The contents of `<config_dir>/active_config`. `ant profile activate <name>` writes this one-line file. So does `ant auth login` when it names a profile or when the file doesn’t exist yet.
893. The literal name `default`.
9090 
9191Claude Code and the Claude Agent SDK honor this same resolution order, so a federation profile configured here also authenticates those tools without additional setup.
9292 

managed-agents/choosing-an-environment Changed · +3 / -3 lines

from line 46
4646 
4747## Start with a cloud environment
4848 
49If you’re not sure which to choose, or you’re new to Claude Managed Agents, start with a [cloud environment](https://platform.claude.com/docs/en/managed-agents/environments), as the [quickstart](https://platform.claude.com/docs/en/managed-agents/quickstart) does. Anthropic runs an isolated container for each session, with common languages and tools already installed, so there is nothing for you to host. Choose a self-hosted sandbox only if tools must run on infrastructure you control.
49If you’re not sure which to choose or you’re new to Claude Managed Agents, start with a [cloud environment](https://platform.claude.com/docs/en/managed-agents/environments). The quickstart, [Get started with Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/quickstart), uses a cloud environment. Anthropic runs an isolated container for each session, with common languages and tools already installed, so there is nothing for you to host. Choose a self-hosted sandbox only if tools must run on infrastructure you control.
5050 
5151## Compare the options
5252 
from line 85
8585 
8686You also give up these cloud environment features:
8787 
88* [`file` and `github_repository` session resources](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#session-resources). You [stage input files yourself](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#stage-files-for-a-session), and you are responsible for mounting your own GitHub repository too.
88* [`file` and `github_repository` session resources](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#session-resources). You [stage input files yourself](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#stage-files-for-a-session), and you are responsible for mounting your own GitHub repository too.
8989* [Repository skill discovery](https://platform.claude.com/docs/en/managed-agents/skills#load-skills-from-a-github-repository).
9090* [Environment variable credentials](https://platform.claude.com/docs/en/managed-agents/vaults#add-a-credential) in vaults.
9191* The [preinstalled runtimes and packages](https://platform.claude.com/docs/en/managed-agents/cloud-sandboxes-reference) of a cloud sandbox. A self-hosted sandbox has whatever your worker provides.
from line 92
9292 
9393## Differences on Claude Platform on AWS
9494 
95If you use Claude Managed Agents through Claude Platform on AWS, Anthropic still operates the service. There, a self-hosted sandbox can’t use memory stores, workers don’t use an environment key, and MCP tunnels aren’t available. See [Claude Managed Agents on Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws#claude-managed-agents) and [Features not supported](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws#features-not-supported).
95If you use Claude Managed Agents through Claude Platform on AWS, Anthropic still operates the service. There, memory stores aren’t available in a self-hosted sandbox, workers don’t use an environment key, and MCP tunnels aren’t available. See [Claude Managed Agents on Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws#claude-managed-agents) and [Features not supported](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws#features-not-supported).
9696 
9797## Differences on Claude Models on Google Cloud (Anthropic managed)
9898 

managed-agents/self-hosted-sandboxes-custom-tools Changed · +32 / -6 lines

from line 42
4242The environment key authorizes posting custom tool results, so your Claude API key stays off the worker host.
4343 
4444<Note>
45 To serve custom tools, you need the SDK worker. The `ant` CLI worker has no way to register a custom tool implementation. In the sandbox-per-session pattern, [run the SDK worker inside the sandbox](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-the-sdk-worker-inside-the-sandbox).
45 To serve custom tools, you need the SDK worker. The `ant` CLI worker has no way to register a custom tool implementation. In the sandbox-per-session pattern, [run the SDK worker inside the sandbox](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#run-the-sdk-worker-inside-the-sandbox).
4646</Note>
4747 
4848## Serve a custom tool
from line 68
6868 </Step>
6969 
7070 <Step title="Register the implementation with the worker">
71 Pass the tool through the worker’s `tools` (go: `ToolsFunc`) factory (see [`EnvironmentWorker`](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-worker)), alongside the built-in toolset:
71 This step uses [`EnvironmentWorker`](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-worker), which only the Python, TypeScript, and Go SDKs have. Pass the tool alongside the built-in toolset through the worker’s `tools` (go: `ToolsFunc`) factory. The samples use `/workspace` as the working directory, which must exist before the worker starts. [Run an always-on worker](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-an-always-on-worker) says how to create the directory and what to use on macOS.
7272 
7373 <CodeGroup exclude="shell, csharp, java, php, ruby">
74 <CodeGroupItem language="cURL">
75 A worker is a long-running process, not a single HTTP request. To serve custom tools, use `EnvironmentWorker` in the Python, TypeScript, or Go SDK.
76 </CodeGroupItem>
77 
78 <CodeGroupItem language="CLI">
79 The `ant` CLI worker can’t serve custom tools. Use `EnvironmentWorker` in the Python, TypeScript, or Go SDK.
80 </CodeGroupItem>
81 
7482 ```python Python
7583 import asyncio
7684 import os
from line 251
243251 List the MCP server’s tools and declare each one as a `custom` tool. The MCP `name`, `description`, and `inputSchema` map one to one onto the custom tool’s fields. If the server paginates its tool list, declare every page; the worker must list the same pages.
244252 
245253 <CodeGroup exclude="shell">
254 <CodeGroupItem language="cURL">
255 Listing an MCP server’s tools and declaring each one needs more logic than a single shell command. Use an MCP SDK and the Anthropic SDK to run it.
256 </CodeGroupItem>
257 
258 <CodeGroupItem language="CLI">
259 Listing an MCP server’s tools and declaring each one needs more logic than a single shell command. Use an MCP SDK and the Anthropic SDK to run it.
260 </CodeGroupItem>
261 
246262 ```python Python
247263 import asyncio
248264 from typing import Any, cast
from line 688
672688 </Step>
673689 
674690 <Step title="Serve the tools from the worker">
675 Connect to the same MCP server at startup, convert its tools with `async_mcp_tool()` (typescript: `mcpTools()`; go: `mcp.NewBetaTools()`), and register them alongside `beta_agent_toolset_20260401()` (typescript: `betaAgentToolset20260401()`; go: `agenttoolset.BetaAgentToolset20260401()`). Keep one MCP session open for the life of the worker.
691 This step uses `EnvironmentWorker`, which only the Python, TypeScript, and Go SDKs have. Connect to the same MCP server at startup. Convert its tools with `async_mcp_tool()` (typescript: `mcpTools()`; go: `mcp.NewBetaTools()`), and register them alongside `beta_agent_toolset_20260401()` (typescript: `betaAgentToolset20260401()`; go: `agenttoolset.BetaAgentToolset20260401()`). Keep one MCP session open for the life of the worker.
676692 
693 The samples use `/workspace` as the working directory, which must exist before the worker starts. [Run an always-on worker](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-an-always-on-worker) says how to create the directory and what to use on macOS.
694 
677695 <CodeGroup exclude="shell, csharp, java, php, ruby">
696 <CodeGroupItem language="cURL">
697 A worker is a long-running process, not a single HTTP request. To serve custom tools, use `EnvironmentWorker` in the Python, TypeScript, or Go SDK.
698 </CodeGroupItem>
699 
700 <CodeGroupItem language="CLI">
701 The `ant` CLI worker can’t serve custom tools. Use `EnvironmentWorker` in the Python, TypeScript, or Go SDK.
702 </CodeGroupItem>
703 
678704 ```python Python
679705 import asyncio
680706 import os
from line 771
745771 await mcpClient.connect(new StreamableHTTPClientTransport(new URL(MCP_SERVER_URL)));
746772 const { tools } = await mcpClient.listTools();
747773 
748 // The MCP SDK's callTool return type still includes a legacy result shape that
749 // mcpTools does not accept; narrow it. Drop this once MCPClientLike widens.
774 // The MCP SDK's callTool return type includes a legacy result shape that
775 // mcpTools does not accept, so narrow it.
750776 const mcpClientForTools: MCPClientLike = {
751777 callTool: (params) => mcpClient.callTool(params) as Promise<MCPCallToolResultLike>
752778 };
from line 896
870896 
871897When the MCP server reports a tool error, the worker posts an error tool result the model can react to. MCP content with no tool result equivalent, such as audio blocks and resource links, also surfaces as an error.
872898 
873Set a timeout on the MCP client for a faster and clearer failure, as the Python worker example does with `read_timeout_seconds`. See [A wrapped MCP tool call hangs](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#a-wrapped-mcp-tool-call-hangs) for what occurs without one.
899Set a timeout on the MCP client for a faster and clearer failure. See [A wrapped MCP tool call hangs](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#a-wrapped-mcp-tool-call-hangs) for what occurs without one.
874900 
875901### Wrap only servers you operate or trust
876902 

managed-agents/self-hosted-sandboxes-memory Changed · +132 / -44 lines

### Read-only stores ### Conflicts

from line 46
4646* **A worker that mounts memory stores:** Use `ant` CLI 1.33.0 or later, or `EnvironmentWorker` from the Python, TypeScript, or Go SDK.
4747* **A POSIX filesystem:** Windows hosts are not supported, because the worker requires `O_NOFOLLOW` when it opens memory files. Anthropic recommends a case-sensitive filesystem, so that memory paths that differ only in case do not collide. macOS volumes are case-insensitive by default, so such paths collide there.
4848* **A writable `/mnt/memory` directory:** See [Prepare the host](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#prepare-the-host). On macOS, see [Prepare a macOS host](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#prepare-a-macos-host).
49* **The work item’s secret:** If your own code launches the worker, [forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#forward-the-work-items-secret) to it.
49* **The work item’s secret:** If your own code launches the worker, [forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#forward-the-work-items-secret) to it.
5050 
5151<Note>
5252 Memory stores are not available for sessions on self-hosted environments on [Claude Models on Google Cloud (Anthropic managed)](https://platform.claude.com/docs/en/build-with-claude/claude-models-on-google-cloud/anthropic-managed) or [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws).
from line 62
6262sudo mkdir -p /mnt/memory && sudo chown "$USER" /mnt/memory
6363```
6464 
65Do not create the per-store directories yourself. The worker creates each store’s `mount_path` (java, php: `mountPath`; csharp, go: `MountPath`) directory (for example, `/mnt/memory/user-preferences`) when a session starts and removes it when the session ends. If something already exists at that path, the worker refuses to start the session’s work.
65Don’t create any store’s directory yourself. The worker creates each store’s `mount_path` (java, php: `mountPath`; csharp, go: `MountPath`) directory, such as `/mnt/memory/user-preferences`, when it claims a session and removes it when it finishes with that session. If anything already exists at that path, even an empty directory, the worker fails the work item.
6666 
67In the [sandbox-per-session pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-one-sandbox-per-session), the sandbox image needs a writable `/mnt/memory`. You don’t need to bind-mount the memory directories to the host, because the worker uploads their contents to the store before the sandbox exits.
67In the [sandbox-per-session pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session), the sandbox image needs a writable `/mnt/memory`. You don’t need to bind-mount the memory directories to the host, because the store holds the lasting copy of every memory.
6868 
6969### Prepare a macOS host
7070 
7171On macOS, the root volume is read-only, so `mkdir` can’t create `/mnt`. Instead, create `/System/Volumes/Data/mnt/memory` on the data volume, which is writable. Then add a line to `/etc/synthetic.conf`, so that macOS creates `/mnt` as a symbolic link to `/System/Volumes/Data/mnt`. These steps need administrator rights.
7272 
73Without this setup, the worker can’t create a store’s directory, so it fails the work item. The session then stays idle with no error event. See [Memory stores fail to mount](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#memory-stores-fail-to-mount).
73Without this setup, the worker can’t create a store’s directory, so it fails the work item. The session then stays idle with no error event. See [Memory stores fail to mount or sync](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#memory-stores-fail-to-mount).
7474 
7575<Steps>
7676 <Step title="Create the directory on the data volume">
from line 88
8888 
8989 * If a line reads `mnt^ISystem/Volumes/Data/mnt$`, this step is already done. Go to the next step.
9090 * If another line starts with `mnt`, stop. Something else on this Mac already defines `/mnt`.
91 * If the last line doesn’t end with `$`, run `echo | sudo tee -a /etc/synthetic.conf` to end it.
92 * If it prints nothing or reports `No such file or directory`, continue. The `printf` command creates the file if it’s missing.
91 * If the last line doesn’t end with `$`, run `echo | sudo tee -a /etc/synthetic.conf` to end it. Then, add the line.
92 * If it prints nothing or reports `No such file or directory`, add the line. The following command creates the file if it’s missing.
93 * Otherwise, add the line.
9394 
94 Then add the line, unless one of the first two cases applies. Run this command only once, because each run appends another line.
95 To add the line, run this command. Run it only once, because each run appends another line.
9596 
9697 ```bash
9798 printf 'mnt\tSystem/Volumes/Data/mnt\n' | sudo tee -a /etc/synthetic.conf
from line 124
123124 
124125### Isolate sessions that share a store
125126 
126Two sessions cannot mount the same store on one host at the same time, because both need the same path. If your sessions attach the same store, run one session for each filesystem. Giving each session [its own sandbox](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-one-sandbox-per-session) satisfies this rule.
127Two sessions cannot mount the same store on one filesystem at the same time because both need the same path. To run sessions that share a store side by side, give each session its own filesystem. If you use a sandbox for each session, each session gets its own filesystem automatically. See [Run one sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session). One host can run many such sandboxes.
127128 
128129## How the worker handles memory
129130 
from line 132
131132 
1321331. **Downloads each store to its `mount_path` (java, php: `mountPath`; csharp, go: `MountPath`).** This is the same directory under `/mnt/memory/` that cloud sessions use, and the session’s system prompt describes it to the agent. For example, a store named “User Preferences” lands at `/mnt/memory/user-preferences/`.
1331342. **Opens those directories to the file tools.** The agent works on memories with the same file tools it uses in the working directory.
1343. **Reconciles changes after tool calls,** at most once per sync interval (15 seconds by default). Memories that changed in the store are written to disk, and files the agent changed are uploaded to the store.
1354. **Runs a final sync when the session ends.** It flushes any uploads still pending for up to 30 seconds, then removes the directories it created.
1353. **Syncs after tool calls.** The worker syncs after a tool call if the [sync interval](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#sync-interval) (15 seconds by default) has passed since its last sync. Each sync writes changed memories from the store to disk and uploads files that the agent changed.
1364. **Runs a final sync when the session ends or stays idle for the worker’s idle limit.** The final sync can take up to 60 seconds. Changes not uploaded by then are lost. The worker then removes the directories it created.
136137 
137The memory store on Anthropic’s side remains the source of truth. [Memory versions](https://platform.claude.com/docs/en/managed-agents/memory#audit-memory-changes), redaction, and viewing or editing memories in the Claude Console work as they do for cloud sessions. The agent’s memory reads and writes appear in the [event stream](https://platform.claude.com/docs/en/managed-agents/events-and-streaming) as ordinary tool events.
138The idle limit is 60 seconds by default. [When the worker finishes with a session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#when-the-worker-finishes-with-a-session) says what the limit covers and how to change it.
138139 
139Because each worker syncs on an interval, a change written in one session becomes visible to another running session only after both have synced. That is typically well under a minute at the default interval. Sessions on cloud sandboxes see each other’s changes almost immediately.
140The agent’s `write` and `edit` tools change only the local copy, and the worker uploads those changes at its next sync. Paths under `/mnt/memory/` outside the store directories are not scratch space. The worker’s file tools refuse to write to them, and anything that a shell command writes there is never synced to a store.
140141 
141Each store directory contains a marker file named `.anthropic-memory-store` that ties the directory to its store. Leave it in place: the worker does not sync a directory whose marker is missing or altered.
142[Memory versions](https://platform.claude.com/docs/en/managed-agents/memory#audit-memory-changes), redaction, and viewing or editing memories in the Claude Console work as they do for cloud sessions. The agent’s memory reads and writes appear in the [event stream](https://platform.claude.com/docs/en/managed-agents/events-and-streaming) as ordinary tool events.
142143 
144Each store directory contains a marker file named `.anthropic-memory-store` that ties the directory to its store. Leave it in place. If the marker is missing or altered and the directory still holds files, the worker doesn’t sync the directory. It also doesn’t remove the directory when it finishes with the session.
145 
143146<Warning>
144 A worker that is killed rather than stopped runs no teardown, so unsynced edits are lost and the store directories stay behind. See [Stop workers gracefully](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#stop-workers-gracefully).
147 If you stop a worker gracefully during a session or [stop the session’s work item](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#stop-a-session-gracefully), the worker still uploads new and changed files. It also removes the store directories. It sends no deletions, so a memory that the agent deleted stays in the store unless an earlier sync already deleted it from the store. A worker that is killed rather than stopped runs no teardown, so unsynced edits are lost and the store directories stay behind. See [Stop workers gracefully](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#stop-workers-gracefully).
145148</Warning>
146149 
147150## Configure sync
from line 153
150153 
151154### Sync interval
152155 
153`memory_sync_interval` (typescript: `memorySyncIntervalMs`; go: `MemorySyncInterval`) sets how often attached stores reconcile with the server while the session runs.
156`memory_sync_interval` (typescript: `memorySyncIntervalMs`; go: `MemorySyncInterval`) sets the shortest time between two syncs while the session runs.
154157 
155158| Setting | Value |
156159| ---------------------- | --------------------------------------------------- |
from line 162
159162| Example (10 seconds) | `10` (typescript: `10_000`; go: `10 * time.Second`) |
160163| Disable memory support | `None` (typescript: `null`; go: `-1`) |
161164 
165The worker doesn’t sync on a timer. It checks the interval after each call to a tool that runs in your sandbox, such as `bash`, `read`, or a custom tool. The call doesn’t have to touch memory. Without tool calls, nothing syncs until the [final sync](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#how-the-worker-handles-memory). A change in one session reaches another running session only after both have synced, so the wait has no fixed length.
166 
162167A shorter interval narrows the window in which another session sees stale memories, at the cost of more memory store requests.
163168 
164169Disable memory support only on workers whose sessions attach no memory stores. A disabled worker neither downloads nor syncs stores, so a session with stores attached runs without them even though its system prompt still describes them.
165170 
166While memory support is enabled, a work item that arrives without a `secret` (csharp, go: `Secret`) for a session with attached stores fails rather than running without memory. See [Memory stores fail to mount](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#memory-stores-fail-to-mount).
171While memory support is enabled, a work item that arrives without a `secret` (csharp, go: `Secret`) for a session with attached stores fails rather than running without memory. See [Memory stores fail to mount or sync](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#memory-stores-fail-to-mount).
167172 
168173### Deletions
169174 
from line 180
175180| `"log_only"` (go: `environments.MemorySyncDeletionsLogOnly`) | Runs the same checks but only logs what it would have deleted. Use it to watch what your workers would delete before you trust the enabled mode. |
176181| `"disabled"` (go: `environments.MemorySyncDeletionsDisabled`) | Never deletes from the store. |
177182 
178For example, to sync every 10 seconds and only log the deletes the worker would have made:
183For example, to sync at most once every 10 seconds and only log the deletions the worker would have made, use the following sample. The sample uses `/workspace` as the working directory, which must exist before the worker starts. [Run an always-on worker](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-an-always-on-worker) says how to create the directory and what to use on macOS.
179184 
180185<CodeGroup exclude="shell, csharp, java, php, ruby">
186 <CodeGroupItem language="cURL">
187 A worker is a long-running process, not a single HTTP request. To change the sync settings, use `EnvironmentWorker` in the Python, TypeScript, or Go SDK.
188 </CodeGroupItem>
189 
190 <CodeGroupItem language="CLI">
191 The `ant` CLI worker always uses the default sync settings. To change them, use `EnvironmentWorker` in the Python, TypeScript, or Go SDK.
192 </CodeGroupItem>
193 
181194 ```python Python
182 worker = EnvironmentWorker(
183 client,
184 environment_id=environment_id,
185 environment_key=environment_key,
186 workdir="/workspace",
187 memory_sync_interval=10, # seconds
188 memory_sync_deletions="log_only",
189 )
195 import asyncio
196 import contextlib
197 import os
198 import signal
199 from anthropic import AsyncAnthropic
200 from anthropic.lib.environments import EnvironmentWorker
201 
202 
203 async def main() -> None:
204 environment_key = os.environ["ANTHROPIC_ENVIRONMENT_KEY"]
205 environment_id = os.environ["ANTHROPIC_ENVIRONMENT_ID"]
206 async with AsyncAnthropic(auth_token=environment_key) as client:
207 worker = EnvironmentWorker(
208 client,
209 environment_id=environment_id,
210 environment_key=environment_key,
211 workdir="/workspace",
212 memory_sync_interval=10, # seconds
213 memory_sync_deletions="log_only",
214 )
215 task = asyncio.create_task(worker.run())
216 loop = asyncio.get_running_loop()
217 for signum in (signal.SIGINT, signal.SIGTERM):
218 loop.add_signal_handler(signum, task.cancel)
219 with contextlib.suppress(asyncio.CancelledError):
220 await task
221 
222 
223 asyncio.run(main())
190224 ```
191225 
192226 ```typescript TypeScript
227 import Anthropic from "@anthropic-ai/sdk";
228 import { EnvironmentWorker } from "@anthropic-ai/sdk/helpers/beta/environments";
229 
230 const environmentKey = process.env.ANTHROPIC_ENVIRONMENT_KEY!;
231 const environmentId = process.env.ANTHROPIC_ENVIRONMENT_ID!;
232 const client = new Anthropic({ authToken: environmentKey });
233 const controller = new AbortController();
234 process.once("SIGINT", () => controller.abort());
235 process.once("SIGTERM", () => controller.abort());
236 
193237 const worker = new EnvironmentWorker({
194238 client,
195239 environmentId,
196240 environmentKey,
197241 workdir: "/workspace",
242 signal: controller.signal,
198243 memorySyncIntervalMs: 10_000,
199244 memorySyncDeletions: "log_only"
200245 });
246 await worker.run();
201247 ```
202248 
203249 <CodeGroupItem language="C#">
from line 251
205251 </CodeGroupItem>
206252 
207253 ```go Go
208 worker := environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{
209 EnvironmentID: environmentID,
210 EnvironmentKey: environmentKey,
211 Workdir: "/workspace",
212 MemorySyncInterval: 10 * time.Second,
213 MemorySyncDeletions: environments.MemorySyncDeletionsLogOnly,
214 })
254 package main
255 
256 import (
257 "context"
258 "log"
259 "os"
260 "os/signal"
261 "syscall"
262 "time"
263 
264 "github.com/anthropics/anthropic-sdk-go/v2"
265 "github.com/anthropics/anthropic-sdk-go/v2/lib/environments"
266 "github.com/anthropics/anthropic-sdk-go/v2/option"
267 )
268 
269 func main() {
270 environmentKey := os.Getenv("ANTHROPIC_ENVIRONMENT_KEY")
271 environmentID := os.Getenv("ANTHROPIC_ENVIRONMENT_ID")
272 
273 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
274 defer stop()
275 
276 client := anthropic.NewClient(option.WithAuthToken(environmentKey))
277 
278 worker := environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{
279 EnvironmentID: environmentID,
280 EnvironmentKey: environmentKey,
281 Workdir: "/workspace",
282 MemorySyncInterval: 10 * time.Second,
283 MemorySyncDeletions: environments.MemorySyncDeletionsLogOnly,
284 })
285 if err := worker.Run(ctx); err != nil {
286 log.Fatalf("worker: %v", err)
287 }
288 }
215289 ```
216290 
217291 <CodeGroupItem language="Java">
from line 303
229303 
230304## Read-only stores and conflicts
231305 
306### Read-only stores
307 
232308For a store attached with `access: "read_only"`, the `write` and `edit` tools refuse to change files inside its directory. The worker never uploads anything from it.
233309 
234Changes made through `bash`, or through a custom tool or MCP server you serve from the sandbox, are not blocked locally. They are never synced to the store, and the next remote change to that memory overwrites them. If the local copy itself must stay unchanged during the session:
310Changes made through `bash` or through a custom tool or MCP server you serve from the sandbox are not blocked locally. They never reach the store. A changed file stays changed until one of these things happens:
235311 
236* Disable the `bash` tool for that agent, and give it no custom tool that writes to the sandbox’s filesystem.
237* Do not mount the store path read-only. The worker itself must create the directory and write the downloaded memories into it.
312* **That memory gets a new version in the store.** The worker’s next sync overwrites the file with that version.
313* **The worker finishes with the session.** It removes the directory.
238314 
239Conflicts resolve in favor of the store. Suppose the agent changes a memory file that also changed in the store since the session last synced it. At the next sync, the worker keeps the store’s version, overwrites the local file with it, and logs a warning. The `write` and `edit` tools themselves succeed and no error reaches the agent. If the agent’s change still applies, it can re-read the file after the sync and make the change again.
315To keep the local copy unchanged too, disable the `bash` tool for that agent. Also, give it no custom tools or MCP servers that write to the sandbox’s filesystem. Don’t mount a read-only volume at the store’s path. The mount puts a directory at that path, and the worker fails the work item if anything already exists there.
240316 
317### Conflicts
318 
319A conflict is a memory that changed both in the store and in the sandbox since the previous sync. A deletion counts as a change. For a store attached with `access: "read_write"`, the worker resolves the conflict at the next sync:
320 
321| In the store | In the sandbox | Result |
322| ------------ | -------------- | ---------------------------------------------------------- |
323| Changed | Changed | The store’s version overwrites the file. |
324| Changed | Deleted | The worker writes the store’s version back to the sandbox. |
325| Deleted | Changed | The worker creates the memory again from the file. |
326 
327In the first two rows, the agent’s change or deletion is lost, even though the tool call succeeded. Nothing tells the agent, and the only sign of the loss is a warning in the worker’s log. In the last row, the deletion in the store is undone.
328 
241329## Troubleshooting
242330 
243See [Memory stores fail to mount](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#memory-stores-fail-to-mount) for the worker’s log messages and their fixes.
331See [Memory stores fail to mount or sync](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#memory-stores-fail-to-mount) for the worker’s log messages and their fixes.
244332 

managed-agents/self-hosted-sandboxes-operations Changed · +16 / -14 lines

### Memory stores fail to mount or sync ### Memory stores fail to mount

from line 326
326326 
327327## Stop workers gracefully
328328 
329A worker that is canceled while a session runs shuts that session down before it exits, as it does when you [stop a session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#stop-a-session-gracefully). If the session has [memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory) attached, the worker skips the final sync but still uploads changed files and removes the store directories.
329A worker that is canceled while a session runs shuts that session down before it exits, as it does when you [stop a session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#stop-a-session-gracefully). If the session has [memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory) attached, the worker still uploads new and changed files and removes the store directories. It sends no deletions, so a memory that the agent deleted stays in the store unless an earlier sync already deleted it from the store.
330330 
331331A killed process runs no teardown. To stop a worker cleanly:
332332 
from line 338
338338 | SDK worker that is its own process | `EnvironmentWorker` installs no signal handlers. Cancel the worker from a signal handler, as the standalone worker examples do. |
339339 | SDK worker inside a webhook server | Cancel the worker from the server’s own shutdown hook, as the webhook examples do. The worker must not take over the server’s signals. |
340340 
3412. **Stop the worker with SIGTERM, and allow at least 30 seconds (3 minutes for a Python SDK worker) before any hard kill.** Uploading changed files to a memory store can take up to 30 seconds, and a Python SDK worker first lets an in-flight tool call complete. Docker sends SIGKILL 10 seconds after the stop signal by default. Raise that limit with `--stop-timeout` on `docker run`, or with your orchestrator’s termination grace period.
3412. **Stop the worker with SIGTERM, and give it time to finish before any hard kill.** The worker needs time to end an in-flight tool call and to upload changed files to a memory store. Docker sends SIGKILL 10 seconds after the stop signal by default. Raise that limit with `--stop-timeout 60` (python: `--stop-timeout 210`) on `docker run`, or set your orchestrator’s termination grace period to the same number of seconds.
342342 
343343If a worker is killed before its teardown runs, any memory edits that had not synced are lost. On a long-lived host, also remove the leftover store directory under `/mnt/memory/` before the next session that attaches that store. A sandbox that serves one session and is then discarded needs no cleanup.
344344 
from line 352
352352 
353353No worker is claiming work. A queued session waits rather than failing. Check `workers_polling` (java, php: `workersPolling`; csharp, go: `WorkersPolling`) and `depth` (csharp, go: `Depth`) in [Read queue depth](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#read-queue-depth).
354354 
355### Memory stores fail to mount
355### Memory stores fail to mount or sync
356356 
357The worker logs mount and background sync failures rather than reporting them to the session. Only read-only refusals reach the agent, as tool errors (see [Read-only stores and conflicts](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#read-only-stores-and-conflicts)).
357Where a memory store failure shows up depends on its kind:
358358 
359If the worker cannot mount a memory store when it claims a session, it fails the work item. The session emits no error event and stays idle.
359* **A mount failure:** If the worker cannot mount a memory store when it claims a session, it writes the failure to its log and fails the work item. The session emits no error event and stays idle.
360* **A sync failure:** The worker writes the failure to its log and doesn’t report it to the session.
361* **A refused write to a read-only store:** The agent gets a tool error. See [Read-only stores and conflicts](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#read-only-stores-and-conflicts).
360362 
361| Symptom | Cause | Fix |
362| --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
363| The worker log contains `the work item carried no sessions token` (in Go, the `ErrSessionMemoryNoToken` error) and the work item fails. | The work item’s per-session `secret` (csharp, go: `Secret`) did not reach the worker. Either your code did not forward it, or memory stores on self-hosted sandboxes are not enabled for your organization. | [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#forward-the-work-items-secret). If the worker polls and runs sessions in one process and still logs this, contact support. |
364| The worker log contains `something already exists at the memory store's path`. | A directory left over from a previous session, usually one whose worker was killed before its teardown ran. | Remove the leftover directory that the log line names. Edits in it that had not synced are lost. |
365| The worker log contains `cannot create the memory store's folder` and `the worker host must make this mount path writable`. | The user the worker runs as cannot create directories under `/mnt/memory`. | Create `/mnt/memory` and `chown` it to that user. See [Prepare the host](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#prepare-the-host). On macOS, follow [Prepare a macOS host](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#prepare-a-macos-host) instead. |
366| The session sits `idle` with a `requires_action` stop reason and no error event shortly after a worker claimed it. | The worker failed the work item because it could not mount a memory store, for one of the preceding reasons. | Fix the cause on the host, then send a [`user.interrupt`](https://platform.claude.com/docs/en/managed-agents/events-and-streaming#interrupt-the-agent) event. The session’s work is queued again, and the next worker that claims it retries the mount. |
363| Symptom | Cause | Fix |
364| --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
365| The worker log contains `the work item carried no sessions token` (in Go, the `ErrSessionMemoryNoToken` error) and the work item fails. | The work item’s per-session `secret` (csharp, go: `Secret`) did not reach the worker. Either your code did not forward it, or memory stores on self-hosted sandboxes are not enabled for your organization. | [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#forward-the-work-items-secret). If the worker polls and runs sessions in one process and still logs this, contact support. |
366| The worker log contains `something already exists at the memory store's path`. | Another session on the same filesystem is using that path. Or a previous session’s worker was killed before its teardown ran, so the directory stayed behind. | Check whether a worker still runs a session that uses that path. If one does, do not remove the directory: the worker removes it when it finishes with the session. If none does, remove the directory that the log line names. Edits in it that had not synced are lost. To run two such sessions at once, see [Isolate sessions that share a store](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#isolate-sessions-that-share-a-store). |
367| The worker log contains `cannot create the memory store's folder` and `the worker host must make this mount path writable`. | The user the worker runs as cannot create directories under `/mnt/memory`. | Create `/mnt/memory` and `chown` it to that user. See [Prepare the host](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#prepare-the-host). On macOS, follow [Prepare a macOS host](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#prepare-a-macos-host) instead. |
368| The session sits `idle` with a `requires_action` stop reason and no error event shortly after a worker claimed it. | The worker failed the work item because it could not mount a memory store, for one of the preceding reasons. | Fix the cause on the host, then send a [`user.interrupt`](https://platform.claude.com/docs/en/managed-agents/events-and-streaming#interrupt-the-agent) event. The session’s work is queued again, and the next worker that claims it retries the mount. |
367369 
368370### A custom tool call never returns
369371 

managed-agents/self-hosted-sandboxes-per-session New page · 598 lines, new page

## Run sandboxes on Kubernetes ### Install the chart ### Add tools to the sandbox image ### Restrict network egress ## Launch sandboxes with a spawn script ## Forward the work item’s secret ## Launch sandboxes from the SDK poller ## Run the SDK worker inside the sandbox ## Stage files for a session ## Next steps

A whole new page. There's nothing to diff it against, so here is what it says.

---
title: Run one sandbox per session
url: https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session
description: Give each session its own self-hosted sandbox with the Helm chart on Kubernetes, a spawn script, or the SDK poller.
featureMetadata:
  topic:
    title: Managed Agents
    url: https://platform.claude.com/docs/en/managed-agents/overview
  status: beta
  betaHeader: managed-agents-2026-04-01
  zdr:
    eligibility: not-eligible
    note: Not eligible for ZDR, except for self-hosted Managed Agents. Sessions are stateful resources; transcripts persist until you delete them.
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: beta
    Claude Platform on AWS: beta
---

In the sandbox-per-session pattern, each session runs in a fresh sandbox, which can have its own filesystem, resource limits, and network controls. To compare it with the other patterns, see [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern).

You can set it up in three ways:

* **[Helm chart on Kubernetes](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#run-sandboxes-on-kubernetes):** Anthropic’s dispatcher claims work and starts a pod for each session on your cluster.
* **[Spawn script](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#launch-sandboxes-with-a-spawn-script):** The `ant` CLI claims work and calls your script, which launches a sandbox on any platform.
* **[SDK poller](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#launch-sandboxes-from-the-sdk-poller):** Your own code claims work and launches the sandbox.

The sections after [Run sandboxes on Kubernetes](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#run-sandboxes-on-kubernetes) apply to the spawn script and the SDK poller.

## Run sandboxes on Kubernetes

Anthropic publishes a Helm chart, `cma-sandboxes`, and its images. The chart runs one sandbox per session on your own Kubernetes cluster. Its dispatcher polls the environment’s work queue and gives each session a pod of its own:

* **Isolation:** Each pod runs under [gVisor](https://gvisor.dev/) behind the chart’s network policies. It has its own filesystem and resource limits. Only the dispatcher holds the environment key.
* **Session affinity:** Every message in a session goes to that session’s sandbox. After the session is idle for 30 minutes (the default of the chart’s `sandbox.idleTimeout` setting), its pod stops. Its `/workspace` volume stays until the session ends. The next message starts a pod on the same volume.
* **Warm pool:** Except on Google Kubernetes Engine (GKE), the chart keeps two pods ready for new sessions (the default of the chart’s `sandbox.warmPoolSize` setting).

Sandbox pods run the `ant` CLI worker. They support [memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory) with the default sync settings, and they don’t support [custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools).

### Install the chart

The chart runs on GKE, Amazon EKS, and other clusters. Set up the following before you install it:

* **In the cluster:** The [Agent Sandbox](https://github.com/kubernetes-sigs/agent-sandbox) controller (on GKE, the Agent Sandbox add-on), nodes that run gVisor, and a network plugin that enforces NetworkPolicy.
* **In your own namespace:** Restricted Pod Security Standard labels, a Secret with the environment ID and [environment key](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#run-your-first-session), and the dispatcher’s TLS certificate.

The [install guide on GitHub](https://github.com/anthropics/anthropic-cli/blob/main/sandboxes/kubernetes/README.md) has the setup steps for each kind of cluster. It also covers upgrades and key rotation.

Save your settings as `cma-values.yaml`. The install fails without the three settings in this file:

<File filename="cma-values.yaml">
  ```yaml
  platform: gke             # or eks, or generic for any other cluster
  egress:
    # The chart already blocks the private ranges. List your other addresses
    # that sandboxes must not reach.
    clusterCIDRs:
      - 203.0.113.10/32     # your cluster's Kubernetes API endpoint
    cmaServer:
      public: true          # the Claude API has a public address
  ```
</File>

The install guide lists the settings that depend on your cluster, such as `gke.dns` on GKE Autopilot. It also says when `egress.clusterIsPrivate: true` takes the place of `egress.clusterCIDRs`.

Then, install the chart:

```bash
helm install cma \
  oci://us-docker.pkg.dev/anthropic-public-registry/sandboxes/charts/cma-sandboxes \
  --version 0.1.0 \
  --namespace cma \
  -f cma-values.yaml \
  --wait
```

After the install, run the preflight check that the install guide describes.

<Warning>
  Don’t remove the chart with `helm uninstall` alone. That command deletes the network policies and leaves the sessions’ sandboxes running without them. Stop the dispatcher and delete the sandboxes first, in the order that the [Removal section of the install guide](https://github.com/anthropics/anthropic-cli/blob/main/sandboxes/kubernetes/README.md#removal) gives.
</Warning>

### Add tools to the sandbox image

The published sandbox image is Alpine Linux with `bash`, `curl`, `jq`, and the `ant` CLI. The chart runs it with a read-only root filesystem and as a non-root user, so an agent can’t install packages during a session.

To give your agents more tools, such as Python or Git, build both images from the repository at the release’s tag. The [Install section of the install guide](https://github.com/anthropics/anthropic-cli/blob/main/sandboxes/kubernetes/README.md#install) has the commands. Push the images to your registry as `cma-dispatcher` and `cma-sandbox`, with the chart’s version as the tag. Then, set `image.registry` to that registry. If you pin image digests, use the digests of your own images.

### Restrict network egress

By default, the chart’s network policies let a sandbox reach the public IPv4 internet. They block private address ranges, the cloud metadata server, and the addresses in `egress.clusterCIDRs`. A prompt-injected agent can send what it reads to any address that its sandbox can reach. [Network egress](https://github.com/anthropics/anthropic-cli/blob/main/sandboxes/kubernetes/README.md#network-egress) in the install guide has the details.

* **GKE with Dataplane V2:** Set `egress.mode: fqdnGke` to limit connections to port 443 on the hosts in `egress.fqdnGke.hosts`. Keep `api.anthropic.com` in that list, and add every host that your agents’ commands need. Unlike the default, this mode has no list of blocked ranges. It allows whatever address a listed host’s name resolves to, so list only hosts whose DNS you trust. A sandbox can still send data out inside DNS lookups.
* **Other clusters and GKE without Dataplane V2:** The default is the only mode.
* **Every cluster:** Network policies don’t cover the ports that the cluster’s own nodes listen on. See [Node isolation you own](https://github.com/anthropics/anthropic-cli/blob/main/sandboxes/kubernetes/README.md#node-isolation-you-own) in the install guide.

## Launch sandboxes with a spawn script

A poller on the host claims work and calls your script once for each work item. The script launches a sandbox for that one session.

<Steps>
  <Step title="Build the sandbox image">
    Install `ant` and set `ant beta:worker run` as the entrypoint. When a sandbox starts, it reads session details from environment variables, handles that session, and exits. The base image must provide `/bin/bash`; the build uses `curl` only to download `ant`.

    <File filename="Dockerfile">
      ```dockerfile
      FROM your-base-image
      ARG ANT_VERSION=2.11.0
      ARG TARGETARCH
      RUN ARCH=$([ "$TARGETARCH" = "arm64" ] && echo arm64 || echo amd64) && \
          curl -fsSL "https://github.com/anthropics/anthropic-cli/releases/download/v${ANT_VERSION}/ant_${ANT_VERSION}_linux_${ARCH}.tar.gz" \
            | tar -xz -C /usr/local/bin ant
      WORKDIR /workspace
      VOLUME /workspace
      ENTRYPOINT ["ant", "beta:worker", "run"]
      ```
    </File>
  </Step>

  <Step title="Write the spawn script">
    The script forwards the session details into a fresh sandbox. It requires `jq` on the poller host.

    <File filename="spawn.sh">
      ```bash
      #!/bin/bash
      # spawn.sh: called once for each claimed work item
      # The claimed work item arrives as JSON on stdin.
      ANTHROPIC_WORK_SECRET="$(jq -r '.secret // empty')"
      export ANTHROPIC_WORK_SECRET
      mkdir -p "/host/outputs/$ANTHROPIC_SESSION_ID"
      exec docker run --rm \
        -e ANTHROPIC_SESSION_ID -e ANTHROPIC_ENVIRONMENT_KEY \
        -e ANTHROPIC_WORK_ID -e ANTHROPIC_ENVIRONMENT_ID -e ANTHROPIC_BASE_URL \
        -e ANTHROPIC_WORK_SECRET \
        -v "/host/outputs/$ANTHROPIC_SESSION_ID":/workspace \
        your-image
      ```
    </File>

    The poller sets `ANTHROPIC_WORK_ID`, `ANTHROPIC_ENVIRONMENT_ID`, `ANTHROPIC_SESSION_ID`, and `ANTHROPIC_ENVIRONMENT_KEY`. `ANTHROPIC_BASE_URL` reaches the script only if you set it on the poller’s host. The script reads `ANTHROPIC_WORK_SECRET` from the work item’s JSON on standard input. See [Environment variables](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-variables).

    `/host/outputs` is a host directory you choose. Mounting it at `/workspace` lets you retrieve the session’s deliverables after the sandbox exits. The mount also picks up the downloaded `skills/` tree and any intermediate files.
  </Step>

  <Step title="Start the poller">
    ```bash
    ant beta:worker poll --on-work ./spawn.sh
    ```
  </Step>
</Steps>

## Forward the work item’s secret

Each claimed work item can carry a `secret` (csharp, go: `Secret`) that Anthropic issues for that session. The worker that runs the session needs it to mount [memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory).

A worker that claims and runs sessions in one process passes the secret along itself. `EnvironmentWorker` with `run()` (go: `Run()`) is one such worker, and `ant beta:worker poll` without `--on-work` is another. When your own code sits between the claim and the worker, you forward the secret:

| You claim work with                                                                                                      | The secret arrives as                                                    | Pass it to the worker as                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ant beta:worker poll --on-work`                                                                                         | The `secret` field of the work item JSON on your script’s standard input | `ANTHROPIC_WORK_SECRET` in the sandbox’s environment                                                                                                                                                |
| The Python, TypeScript, or Go SDK’s `work.poller()` (typescript: `new WorkPoller()`; go: `environments.NewWorkPoller()`) | The `secret` (go: `Secret`) field of each claimed work item              | `ANTHROPIC_WORK_SECRET` in the sandbox’s environment or the `work_secret` (typescript: `workSecret`; go: `WorkSecret`) argument to `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) |

Pass the secret only into the sandbox that serves that session, and never log it. See [Security model](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-security) for how it relates to the environment key.

## Launch sandboxes from the SDK poller

To claim work from your own code instead of `ant beta:worker poll --on-work`, use the poller in the Python, TypeScript, or Go SDK: `work.poller()` (typescript: `new WorkPoller()`; go: `environments.NewWorkPoller()`). It polls the queue and gives you each claimed session, and you launch the sandbox:

<CodeGroup exclude="shell, csharp, java, php, ruby">
  <CodeGroupItem language="cURL">
    Claiming work in a loop and launching a sandbox for each session needs more logic than a single shell command. From the shell, run `ant beta:worker poll --on-work` with a spawn script, as in [Launch sandboxes with a spawn script](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#launch-sandboxes-with-a-spawn-script).
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    To claim work from the shell and launch a sandbox for each session, run `ant beta:worker poll --on-work` with a spawn script. See [Launch sandboxes with a spawn script](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#launch-sandboxes-with-a-spawn-script).
  </CodeGroupItem>

  ```python Python
  import asyncio
  import os

  from anthropic import AsyncAnthropic
  from anthropic.types.beta.environments import BetaSelfHostedWork

  SANDBOX_ENV = (
      "ANTHROPIC_ENVIRONMENT_ID",
      "ANTHROPIC_ENVIRONMENT_KEY",
      "ANTHROPIC_WORK_ID",
      "ANTHROPIC_SESSION_ID",
      "ANTHROPIC_WORK_SECRET",
      "ANTHROPIC_BASE_URL",  # forwarded only when set on this host
  )


  async def launch_container(work: BetaSelfHostedWork) -> None:
      print(f"claimed session {work.data.id}")
      # Replace `docker run` with your own sandbox launcher. Forward the environment
      # key (never your API key) and the work item's per-session secret: the worker
      # inside needs the secret to mount the session's memory stores.
      env = os.environ | {
          "ANTHROPIC_WORK_ID": work.id,
          "ANTHROPIC_SESSION_ID": work.data.id,
          "ANTHROPIC_WORK_SECRET": work.secret or "",
      }
      forward = [arg for name in SANDBOX_ENV for arg in ("-e", name)]
      launcher = await asyncio.create_subprocess_exec(
          "docker", "run", "--rm", "--detach", *forward, "your-image", env=env
      )
      await launcher.wait()


  async def main() -> None:
      environment_key = os.environ["ANTHROPIC_ENVIRONMENT_KEY"]
      environment_id = os.environ["ANTHROPIC_ENVIRONMENT_ID"]
      async with AsyncAnthropic(auth_token=environment_key) as client:
          async for work in client.beta.environments.work.poller(
              environment_id=environment_id,
              environment_key=environment_key,
              auto_stop=False,  # the launched sandbox owns the stop call
          ):
              await launch_container(work)


  asyncio.run(main())
  ```

  ```typescript TypeScript
  import { spawn } from "node:child_process";
  import { once } from "node:events";
  import Anthropic from "@anthropic-ai/sdk";
  import { WorkPoller } from "@anthropic-ai/sdk/helpers/beta/environments";
  import type { BetaSelfHostedWork } from "@anthropic-ai/sdk/resources/beta/environments";

  const SANDBOX_ENV = [
    "ANTHROPIC_ENVIRONMENT_ID",
    "ANTHROPIC_ENVIRONMENT_KEY",
    "ANTHROPIC_WORK_ID",
    "ANTHROPIC_SESSION_ID",
    "ANTHROPIC_WORK_SECRET",
    "ANTHROPIC_BASE_URL" // forwarded only when set on this host
  ];

  const environmentKey = process.env.ANTHROPIC_ENVIRONMENT_KEY!;
  const environmentId = process.env.ANTHROPIC_ENVIRONMENT_ID!;
  const client = new Anthropic({ authToken: environmentKey });

  async function launchContainer(work: BetaSelfHostedWork): Promise<void> {
    console.log(`claimed session ${work.data.id}`);
    // Replace `docker run` with your own sandbox launcher. Forward the environment
    // key (never your API key) and the work item's per-session secret: the worker
    // inside needs the secret to mount the session's memory stores.
    const env = {
      ...process.env,
      ANTHROPIC_WORK_ID: work.id,
      ANTHROPIC_SESSION_ID: work.data.id,
      ANTHROPIC_WORK_SECRET: work.secret ?? ""
    };
    const forward = SANDBOX_ENV.flatMap((name) => ["-e", name]);
    const launcher = spawn("docker", ["run", "--rm", "--detach", ...forward, "your-image"], {
      env,
      stdio: "inherit"
    });
    await once(launcher, "close");
  }

  const poller = new WorkPoller({
    client,
    environmentId,
    environmentKey,
    autoStop: false // the launched sandbox owns the stop call
  });

  for await (const work of poller) {
    await launchContainer(work);
  }
  ```

  <CodeGroupItem language="C#">
    The C# SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work) to poll for an item and acknowledge it.
  </CodeGroupItem>

Cut at 300 lines. The page has the rest.

managed-agents/self-hosted-sandboxes-reference Changed · +199 / -49 lines

### When the worker finishes with a session ### Final deliverables

from line 50
5050| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
5151| `--environment-id` | The environment to poll for work. Also reads from `ANTHROPIC_ENVIRONMENT_ID`. |
5252| `--environment-key` | Authenticates the worker with this environment. Also reads from `ANTHROPIC_ENVIRONMENT_KEY`. |
53| `--workdir` | Directory where the worker downloads skills, and where tools read and write files. Defaults to `.` (the current directory). |
53| `--workdir` | Directory where the worker downloads skills and where tools read and write files. Defaults to `.` (the current directory). The directory must exist before the worker starts. |
5454| `--on-work` | Script to call for each claimed work item instead of running tools in process. Receives session details as environment variables and the work item as JSON on standard input. |
5555| `--max-idle` | How long the worker waits while a session is idle before `ant beta:worker run` exits or `ant beta:worker poll` moves on to the next work item. Idle time with a [`requires_action` stop reason](https://platform.claude.com/docs/en/managed-agents/events-and-streaming#respond-when-the-session-goes-idle) does not count. Defaults to `60s`. Set it to `0` to turn off the timeout. With an `--on-work` script, `ant beta:worker poll` ignores this flag. Pass it instead to the `ant beta:worker run` command that your script starts. |
5656| `--log-format` | Log output format. Use `json` for structured log ingestion. Defaults to `text`. |
from line 57
5757 
5858## Environment variables
5959 
60| Variable | Description | Set by |
61| ------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
62| `ANTHROPIC_ENVIRONMENT_ID` | The environment whose queue the worker serves. | You, on the worker host. The poller passes it to the `--on-work` script. |
63| `ANTHROPIC_ENVIRONMENT_KEY` | Authenticates the worker to its queue. | You, on the worker host. The poller passes it to the `--on-work` script. |
64| `ANTHROPIC_SESSION_ID` | The session that a claimed work item represents. | The poller, for the `--on-work` script. |
65| `ANTHROPIC_WORK_ID` | The claimed work item. | The poller, for the `--on-work` script. |
66| `ANTHROPIC_WORK_SECRET` | The work item’s secret for its session. | You. The poller does not set it. See [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#forward-the-work-items-secret). |
67| `ANTHROPIC_BASE_URL` | Overrides the default API endpoint. Optional. | You, on the worker host. |
68| `ANTHROPIC_WEBHOOK_SIGNING_KEY` | Verifies incoming webhook payloads. | You, on a webhook handler host. |
60| Variable | Description | Set by |
61| ------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
62| `ANTHROPIC_ENVIRONMENT_ID` | The environment whose queue the worker serves. | You, on the worker host. The poller passes it to the `--on-work` script. |
63| `ANTHROPIC_ENVIRONMENT_KEY` | Authenticates the worker to its queue. | You, on the worker host. The poller passes it to the `--on-work` script. |
64| `ANTHROPIC_SESSION_ID` | The session that a claimed work item represents. | The poller, for the `--on-work` script. |
65| `ANTHROPIC_WORK_ID` | The claimed work item. | The poller, for the `--on-work` script. |
66| `ANTHROPIC_WORK_SECRET` | The work item’s secret for its session. | You. The poller does not set it. See [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#forward-the-work-items-secret). |
67| `ANTHROPIC_BASE_URL` | Overrides the default API endpoint. Optional. | You, on the worker host. |
68| `ANTHROPIC_WEBHOOK_SIGNING_KEY` | Verifies incoming webhook payloads. | You, on a webhook handler host. |
6969 
7070## Host requirements
7171 
from line 81
8181 
8282## Sandbox filesystem
8383 
84| Path | Contents |
85| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
86| `/workspace` | The system default working directory for running tools and downloading skills. If you use a different working directory, update your agent’s system prompt so Claude can locate the skill files. |
87| `<workdir>/skills/<name>/` | The agent’s downloaded skills. |
88| `/mnt/memory/<store>/` | One directory per attached memory store, at the store’s `mount_path` (java, php: `mountPath`; csharp, go: `MountPath`) (for example, `/mnt/memory/user-preferences/`). The worker creates these directories when it claims the session and removes them when the session ends. |
84| Path | Contents |
85| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
86| `/workspace` | The working directory in the samples on the self-hosted sandboxes pages. It is not the worker’s default: the worker uses the current directory unless you set `--workdir` or `workdir` (go: `Workdir`). Anthropic’s cloud sandboxes keep skills and repositories in `/workspace`. If you use a different working directory, update your agent’s system prompt so Claude can locate the skill files. |
87| `<workdir>/skills/<name>/` | The agent’s downloaded skills. |
88| `/mnt/memory/<store>/` | A local copy of each attached memory store, one directory per store. The API returns each directory’s full path in the `mount_path` (java, php: `mountPath`; csharp, go: `MountPath`) field of the session’s memory store resource (for example, `/mnt/memory/user-preferences/`). |
8989 
90On self-hosted environments the session’s system prompt omits the `/mnt/session/outputs` instruction used on Anthropic-managed sandboxes. Final deliverables land wherever the agent writes them in your sandbox filesystem, typically under the working directory.
90The worker creates the memory store directories when it claims a session. It removes them when it finishes with that session or when you [stop the worker gracefully](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#stop-workers-gracefully). That removes only the local copies, and the memories stay in the store.
9191 
92Skills can include executables that the agent may run directly. The CLI and SDK workers preserve the executable permissions recorded in the skill bundle when they extract it. If you implement skills download manually, you are responsible for setting executable permissions.
92Skills can include executables that the agent can run directly. The CLI and SDK workers preserve the executable permissions recorded in the skill bundle when they extract it. If you download skills yourself, set their executable permissions yourself.
9393 
94### When the worker finishes with a session
95 
96The worker finishes with a session in any of these cases:
97 
98* The session ends.
99* You [stop the session’s work item](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations#stop-a-session-gracefully).
100* The session stays idle for the worker’s idle limit. The session itself stays open. When you then send it a new event, such as a user message, the same worker or another one claims it. That worker downloads the stores again.
101 
102The idle limit is 60 seconds by default. To change it, use [`--max-idle`](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#cli-commands-and-flags) for the `ant` CLI worker or [`max_idle` (typescript: `maxIdleMs`; go: `MaxIdle`)](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-worker) for `EnvironmentWorker`. The [`cma-sandboxes` Helm chart](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#run-sandboxes-on-kubernetes) starts its workers with a limit of 30 minutes instead. To change that limit, change the chart’s `sandbox.idleTimeout` setting.
103 
104### Final deliverables
105 
106Self-hosted sandboxes have no `/mnt/session/outputs` directory. On Anthropic’s cloud sandboxes, the session’s system prompt tells the agent to copy final deliverables there. On self-hosted environments, the system prompt leaves that instruction out. Final deliverables stay wherever the agent writes them, typically under the working directory, and the worker doesn’t upload them.
107 
108To collect final deliverables in one place, give the full path of a directory in your agent’s system prompt. Choose a directory that the worker’s file tools can write to:
109 
110* **Inside the working directory:** For example, `/workspace/outputs` if the working directory is `/workspace`.
111* **Anywhere else, with an SDK worker only:** Add the directory to `allowed_roots` (typescript: `allowedRoots`; go: `AllowedRoots`). See [AgentToolContext and the agent toolset](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#agent-tool-context-and-the-agent-toolset).
112 
94113## SDK helpers
95114 
96115The Python, TypeScript, and Go SDKs provide three helpers at different levels of control:
from line 117
98117| Helper | What it does | Use it when |
99118| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
100119| [`EnvironmentWorker`](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-worker) | Handles polling, setup, and tool runs end to end. | Most cases. |
101| [`work.poller()` (go: `environments.NewWorkPoller()`)](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#work-poller) | Polls the work queue and gives you each claimed session. | You determine how to handle each session, for example by launching a sandbox rather than running tools in process. |
120| [`work.poller()` (typescript: `new WorkPoller()`; go: `environments.NewWorkPoller()`)](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#work-poller) | Polls the work queue and gives you each claimed session. | You determine how to handle each session, for example by launching a sandbox rather than running tools in process. |
102121| [`client.beta.sessions.events.tool_runner()` (typescript: `client.beta.sessions.events.toolRunner()`; go: `client.Beta.Sessions.Events.NewToolRunner()`)](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#session-tool-runner) | Runs tool calls for a single session, given the session ID and a tool list. | You’ve already claimed the work and only need to run the tools. |
103122 
104123### EnvironmentWorker
105124 
106| Method | Description |
107| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
108| `run()` (go: `Run()`) | Runs indefinitely, picking up sessions as they arrive. |
109| `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) | Handles a single claimed work item and returns. Pass the work, session, and environment identifiers and the `work_secret` (typescript: `workSecret`; go: `WorkSecret`) explicitly, or let it read the [`ANTHROPIC_*` variables](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-variables). |
125| Method | Description |
126| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
127| `run()` (go: `Run()`) | Runs indefinitely, picking up sessions as they arrive. |
128| `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) | Handles one work item already claimed by a poller. The poller can be `ant beta:worker poll --on-work` or your own code. The method returns when the worker finishes with the item’s session. You can pass `work_id` (typescript: `workId`; go: `WorkID`), `session_id` (typescript: `sessionId`; go: `SessionID`), `environment_id` (typescript: `environmentId`; go: `EnvironmentID`), and `work_secret` (typescript: `workSecret`; go: `WorkSecret`). For each one that you leave out, the method reads the matching [`ANTHROPIC_*` variable](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-variables). |
110129 
111| Option | Description |
112| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
113| `tools` (go: `ToolsFunc`) | A factory that receives the session’s `AgentToolContext` and returns the tool list. Defaults to the standard agent toolset. |
114| `memory_sync_interval` (typescript: `memorySyncIntervalMs`; go: `MemorySyncInterval`) | How often attached memory stores reconcile with the server while the session runs. See [Sync interval](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#sync-interval). |
115| `memory_sync_deletions` (typescript: `memorySyncDeletions`; go: `MemorySyncDeletions`) | Whether files the agent deletes locally are also deleted from the store. See [Deletions](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#deletions). |
130| Option | Description |
131| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
132| `tools` (go: `ToolsFunc`) | A factory that receives the session’s `AgentToolContext` and returns the tool list. Defaults to the standard agent toolset. |
133| `max_idle` (typescript: `maxIdleMs`; go: `MaxIdle`) | How long the worker waits while a session is idle before it finishes with the session. Idle time with a [`requires_action` stop reason](https://platform.claude.com/docs/en/managed-agents/events-and-streaming#respond-when-the-session-goes-idle) does not count. Defaults to 60 seconds. To wait 5 minutes, set it to `300` (typescript: `300_000`; go: `anthropic.Ptr(5 * time.Minute)`). To turn the limit off, set it to `None` (typescript: `0`; go: `new(time.Duration)`). |
134| `memory_sync_interval` (typescript: `memorySyncIntervalMs`; go: `MemorySyncInterval`) | The shortest time between two syncs of the attached memory stores while the session runs. The worker checks the interval after each call to a tool that runs in your sandbox, not on a timer. Defaults to 15 seconds. See [Sync interval](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#sync-interval). |
135| `memory_sync_deletions` (typescript: `memorySyncDeletions`; go: `MemorySyncDeletions`) | Whether files the agent deletes locally are also deleted from the store. See [Deletions](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#deletions). |
116136 
117137`EnvironmentWorker` manages the `AgentToolContext` and the toolset automatically. Pass a `tools` (go: `ToolsFunc`) factory to customize the tool list:
118138 
119139<CodeGroup exclude="shell, csharp, java, php, ruby">
140 <CodeGroupItem language="cURL">
141 A worker is a long-running process, not a single HTTP request. To customize the tool list, use `EnvironmentWorker` in the Python, TypeScript, or Go SDK.
142 </CodeGroupItem>
143 
144 <CodeGroupItem language="CLI">
145 The `ant` CLI worker always uses the standard agent toolset. To customize the tool list, use `EnvironmentWorker` in the Python, TypeScript, or Go SDK.
146 </CodeGroupItem>
147 
120148 ```python Python
121 EnvironmentWorker(client, ..., tools=lambda env: [beta_bash_tool(env), my_custom_tool])
149 import asyncio
150 import contextlib
151 import os
152 import signal
153 from anthropic import AsyncAnthropic, beta_async_tool
154 from anthropic.lib.environments import EnvironmentWorker
155 from anthropic.lib.tools.agent_toolset import beta_bash_tool
156 
157 
158 @beta_async_tool
159 async def get_order_status(order_id: str) -> str:
160 """Look up an order in the internal fulfillment system by order ID."""
161 return f"Order {order_id}: shipped"
162 
163 
164 async def main() -> None:
165 environment_key = os.environ["ANTHROPIC_ENVIRONMENT_KEY"]
166 environment_id = os.environ["ANTHROPIC_ENVIRONMENT_ID"]
167 async with AsyncAnthropic(auth_token=environment_key) as client:
168 worker = EnvironmentWorker(
169 client,
170 environment_id=environment_id,
171 environment_key=environment_key,
172 # List every tool that the agent can call. The worker answers no other tool.
173 tools=lambda env: [beta_bash_tool(env), get_order_status],
174 )
175 task = asyncio.create_task(worker.run())
176 loop = asyncio.get_running_loop()
177 for signum in (signal.SIGINT, signal.SIGTERM):
178 loop.add_signal_handler(signum, task.cancel)
179 with contextlib.suppress(asyncio.CancelledError):
180 await task
181 
182 
183 asyncio.run(main())
122184 ```
123185 
124186 ```typescript TypeScript
125 new EnvironmentWorker({
187 import Anthropic from "@anthropic-ai/sdk";
188 import { EnvironmentWorker } from "@anthropic-ai/sdk/helpers/beta/environments";
189 import { betaTool } from "@anthropic-ai/sdk/helpers/beta/json-schema";
190 import { betaBashTool } from "@anthropic-ai/sdk/tools/agent-toolset/node";
191 
192 const getOrderStatus = betaTool({
193 name: "get_order_status",
194 description: "Look up an order in the internal fulfillment system by order ID.",
195 inputSchema: {
196 type: "object",
197 properties: { order_id: { type: "string", description: "The order ID" } },
198 required: ["order_id"]
199 },
200 run: async ({ order_id }) => `Order ${order_id}: shipped`
201 });
202 
203 const environmentKey = process.env.ANTHROPIC_ENVIRONMENT_KEY!;
204 const environmentId = process.env.ANTHROPIC_ENVIRONMENT_ID!;
205 const client = new Anthropic({ authToken: environmentKey });
206 const controller = new AbortController();
207 process.once("SIGINT", () => controller.abort());
208 process.once("SIGTERM", () => controller.abort());
209 
210 await new EnvironmentWorker({
126211 client,
127212 environmentId,
128213 environmentKey,
129 tools: (ctx) => [betaBashTool(ctx), myCustomTool]
130 });
214 signal: controller.signal,
215 // List every tool that the agent can call. The worker answers no other tool.
216 tools: (ctx) => [betaBashTool(ctx), getOrderStatus]
217 }).run();
131218 ```
132219 
133220 <CodeGroupItem language="C#">
from line 222
135222 </CodeGroupItem>
136223 
137224 ```go Go
138 worker := environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{
139 EnvironmentID: environmentID,
140 EnvironmentKey: environmentKey,
141 ToolsFunc: func(env *agenttoolset.AgentToolContext) []anthropic.BetaTool {
142 return []anthropic.BetaTool{agenttoolset.BetaBashTool(env), myCustomTool}
143 },
144 })
225 package main
226 
227 import (
228 "context"
229 "log"
230 "os"
231 "os/signal"
232 "syscall"
233 
234 "github.com/anthropics/anthropic-sdk-go/v2"
235 "github.com/anthropics/anthropic-sdk-go/v2/lib/environments"
236 "github.com/anthropics/anthropic-sdk-go/v2/option"
237 "github.com/anthropics/anthropic-sdk-go/v2/toolrunner"
238 "github.com/anthropics/anthropic-sdk-go/v2/tools/agenttoolset"
239 )
240 
241 type orderStatusInput struct {
242 OrderID string `json:"order_id"`
243 }
244 
245 func main() {
246 environmentKey := os.Getenv("ANTHROPIC_ENVIRONMENT_KEY")
247 environmentID := os.Getenv("ANTHROPIC_ENVIRONMENT_ID")
248 
249 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
250 defer stop()
251 
252 getOrderStatus := toolrunner.NewBetaTool(
253 "get_order_status",
254 "Look up an order in the internal fulfillment system by order ID.",
255 anthropic.BetaToolInputSchemaParam{
256 Properties: map[string]any{
257 "order_id": map[string]any{"type": "string", "description": "The order ID"},
258 },
259 Required: []string{"order_id"},
260 },
261 func(ctx context.Context, input orderStatusInput) (anthropic.BetaToolResultBlockParamContentUnion, error) {
262 return anthropic.BetaToolResultBlockParamContentUnion{
263 OfText: &anthropic.BetaTextBlockParam{Text: "Order " + input.OrderID + ": shipped"},
264 }, nil
265 },
266 )
267 
268 client := anthropic.NewClient(option.WithAuthToken(environmentKey))
269 
270 worker := environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{
271 EnvironmentID: environmentID,
272 EnvironmentKey: environmentKey,
273 // List every tool that the agent can call. The worker answers no other tool.
274 ToolsFunc: func(env *agenttoolset.AgentToolContext) []anthropic.BetaTool {
275 return []anthropic.BetaTool{agenttoolset.BetaBashTool(env), getOrderStatus}
276 },
277 })
278 if err := worker.Run(ctx); err != nil {
279 log.Fatalf("worker: %v", err)
280 }
281 }
145282 ```
146283 
147284 <CodeGroupItem language="Java">
from line 296
159296 
160297### Work poller
161298 
162| Option | Description |
163| ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
164| `drain` (go: `Drain`) | Whether to stop polling once the queue is empty rather than waiting for new work. |
165| `block_ms` (typescript: `blockMs`; go: `BlockMs`) | How long each poll waits for work to arrive before returning, in milliseconds. Must be between 1 and 999. The helper polls again automatically. Pass `null` (python: `None`; go: `param.Null[int64]()`) for a non-blocking check. Defaults to a 999ms long-poll. |
166| `reclaim_older_than_ms` (typescript: `reclaimOlderThanMs`; go: `ReclaimOlderThanMs`) | Reclaims work items that were claimed but never acknowledged within this many milliseconds. |
167| `auto_stop` (typescript: `autoStop`; go: `AutoStop`) | Whether to post a stop signal for each work item once your loop body finishes with it. Set it to `false` (python: `False`; go: `param.NewOpt(false)`) when whatever runs the work item posts the stop itself. `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) does, and so does a sandbox you launch that owns the stop call. |
299| Option | Description |
300| ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
301| `drain` (go: `Drain`) | Whether to stop polling once the queue is empty rather than waiting for new work. |
302| `block_ms` (typescript: `blockMs`; go: `BlockMs`) | How long each poll waits for work to arrive before returning, in milliseconds. Must be between 1 and 999. The helper polls again automatically. Pass `null` (python: `None`; go: `param.Null[int64]()`) for a non-blocking check. Defaults to a 999ms long-poll. |
303| `reclaim_older_than_ms` (typescript: `reclaimOlderThanMs`; go: `ReclaimOlderThanMs`) | Reclaims work items that were claimed but never acknowledged within this many milliseconds. |
304| `auto_stop` (typescript: `autoStop`; go: `AutoStop`) | Whether the poller posts a stop signal for each work item once your loop body finishes with it. Defaults to `true` (python: `True`). Set it to `false` (python: `False`; go: `param.NewOpt(false)`) in the two cases that follow this table. |
168305 
169For a complete example, see [Launch sandboxes from the SDK poller](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#launch-sandboxes-from-the-sdk-poller).
306Set `auto_stop` (typescript: `autoStop`; go: `AutoStop`) to `false` (python: `False`; go: `param.NewOpt(false)`) in two cases:
170307 
3081. Your loop calls `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`), which posts the stop itself.
3092. Your loop launches a sandbox for the item and moves on. The worker in that sandbox must post the stop when the session’s work ends, as `ant beta:worker run` and `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) do.
310 
311For a complete example, see [Launch sandboxes from the SDK poller](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#launch-sandboxes-from-the-sdk-poller).
312 
171313### Session tool runner
172314 
173315`client.beta.sessions.events.tool_runner()` (typescript: `client.beta.sessions.events.toolRunner()`; go: `client.Beta.Sessions.Events.NewToolRunner()`) takes a tool list as `tools` (go: `Tools`). To build that list, set up `AgentToolContext` yourself and call `beta_agent_toolset_20260401(env)` (typescript: `betaAgentToolset20260401(ctx)`; go: `agenttoolset.BetaAgentToolset20260401(env)`):
174316 
175317<CodeGroup exclude="shell, csharp, java, php, ruby">
318 <CodeGroupItem language="cURL">
319 `AgentToolContext` is a helper in the Python, TypeScript, and Go SDKs. cURL has no equivalent. Use one of those SDKs.
320 </CodeGroupItem>
321 
322 <CodeGroupItem language="CLI">
323 `AgentToolContext` is a helper in the Python, TypeScript, and Go SDKs. The `ant` CLI has no equivalent. Use one of those SDKs.
324 </CodeGroupItem>
325 
176326 ```python Python
177327 from anthropic.lib.tools.agent_toolset import (
178328 AgentToolContext,

managed-agents/self-hosted-sandboxes-security Changed · +18 / -5 lines

from line 42
4242## What you own
4343 
4444* **Sandbox image quality and runtime hardening.** Anthropic does not inspect or verify your sandbox image. Follow best practices such as dropping unnecessary Linux capabilities, running as a non-root user, and using a read-only root filesystem.
45* **Network egress controls.** Your sandbox’s network access is determined by your VPC and firewall rules. Without egress restrictions, a compromised tool execution can reach arbitrary external hosts. Restrict outbound traffic to only the endpoints your tools require.
45 
46* **Network egress controls.** Your VPC and firewall rules determine your sandbox’s network access. Without egress restrictions, a compromised tool execution can reach arbitrary external hosts. Restrict outbound traffic to only the endpoints your tools require.
47 
4648* **Service key storage and rotation.** The environment service key (`ANTHROPIC_ENVIRONMENT_KEY`) authorizes polling your environment’s work queue and submitting results back to sessions. Store it in a secrets manager, not in environment files or sandbox images. Rotate it immediately if you suspect exposure.
47* **Isolating untrusted workloads.** The environment service key is scoped to one environment’s work queue. If you run untrusted code inside your sandbox, consider provisioning a separate workspace and environment for each trust boundary. This limits each key to a single user’s sessions instead of a shared pool.
48* **Per-session credentials.** Each work item your worker claims can carry a per-session `secret` (csharp, go: `Secret`), which the worker uses in place of the environment service key. Access to [memory stores](https://platform.claude.com/docs/en/managed-agents/memory) requires the `secret` (csharp, go: `Secret`): the memory store endpoints reject the environment key (see [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#forward-the-work-items-secret)). Pass the `secret` (csharp, go: `Secret`) only into the sandbox that serves that session, keep it out of images and shared volumes, and never log it.
49 
50* **Untrusted workload isolation.** The environment service key is scoped to one environment’s work queue. If you run untrusted code inside your sandbox, consider provisioning a separate workspace and environment for each trust boundary. This way, each key reaches only one trust boundary’s sessions, such as one user’s, rather than every session in a shared environment.
51 
52* **Per-session credentials.** Each work item your worker claims can carry a per-session `secret` (csharp, go: `Secret`), which the worker uses in place of the environment service key. Access to [memory stores](https://platform.claude.com/docs/en/managed-agents/memory) requires the `secret` (csharp, go: `Secret`): the memory store endpoints reject the environment service key (see [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#forward-the-work-items-secret)). Pass the `secret` (csharp, go: `Secret`) only into the sandbox that serves that session, keep it out of images and shared volumes, and never log it.
53 
4954* **Tool-execution blast radius.** Tools run inside your sandbox with whatever permissions your process has. Apply least privilege to the process user and mount only the directories your tools require.
55 
5056* **Log retention and session content.** Conversation content and tool outputs pass through your worker and stay in your environment. You are responsible for retaining, redacting, or deleting that data in compliance with your own policies. Anthropic has no visibility into what your worker does with session content once delivered.
51* **Memory store contents.** [Memory stores](https://platform.claude.com/docs/en/managed-agents/memory) remain hosted by Anthropic, including their version history. When a session attaches one, the worker keeps a working copy under `/mnt/memory/` in your sandbox for the session’s duration and syncs changes back. The worker deletes that copy when the session ends, but a worker that exits without running its teardown leaves it behind. Cleanup of leftover copies, the permissions on that path, and isolation between sessions that share a filesystem are your responsibility.
52* **Read-only memory stores.** A store attached with `read_only` access is protected from upload, not from local modification. The worker’s `write` and `edit` tools refuse to write under its directory, nothing there syncs back, and the memory store endpoints reject writes to it made with the session’s `secret` (csharp, go: `Secret`). Other processes in the sandbox can still change the local copy: commands the agent runs through the `bash` tool, and [custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools) or MCP servers you serve from the sandbox, which run with the worker’s permissions. Later tool calls in that session read the changed copy until that memory next changes in the store. If the agent must not be able to alter even its local view of such a store, disable the `bash` tool for that agent and give it no custom tool that writes to the sandbox’s filesystem.
57 
58* **Memory store contents.** Anthropic hosts [memory stores](https://platform.claude.com/docs/en/managed-agents/memory), including their version history. When a session attaches one, the worker keeps a working copy under `/mnt/memory/` in your sandbox while it serves the session and syncs changes back. The worker deletes that copy when it finishes with the session (see [How the worker handles memory](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#how-the-worker-handles-memory)). A worker that exits without running its teardown leaves the copy behind. Cleanup of leftover copies, the permissions on that path, and isolation between sessions that share a filesystem are your responsibility.
59 
60* **Read-only memory stores.** A store attached with `read_only` access is protected from upload, not from local modification.
61 
62 * **What is blocked:** The worker’s `write` and `edit` tools refuse to write under the store’s directory. The worker uploads nothing from that directory. The memory store endpoints reject requests that use the session’s `secret` (csharp, go: `Secret`) to write to the store.
63 * **What is not blocked:** Commands that the agent runs through the `bash` tool can change the local copy. So can [custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools) or MCP servers that you serve from the sandbox, which run with the worker’s permissions.
64 * **What happens to a changed file:** For as long as the worker serves the session, later tool calls read the changed file. The worker doesn’t restore it on its own. If that file gets a new version in the store during that time, the worker’s next sync overwrites the local file with that version.
65 * **How to prevent local changes too:** Disable the `bash` tool for that agent, and give it no custom tools or MCP servers that write to the sandbox’s filesystem.
5366 
5467## What Anthropic cannot do for you
5568 

managed-agents/self-hosted-sandboxes-workers Changed · +49 / -487 lines

## Run one sandbox per session ### Forward the work item’s secret ### Launch sandboxes from the SDK poller ### Run the SDK worker inside the sandbox ## Stage files for a session

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 1
11---
22title: Deploy self-hosted workers
33url: https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers
4description: "Choose how self-hosted sandbox workers claim work and where sessions run: always-on or webhook-triggered, in one process or one sandbox per session."
4description: Choose how self-hosted sandbox workers claim work and where sessions run, then run an always-on worker or trigger workers from webhooks.
55featureMetadata:
66 topic:
77 title: Managed Agents
from line 36
3636 Claude Platform on AWS: beta
3737---
3838 
39The [quickstart](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#quickstart) runs one `ant` CLI worker that polls continuously and runs every session in one process. This page covers the other ways to run a worker and how to choose among them.
39The [self-hosted sandboxes quickstart](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#quickstart) runs one `ant` CLI worker that polls continuously and runs every session in one process. This page helps you choose a deployment pattern and then covers always-on and webhook-triggered workers.
4040 
4141## Choose a deployment pattern
4242 
from line 44
4444 
4545**How the worker claims work:**
4646 
47* **Always-on:** A long-running process polls the queue continuously and needs only outbound HTTPS. This is the simplest setup.
47* **Always-on:** A long-running process polls the queue continuously. The process makes only outbound HTTPS requests, so you don’t expose an endpoint to Anthropic.
4848* **Webhook-triggered:** A handler wakes on `session.status_run_started` and starts polling. This avoids an idle poller, but requires a [webhook](https://platform.claude.com/docs/en/managed-agents/webhooks) endpoint that Anthropic can reach.
4949 
5050**Where each session runs:**
5151 
5252* **In process:** The worker that claims a session also runs its tool calls, in one shared working directory.
53* **Sandbox per session:** A poller launches a fresh sandbox for each claimed session. Choose this for stronger isolation: a fresh filesystem, resource limits, or per-session network controls.
53* **Sandbox per session:** A poller launches a fresh sandbox for each claimed session. Choose this for stronger isolation: a fresh filesystem, resource limits, or per-session network controls. See [Run one sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session), which also covers the Helm chart for Kubernetes.
5454 
5555The CLI and SDK workers support different combinations:
5656 
57| Capability | `ant` CLI | SDK (Python, TypeScript, Go) |
58| ----------------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------- |
59| Always-on polling | Yes | Yes |
60| Webhook-triggered | No | Yes |
61| Sandbox per session | Yes | Yes |
62| [Memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory) | Yes, with default sync settings | Yes, with configurable sync |
63| [Custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools) | No | Yes |
64 
65See [Self-hosted worker reference](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference) for every CLI flag and SDK option. For more control, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work) directly and implement your own worker.
57| Capability | `ant` CLI | SDK (Python, TypeScript, Go) |
58| ----------------------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------- |
59| Always-on polling | Yes | Yes |
60| Webhook-triggered | No | Yes |
61| [Sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session) | Yes | Yes |
62| [Memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory) | Yes, with default sync settings | Yes, with configurable sync |
63| [Custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools) | No | Yes |
64 
65See [Self-hosted worker reference](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference) for every CLI flag and SDK option.
66 
67For more control, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work) directly and implement your own worker. Your worker then does what the SDK workers do. Among other things, it acknowledges each work item, sends heartbeats, and downloads the agent’s skills. It runs only the tool calls that the session’s [permission policy](https://platform.claude.com/docs/en/managed-agents/permission-policies#see-how-each-call-was-evaluated) allows. It returns each result as a `user.tool_result` or `user.custom_tool_result` event. At the end, it stops the item. Use the worker’s source in the [Python SDK](https://github.com/anthropics/anthropic-sdk-python/tree/main/src/anthropic/lib/environments), the [TypeScript SDK](https://github.com/anthropics/anthropic-sdk-typescript/tree/main/src/lib/environments), or the [Go SDK](https://github.com/anthropics/anthropic-sdk-go/tree/main/lib/environments) as a reference.
6668 
6769## Run an always-on worker
6870 
71These samples use `/workspace` as the worker’s working directory. The directory must exist before the worker starts. On a new host, create it and give the worker’s user write access, as in the “Start the worker” step of [Run your first session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#run-your-first-session).
72 
73On macOS, `mkdir` can’t create `/workspace`, because the root volume is read-only. Create `~/workspace` instead, as that step shows. In place of `/workspace`, use the full path that `echo ~/workspace` prints, because the SDK doesn’t expand `~`.
74 
6975Start a worker that polls the queue continuously. It authenticates with the [environment key](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#run-your-first-session) from the quickstart:
7076 
7177<CodeGroup exclude="shell:cURL, csharp, java, php, ruby">
78 <CodeGroupItem language="cURL">
79 A worker is a long-running process, not a single HTTP request. Run the `ant` CLI worker instead: `ant beta:worker poll --workdir /workspace`.
80 </CodeGroupItem>
81 
7282 ```bash CLI
7383 ant beta:worker poll --workdir /workspace
7484 ```
from line 103
93103 workdir="/workspace",
94104 )
95105 task = asyncio.create_task(worker.run())
96 # Cancelling the task, rather than killing the process, lets the worker stop its
106 # Canceling the task, rather than killing the process, lets the worker stop its
97107 # in-flight work item and upload changed memory files before it exits.
98108 loop = asyncio.get_running_loop()
99109 for signum in (signal.SIGINT, signal.SIGTERM):
from line 193
183193 
184194<Steps>
185195 <Step title="Subscribe to session webhooks">
186 In the [Claude Console](https://platform.claude.com/settings/workspaces/default/webhooks), define a webhook endpoint that listens for `session.status_run_started` events. See [Webhooks](https://platform.claude.com/docs/en/managed-agents/webhooks) for details.
196 In the [Claude Console](https://platform.claude.com/settings/workspaces/default/webhooks), define a webhook endpoint that listens for `session.status_run_started` events. See [Subscribe to webhooks](https://platform.claude.com/docs/en/managed-agents/webhooks) for details.
187197 </Step>
188198 
189199 <Step title="Export the webhook signing key">
from line 205
195205 </Step>
196206 
197207 <Step title="Implement the webhook handler">
198 Start the worker when `session.status_run_started` fires. The handler drains the queue and hands each claimed work item to `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`), which downloads skills, runs tool calls, posts results back, and returns.
208 Start the worker when `session.status_run_started` fires. The handler drains the queue and hands each claimed work item to `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) (in the Python, TypeScript, and Go SDKs). That method downloads skills, runs tool calls, posts results back, and returns.
209 
210 The samples use `/workspace` as the working directory. Before you start the handler, create that directory on the handler host. Make sure that the handler’s user can write to it, as in the “Start the worker” step of [Run your first session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes#run-your-first-session).
199211 
200212 <CodeGroup exclude="shell, csharp, java, php, ruby">
213 <CodeGroupItem language="cURL">
214 This handler needs more logic than a single shell command. Use the Python, TypeScript, or Go SDK to run it.
215 </CodeGroupItem>
216 
217 <CodeGroupItem language="CLI">
218 This handler needs more logic than a single shell command. Use the Python, TypeScript, or Go SDK to run it.
219 </CodeGroupItem>
220 
201221 <CodeGroupItem>
202222 To verify webhook signatures, install the webhooks extra: `pip install "anthropic[webhooks]"`.
203223 
from line 232
212232 client = anthropic.AsyncAnthropic(
213233 auth_token=environment_key,
214234 )
215 # Cancelled by shutdown() so an in-flight work item can upload changed memory files and
235 # Canceled by shutdown() so an in-flight work item can upload changed memory files and
216236 # remove its store directories before the process exits.
217237 inflight: set[asyncio.Task[None]] = set()
218238 
from line 341
321341 ```
322342 
323343 <CodeGroupItem language="C#">
324 The C# SDK does not have `EnvironmentWorker`. To handle work items from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
344 The C# SDK does not have `EnvironmentWorker`. To handle work items from your own code, implement your own worker, as [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern) describes.
325345 </CodeGroupItem>
326346 
327347 ```go Go
from line 374
354374 worker = environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{
355375 Workdir: "/workspace",
356376 })
357 // Cancelled on SIGINT or SIGTERM (set in main) so an in-flight work item can
377 // Canceled on SIGINT or SIGTERM (set in main) so an in-flight work item can
358378 // upload changed memory files and remove its store directories before exit.
359379 shutdown context.Context
360380 )
from line 455
435455 ```
436456 
437457 <CodeGroupItem language="Java">
438 The Java SDK does not have `EnvironmentWorker`. To handle work items from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
458 The Java SDK does not have `EnvironmentWorker`. To handle work items from your own code, implement your own worker, as [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern) describes.
439459 </CodeGroupItem>
440460 
441461 <CodeGroupItem language="PHP">
442 The PHP SDK does not have `EnvironmentWorker`. To handle work items from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
462 The PHP SDK does not have `EnvironmentWorker`. To handle work items from your own code, implement your own worker, as [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern) describes.
443463 </CodeGroupItem>
444464 
445465 <CodeGroupItem language="Ruby">
446 The Ruby SDK does not have `EnvironmentWorker`. To handle work items from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
466 The Ruby SDK does not have `EnvironmentWorker`. To handle work items from your own code, implement your own worker, as [Choose a deployment pattern](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#choose-a-deployment-pattern) describes.
447467 </CodeGroupItem>
448468 </CodeGroup>
449469 
450 Because the handler claims work itself, it must [forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#forward-the-work-items-secret), as the `work_secret` (typescript: `workSecret`; go: `WorkSecret`) argument does here.
470 In the Python, TypeScript, and Go SDKs, `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) needs the work item’s secret to mount memory stores. A worker that polls with `run()` (go: `Run()`) already has the secret. This handler claims each item itself, so it passes the secret in the `work_secret` (typescript: `workSecret`; go: `WorkSecret`) argument. See [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#forward-the-work-items-secret).
451471 </Step>
452472</Steps>
453473 
454This handler runs every claimed item in one process on one host. If your sessions attach the same memory store, see [Isolate sessions that share a store](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#isolate-sessions-that-share-a-store).
455 
456## Run one sandbox per session
457 
458A poller on the host claims work and calls your script once for each work item. The script launches a sandbox for that one session.
459 
460<Steps>
461 <Step title="Build the sandbox image">
462 Install `ant` and set `ant beta:worker run` as the entrypoint. When a sandbox starts, it reads session details from environment variables, handles that session, and exits. The base image must provide `/bin/bash`; `curl` is only used at build time.
463 
464 ```dockerfile
465 FROM your-base-image
466 ARG ANT_VERSION=2.11.0
467 ARG TARGETARCH
468 RUN ARCH=$([ "$TARGETARCH" = "arm64" ] && echo arm64 || echo amd64) && \
469 curl -fsSL "https://github.com/anthropics/anthropic-cli/releases/download/v${ANT_VERSION}/ant_${ANT_VERSION}_linux_${ARCH}.tar.gz" \
470 | tar -xz -C /usr/local/bin ant
471 WORKDIR /workspace
472 VOLUME /workspace
473 ENTRYPOINT ["ant", "beta:worker", "run"]
474 ```
475 </Step>
476 
477 <Step title="Write the spawn script">
478 The script forwards the session details into a fresh sandbox. It requires `jq` on the poller host.
479 
480 ```bash
481 #!/bin/bash
482 # spawn.sh: called once for each claimed work item
483 # The claimed work item arrives as JSON on stdin.
484 ANTHROPIC_WORK_SECRET="$(jq -r '.secret // empty')"
485 export ANTHROPIC_WORK_SECRET
486 mkdir -p "/host/outputs/$ANTHROPIC_SESSION_ID"
487 exec docker run --rm \
488 -e ANTHROPIC_SESSION_ID -e ANTHROPIC_ENVIRONMENT_KEY \
489 -e ANTHROPIC_WORK_ID -e ANTHROPIC_ENVIRONMENT_ID -e ANTHROPIC_BASE_URL \
490 -e ANTHROPIC_WORK_SECRET \
491 -v "/host/outputs/$ANTHROPIC_SESSION_ID":/workspace \
492 your-image
493 ```
494 
495 The poller sets the `ANTHROPIC_*` variables that the script forwards, except the secret. See [Environment variables](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-reference#environment-variables).
496 
497 `/host/outputs` is a host directory you choose. Mounting it at `/workspace` lets you retrieve the session’s deliverables after the sandbox exits. The mount also picks up the downloaded `skills/` tree and any intermediate files.
498 </Step>
499 
500 <Step title="Start the poller">
501 ```bash
502 ant beta:worker poll --on-work ./spawn.sh
503 ```
504 </Step>
505</Steps>
506 
507### Forward the work item’s secret
508 
509Each claimed work item can carry a per-session `secret` (csharp, go: `Secret`), which Anthropic issues. The worker that runs the session needs it to mount [memory stores](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory).
510 
511A worker that claims and runs sessions in one process (`ant beta:worker poll` without `--on-work`, or `EnvironmentWorker` with `run()` (go: `Run()`)) passes the secret along itself. When your own code sits between the claim and the worker, you forward it:
512 
513| You claim work with | The secret arrives as | Pass it to the worker as |
514| -------------------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
515| `ant beta:worker poll --on-work` | The `secret` field of the work item JSON on your script’s standard input | `ANTHROPIC_WORK_SECRET` in the sandbox’s environment |
516| The SDK’s `work.poller()` (go: `environments.NewWorkPoller()`) | The `secret` (go: `Secret`) field of each claimed work item | `ANTHROPIC_WORK_SECRET` in the sandbox’s environment, or the `work_secret` (typescript: `workSecret`; go: `WorkSecret`) argument to `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`) |
517 
518Pass the secret only into the sandbox that serves that session, and never log it. See [Security model](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-security) for how it relates to the environment key.
519 
520### Launch sandboxes from the SDK poller
521 
522To claim work from your own code instead of `ant beta:worker poll --on-work`, use `work.poller()` (typescript: `new WorkPoller()`; go: `environments.NewWorkPoller()`). It polls the queue and gives you each claimed session, and you launch the sandbox:
523 
524<CodeGroup exclude="shell, csharp, java, php, ruby">
525 <CodeGroupItem language="cURL">
526 Claiming work in a loop and launching a sandbox for each session needs more logic than a single shell command. From the shell, run `ant beta:worker poll --on-work` with a spawn script, as in [Run one sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-one-sandbox-per-session).
527 </CodeGroupItem>
528 
529 <CodeGroupItem language="CLI">
530 To claim work from the shell and launch a sandbox for each session, run `ant beta:worker poll --on-work` with a spawn script, as in [Run one sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-one-sandbox-per-session).
531 </CodeGroupItem>
532 
533 ```python Python
534 import asyncio
535 import os
536 
537 from anthropic import AsyncAnthropic
538 from anthropic.types.beta.environments import BetaSelfHostedWork
539 
540 SANDBOX_ENV = (
541 "ANTHROPIC_ENVIRONMENT_ID",
542 "ANTHROPIC_ENVIRONMENT_KEY",
543 "ANTHROPIC_WORK_ID",
544 "ANTHROPIC_SESSION_ID",
545 "ANTHROPIC_WORK_SECRET",
546 "ANTHROPIC_BASE_URL", # forwarded only when set on this host
547 )
548 
549 
550 async def launch_container(work: BetaSelfHostedWork) -> None:
551 print(f"claimed session {work.data.id}")
552 # Replace `docker run` with your own sandbox launcher. Forward the environment
553 # key (never your API key) and the work item's per-session secret: the worker
554 # inside needs the secret to mount the session's memory stores.
555 env = os.environ | {
556 "ANTHROPIC_WORK_ID": work.id,
557 "ANTHROPIC_SESSION_ID": work.data.id,
558 "ANTHROPIC_WORK_SECRET": work.secret or "",
559 }
560 forward = [arg for name in SANDBOX_ENV for arg in ("-e", name)]
561 launcher = await asyncio.create_subprocess_exec(
562 "docker", "run", "--rm", "--detach", *forward, "your-image", env=env
563 )
564 await launcher.wait()
565 
566 
567 async def main() -> None:
568 environment_key = os.environ["ANTHROPIC_ENVIRONMENT_KEY"]
569 environment_id = os.environ["ANTHROPIC_ENVIRONMENT_ID"]
570 async with AsyncAnthropic(auth_token=environment_key) as client:
571 async for work in client.beta.environments.work.poller(
572 environment_id=environment_id,
573 environment_key=environment_key,
574 auto_stop=False, # the launched sandbox owns the stop call
575 ):
576 await launch_container(work)
577 
578 
579 asyncio.run(main())
580 ```
581 
582 ```typescript TypeScript
583 import { spawn } from "node:child_process";
584 import { once } from "node:events";
585 import Anthropic from "@anthropic-ai/sdk";
586 import { WorkPoller } from "@anthropic-ai/sdk/helpers/beta/environments";
587 import type { BetaSelfHostedWork } from "@anthropic-ai/sdk/resources/beta/environments";
588 
589 const SANDBOX_ENV = [
590 "ANTHROPIC_ENVIRONMENT_ID",
591 "ANTHROPIC_ENVIRONMENT_KEY",
592 "ANTHROPIC_WORK_ID",
593 "ANTHROPIC_SESSION_ID",
594 "ANTHROPIC_WORK_SECRET",
595 "ANTHROPIC_BASE_URL" // forwarded only when set on this host
596 ];
597 
598 const environmentKey = process.env.ANTHROPIC_ENVIRONMENT_KEY!;
599 const environmentId = process.env.ANTHROPIC_ENVIRONMENT_ID!;
600 const client = new Anthropic({ authToken: environmentKey });
601 
602 async function launchContainer(work: BetaSelfHostedWork): Promise<void> {
603 console.log(`claimed session ${work.data.id}`);
604 // Replace `docker run` with your own sandbox launcher. Forward the environment
605 // key (never your API key) and the work item's per-session secret: the worker
606 // inside needs the secret to mount the session's memory stores.
607 const env = {
608 ...process.env,
609 ANTHROPIC_WORK_ID: work.id,
610 ANTHROPIC_SESSION_ID: work.data.id,
611 ANTHROPIC_WORK_SECRET: work.secret ?? ""
612 };
613 const forward = SANDBOX_ENV.flatMap((name) => ["-e", name]);
614 const launcher = spawn("docker", ["run", "--rm", "--detach", ...forward, "your-image"], {
615 env,
616 stdio: "inherit"
617 });
618 await once(launcher, "close");
619 }
620 
621 const poller = new WorkPoller({
622 client,
623 environmentId,
624 environmentKey,
625 autoStop: false // the launched sandbox owns the stop call
626 });
627 
628 for await (const work of poller) {
629 await launchContainer(work);
630 }
631 ```
632 
633 <CodeGroupItem language="C#">
634 The C# SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
635 </CodeGroupItem>
636 
637 ```go Go
638 package main
639 
640 import (
641 "context"
642 "fmt"
643 "log"
644 "os"
645 "os/exec"
646 
647 "github.com/anthropics/anthropic-sdk-go/v2"
648 "github.com/anthropics/anthropic-sdk-go/v2/lib/environments"
649 "github.com/anthropics/anthropic-sdk-go/v2/option"
650 "github.com/anthropics/anthropic-sdk-go/v2/packages/param"
651 )
652 
653 var sandboxEnv = []string{
654 "ANTHROPIC_ENVIRONMENT_ID",
655 "ANTHROPIC_ENVIRONMENT_KEY",
656 "ANTHROPIC_WORK_ID",
657 "ANTHROPIC_SESSION_ID",
658 "ANTHROPIC_WORK_SECRET",
659 "ANTHROPIC_BASE_URL", // forwarded only when set on this host
660 }
661 
662 func launchContainer(ctx context.Context, work *anthropic.BetaSelfHostedWork) error {
663 fmt.Printf("claimed session %s\n", work.Data.ID)
664 // Replace `docker run` with your own sandbox launcher. Forward the environment
665 // key (never your API key) and the work item's per-session secret: the worker
666 // inside needs the secret to mount the session's memory stores.
667 args := []string{"run", "--rm", "--detach"}
668 for _, name := range sandboxEnv {
669 args = append(args, "-e", name)
670 }
671 launcher := exec.CommandContext(ctx, "docker", append(args, "your-image")...)
672 launcher.Env = append(os.Environ(),
673 "ANTHROPIC_WORK_ID="+work.ID,
674 "ANTHROPIC_SESSION_ID="+work.Data.ID,
675 "ANTHROPIC_WORK_SECRET="+work.Secret,
676 )
677 launcher.Stdout, launcher.Stderr = os.Stdout, os.Stderr
678 return launcher.Run()
679 }
680 
681 func main() {
682 environmentID := os.Getenv("ANTHROPIC_ENVIRONMENT_ID")
683 environmentKey := os.Getenv("ANTHROPIC_ENVIRONMENT_KEY")
684 
685 client := anthropic.NewClient(option.WithAuthToken(environmentKey))
686 
687 ctx := context.Background()
688 
689 poller := environments.NewWorkPoller(ctx, client, environments.WorkPollerOptions{
690 EnvironmentID: environmentID,
691 EnvironmentKey: environmentKey,
692 AutoStop: param.NewOpt(false), // the launched sandbox owns the stop call
693 })
694 defer poller.Close()
695 
696 for work, err := range poller.All() {
697 if err != nil {
698 log.Fatal(err)
699 }
700 if err := launchContainer(ctx, work); err != nil {
701 log.Fatal(err)
702 }
703 }
704 }
705 ```
706 
707 <CodeGroupItem language="Java">
708 The Java SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
709 </CodeGroupItem>
710 
711 <CodeGroupItem language="PHP">
712 The PHP SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
713 </CodeGroupItem>
714 
715 <CodeGroupItem language="Ruby">
716 The Ruby SDK does not have a helper that polls for work. To claim work from your own code, call the [Environments Work endpoints](https://platform.claude.com/docs/en/api/beta/environments/work).
717 </CodeGroupItem>
718</CodeGroup>
719 
720### Run the SDK worker inside the sandbox
721 
722Replace the `ant beta:worker run` entrypoint with an SDK entrypoint when the sandbox must [serve custom tools](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-custom-tools) or use [non-default memory sync settings](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#configure-sync). The entrypoint constructs `EnvironmentWorker` and calls `handle_item()` (typescript: `handleItem()`; go: `HandleItem()`), which reads the same `ANTHROPIC_*` variables that the spawn script forwards.
723 
724<CodeGroup exclude="shell, csharp, java, php, ruby">
725 ```python Python
726 import asyncio
727 import contextlib
728 import os
729 import signal
730 from anthropic import AsyncAnthropic
731 from anthropic.lib.environments import EnvironmentWorker
732 
733 
734 async def main() -> None:
735 async with AsyncAnthropic(
736 auth_token=os.environ["ANTHROPIC_ENVIRONMENT_KEY"]
737 ) as client:
738 worker = EnvironmentWorker(client, workdir="/workspace")
739 # With no arguments, handle_item() reads the ANTHROPIC_* variables the spawn
740 # script forwarded, including ANTHROPIC_WORK_SECRET.
741 task = asyncio.create_task(worker.handle_item())
742 # Cancelling the task when the container is stopped lets the worker upload
743 # changed memory files and remove the store directories before it exits.
744 loop = asyncio.get_running_loop()
745 for signum in (signal.SIGINT, signal.SIGTERM):
746 loop.add_signal_handler(signum, task.cancel)
747 with contextlib.suppress(asyncio.CancelledError):
748 await task
749 
750 
751 asyncio.run(main())
752 ```
753 
754 ```typescript TypeScript
755 import Anthropic from "@anthropic-ai/sdk";
756 import { EnvironmentWorker } from "@anthropic-ai/sdk/helpers/beta/environments";
757 
758 const client = new Anthropic({ authToken: process.env.ANTHROPIC_ENVIRONMENT_KEY });
759 const controller = new AbortController();
760 // Aborting when the container is stopped lets the worker upload changed memory
761 // files and remove the store directories before it exits.
762 process.once("SIGTERM", () => controller.abort());
763 process.once("SIGINT", () => controller.abort());
764 
765 // With no arguments, handleItem() reads the ANTHROPIC_* variables the spawn
766 // script forwarded, including ANTHROPIC_WORK_SECRET.
767 await new EnvironmentWorker({
768 client,
769 workdir: "/workspace",
770 signal: controller.signal
771 }).handleItem();
772 ```
773 
774 <CodeGroupItem language="C#">
775 The C# SDK does not have `EnvironmentWorker`.
776 </CodeGroupItem>
777 
778 ```go Go
779 package main
780 
781 import (
782 "context"
783 "log"
784 "os"
785 "os/signal"
786 "syscall"
787 
788 "github.com/anthropics/anthropic-sdk-go/v2"
789 "github.com/anthropics/anthropic-sdk-go/v2/lib/environments"
790 "github.com/anthropics/anthropic-sdk-go/v2/option"
791 )
792 
793 func main() {
794 // Cancelling the context when the container is stopped lets the worker upload
795 // changed memory files and remove the store directories before it exits.
796 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
797 defer stop()
798 
799 client := anthropic.NewClient(option.WithAuthToken(os.Getenv("ANTHROPIC_ENVIRONMENT_KEY")))
800 worker := environments.NewEnvironmentWorker(client, environments.EnvironmentWorkerOptions{
801 Workdir: "/workspace",
802 })
803 // With zero-value options, HandleItem reads the ANTHROPIC_* variables the spawn
804 // script forwarded, including ANTHROPIC_WORK_SECRET.
805 if err := worker.HandleItem(ctx, environments.HandleItemOptions{}); err != nil {
806 log.Fatalf("worker: %v", err)
807 }
808 }
809 ```
810 
811 <CodeGroupItem language="Java">
812 The Java SDK does not have `EnvironmentWorker`.
813 </CodeGroupItem>
814 
815 <CodeGroupItem language="PHP">
816 The PHP SDK does not have `EnvironmentWorker`.
817 </CodeGroupItem>
818 
819 <CodeGroupItem language="Ruby">
820 The Ruby SDK does not have `EnvironmentWorker`.
821 </CodeGroupItem>
822</CodeGroup>
823 
824## Stage files for a session
825 
826Anthropic doesn’t mount files or GitHub repositories into self-hosted sandboxes. To make session-specific files available:
827 
8281. Pass file references, such as an S3 path or commit SHA, in the session’s `metadata` field.
8292. In your spawn script or `--on-work` handler, retrieve the session (`GET /v1/sessions/{session_id}`) and read `metadata`. The claimed work item carries the session ID but not the metadata.
8303. Stage the files into the working directory before any tool runs.
831 
832<CodeGroup>
833 ```bash cURL
834 curl -sS --fail-with-body https://api.anthropic.com/v1/sessions \
835 -H "x-api-key: $ANTHROPIC_API_KEY" \
836 -H "anthropic-version: 2026-10-21" \
837 -H "anthropic-beta: managed-agents-2026-04-01" \
838 -H "content-type: application/json" \
839 -d '{
840 "agent": "'"$AGENT_ID"'",
841 "environment_id": "'"$ANTHROPIC_ENVIRONMENT_ID"'",
842 "metadata": {"input_file": "s3://my-bucket/data.csv"}
843 }'
844 ```
845 
846 ```bash CLI
847 ant beta:sessions create \
848 --agent "$AGENT_ID" \
849 --environment-id "$ANTHROPIC_ENVIRONMENT_ID" \
850 --metadata '{"input_file": "s3://my-bucket/data.csv"}'
851 ```
852 
853 ```python Python
854 session = client.beta.sessions.create(
855 agent=agent.id,
856 environment_id=environment.id,
857 metadata={"input_file": "s3://my-bucket/data.csv"},
858 )
859 ```
860 
861 ```typescript TypeScript
862 const session = await client.beta.sessions.create({
863 agent: agent.id,
864 environment_id: environment.id,
865 metadata: { input_file: "s3://my-bucket/data.csv" }
866 });
867 ```
868 
869 ```csharp C#
870 var session = await client.Beta.Sessions.Create(new()
871 {
872 Agent = agent.ID,
873 EnvironmentID = environment.ID,
874 Metadata = new Dictionary<string, string> { ["input_file"] = "s3://my-bucket/data.csv" },
875 });
876 ```
877 
878 ```go Go
879 session, err := client.Beta.Sessions.New(ctx, anthropic.BetaSessionNewParams{
880 Agent: anthropic.BetaSessionNewParamsAgentUnion{OfString: anthropic.String(agent.ID)},
881 EnvironmentID: environment.ID,
882 Metadata: map[string]string{
883 "input_file": "s3://my-bucket/data.csv",
884 },
885 })
886 if err != nil {
887 panic(err)
888 }
889 ```
890 
891 ```java Java
892 var session = client.beta().sessions().create(SessionCreateParams.builder()
893 .agent(agent.id())
894 .environmentId(environment.id())
895 .metadata(SessionCreateParams.Metadata.builder()
896 .putAdditionalProperty("input_file", JsonValue.from("s3://my-bucket/data.csv"))
897 .build())
898 .build());
899 ```
900 
901 ```php PHP
902 $session = $client->beta->sessions->create(
903 agent: $agent->id,
904 environmentID: $environment->id,
905 metadata: ['input_file' => 's3://my-bucket/data.csv'],
906 );
907 ```
908 
909 ```ruby Ruby
910 session = client.beta.sessions.create(
911 agent: agent.id,
912 environment_id: environment.id,
913 metadata: {input_file: "s3://my-bucket/data.csv"}
914 )
915 ```
916</CodeGroup>
474This handler runs every claimed item in one process, and it runs items from separate webhook deliveries at the same time. Those sessions share one filesystem, including `/workspace` and `/mnt/memory`. If your sessions attach the same memory store, see [Isolate sessions that share a store](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-memory#isolate-sessions-that-share-a-store).
917475 
918476## Next steps
919477 
920478<CardGroup cols={2}>
921 <Card title="Monitor and troubleshoot" icon="lightning" href="https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations">
479 <Card title="Run one sandbox per session" icon="cube" href="https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session">
480 Launch sandboxes with the Helm chart on Kubernetes, a spawn script, or the SDK poller.
481 </Card>
482 
483 <Card title="Monitor and troubleshoot self-hosted workers" icon="lightning" href="https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-operations">
922484 Read queue depth, stop sessions and workers cleanly, and fix common failures.
923485 </Card>
924486 
925487 

managed-agents/self-hosted/call-the-api Changed · +4 / -4 lines

from line 619
619619 
620620For workers that you start yourself, put input files in the working directory before you send the message that needs them. Read output files from it afterward.
621621 
622When you start a container for each session yourself, mount a directory that holds the session’s input files as the container’s working directory. Collect the output files from it after the container exits. See [Stage files for a session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#stage-files-for-a-session).
622When you start a container for each session yourself, mount a directory that holds the session’s input files as the container’s working directory. Collect the output files from it after the container exits. See [Stage files for a session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#stage-files-for-a-session).
623623 
624624## Find more examples in the hosted guides
625625 
from line 699
699699 
700700### Run workers in production
701701 
702For anything but a local experiment, start one container for each session and run `ant beta:worker run` in it, as [Run one sandbox per session](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-one-sandbox-per-session) shows. Give its image what [Build your own sandbox image](https://platform.claude.com/docs/en/managed-agents/self-hosted/call-the-api#build-your-own-sandbox-image) lists, and change three things in that setup:
702For anything but a local experiment, start one container for each session and run `ant beta:worker run` in it. [Launch sandboxes with a spawn script](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#launch-sandboxes-with-a-spawn-script) shows how. Give the container’s image what [Build your own sandbox image](https://platform.claude.com/docs/en/managed-agents/self-hosted/call-the-api#build-your-own-sandbox-image) lists, and change three things in that setup:
703703 
704704* **Environment key:** Don’t pass `ANTHROPIC_ENVIRONMENT_KEY` into a session’s container. The server accepts that key for every session in the environment, and the container needs access to one session only.
705* **Work item’s secret:** Pass this secret in place of the key, because the server accepts it for that one session only. [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#forward-the-work-items-secret) shows where your code receives it. Where that section sets `ANTHROPIC_WORK_SECRET`, put the secret in a file that only the container’s user can read. For example, pipe the secret to the container’s standard input, and have the container write the file before it starts the worker. Then set `ANTHROPIC_WORK_SECRET_FILE` to the file’s path.
705* **Work item’s secret:** Pass this secret in place of the key, because the server accepts it for that one session only. [Forward the work item’s secret](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#forward-the-work-items-secret) shows where your code receives it. Where that section sets `ANTHROPIC_WORK_SECRET`, put the secret in a file that only the container’s user can read. For example, pipe the secret to the container’s standard input, and have the container write the file before it starts the worker. Then, set `ANTHROPIC_WORK_SECRET_FILE` to the file’s path.
706706* **Server address:** Set `ANTHROPIC_BASE_URL` to an address that the container can reach. `http://127.0.0.1:8400` isn’t one.
707707 
708708For an SDK worker, two more points apply:
709709 
710710* **Version:** Build the worker on the latest version of the SDK, as [SDKs, CLI, and libraries](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) describes. That version’s worker waits for approval before it runs a tool call that needs it, and never runs a call that a policy denies. A worker built on an earlier version runs every tool call as soon as it arrives.
711* **Samples:** The samples in [Run the SDK worker inside the sandbox](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers#run-the-sdk-worker-inside-the-sandbox) read the environment key, so they don’t work here as they are.
711* **Samples:** The samples in [Run the SDK worker inside the sandbox](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-per-session#run-the-sdk-worker-inside-the-sandbox) read the environment key, so they don’t work here as they are.
712712 
713713### Build your own sandbox image
714714 

release-notes/overview Changed · +45 / -43 lines

from line 451
451451 
452452### April 23, 2026
453453 
454* Memory for Claude Managed Agents is now in beta under the standard `managed-agents-2026-04-01` header. See [Using agent memory](https://platform.claude.com/docs/en/managed-agents/memory) for the full integration guide.
454* Memory for Claude Managed Agents is now available in beta under the standard `managed-agents-2026-04-01` header. See [Using agent memory](https://platform.claude.com/docs/en/managed-agents/memory) for the full integration guide.
455455 
456456### April 20, 2026
457457 
from line 459
459459 
460460### April 16, 2026
461461 
462* We’ve launched [Claude Opus 4.7](https://www.anthropic.com/news/claude-opus-4-7), our most capable model for complex reasoning and agentic coding, at the same $5 / $25 USD per MTok pricing as Opus 4.6. See [What’s new in Claude Opus 4.7](https://platform.claude.com/docs/en/about-claude/models/whats-new-claude-4-7) for capability improvements, new features, and the updated tokenizer. Opus 4.7 includes API breaking changes versus Opus 4.6; see the [migration guide](https://platform.claude.com/docs/en/about-claude/models/migration-guide) before upgrading.
462* We’ve [launched Claude Opus 4.7](https://www.anthropic.com/news/claude-opus-4-7), our most capable model for complex reasoning and agentic coding, at the same $5 / $25 USD per MTok pricing as Claude Opus 4.6. See [Claude Opus 4.7](https://platform.claude.com/docs/en/models/opus-4-7/overview) for its specifications. Opus 4.7 includes an updated tokenizer and API breaking changes versus Opus 4.6; see [Migration guides](https://platform.claude.com/docs/en/about-claude/models/migration-guide) before upgrading.
463463* [Claude in Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock) is now open to all Amazon Bedrock customers. Claude Opus 4.7 and Claude Haiku 4.5 are available self-serve from the Bedrock console through the Messages API endpoint at `/anthropic/v1/messages`, in 27 AWS regions with global and regional endpoints.
464464* We’ve launched [task budgets](https://platform.claude.com/docs/en/build-with-claude/task-budgets) in beta on Claude Opus 4.7. Give Claude an advisory token budget for a full agentic loop (thinking, tool calls, tool results, and output) and the model sees a running countdown, using it to prioritize work and finish gracefully as the budget is consumed. Include the `task-budgets-2026-03-13` beta header in your requests.
465465* Claude Opus 4.7 supports [high-resolution image input](https://platform.claude.com/docs/en/build-with-claude/vision#high-resolution-image-support-on-claude-opus-4-7), raising the maximum image resolution from 1,568 to 2,576 pixels on the long edge for improved performance on computer use, screenshot understanding, and document analysis. High-resolution support is automatic and requires no beta header; images might use up to approximately 3x more image tokens than on prior models.
from line 481
481481### April 7, 2026
482482 
483483* We announced [Claude Mythos Preview](https://anthropic.com/glasswing) is available as a gated research preview for defensive cybersecurity work as part of [Project Glasswing](https://anthropic.com/glasswing). Access is invitation-only.
484* The [Messages API](https://platform.claude.com/docs/en/api/messages) is now available on Amazon Bedrock as a research preview. The new Claude in Amazon Bedrock endpoint at `/anthropic/v1/messages` uses the same request shape as the first-party Claude API and runs on AWS-managed infrastructure with zero operator access. Available in `us-east-1`; contact your Anthropic account executive to request access. Learn more in [Claude in Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock).
484* The [Messages API](https://platform.claude.com/docs/en/api/messages) is now available on Amazon Bedrock in research preview. The new Claude in Amazon Bedrock endpoint at `/anthropic/v1/messages` uses the same request shape as the first-party Claude API and runs on AWS-managed infrastructure with zero operator access. It’s available in `us-east-1`. Contact your Anthropic account executive to request access. Learn more in [Claude in Amazon Bedrock (`bedrock-mantle`)](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock).
485485 
486486### March 30, 2026
487487 
from line 504
504504 
505505### February 19, 2026
506506 
507* We’ve launched **automatic caching** for the Messages API. Add a single `cache_control` field to your request body and the system automatically caches the last cacheable block, moving the cache point forward as conversations grow. No manual breakpoint management required. Works alongside existing block-level cache control for fine-grained optimization. Available on the Claude API and Microsoft Foundry (preview). Learn more in [Automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching).
507* We’ve launched **automatic caching** for the Messages API. Add a single `cache_control` field to your request body and the system automatically caches the last cacheable block, moving the cache point forward as conversations grow. No manual breakpoint management required. Works alongside existing block-level cache control for fine-grained optimization. Available on the Claude API and Microsoft Foundry. Learn more in [Automatic caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#automatic-caching).
508508* We’ve retired the Claude Sonnet 3.7 model (`claude-3-7-sonnet-20250219`) and the Claude Haiku 3.5 model (`claude-3-5-haiku-20241022`). All requests to Claude Sonnet 3.7 will now return an error. Requests to Claude Haiku 3.5 on the Claude API will now return an error; it remains available on Amazon Bedrock and Google Cloud. We recommend upgrading to [Claude Sonnet 4.6](https://platform.claude.com/docs/en/models/overview#latest-models-comparison) and [Claude Haiku 4.5](https://platform.claude.com/docs/en/models/overview#latest-models-comparison) respectively. Researchers can request ongoing access through the [External Researcher Access Program](https://support.claude.com/en/articles/9125743-what-is-the-external-researcher-access-program).
509509* We announced the deprecation of the Claude Haiku 3 model (`claude-3-haiku-20240307`), with retirement scheduled for April 20, 2026. We recommend migrating to [Claude Haiku 4.5](https://platform.claude.com/docs/en/models/overview#latest-models-comparison). Read more in [Model deprecations](https://platform.claude.com/docs/en/about-claude/model-deprecations).
510510 
511511### February 17, 2026
512512 
513* We’ve [launched Claude Sonnet 4.6](https://www.anthropic.com/news/claude-sonnet-4-6), our latest balanced model combining speed and intelligence for everyday tasks. Sonnet 4.6 delivers improved agentic search performance while consuming fewer tokens. Sonnet 4.6 supports [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) and a [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows) (beta). See [Models & Pricing](https://platform.claude.com/docs/en/models/overview) for details.
513* We’ve [launched Claude Sonnet 4.6](https://www.anthropic.com/news/claude-sonnet-4-6), our latest balanced model combining speed and intelligence for everyday tasks. Sonnet 4.6 delivers improved agentic search performance while consuming fewer tokens. Sonnet 4.6 supports [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) and a [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows), which is in beta. See [Models overview](https://platform.claude.com/docs/en/models/overview) for details.
514514* API [code execution](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) is now **free when used with web search or web fetch**. Sandboxed code execution improves model capability and token efficiency. See the [pricing details](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing) for standalone usage.
515515* The [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) and [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) are available with no beta header required. Web search and web fetch now support [dynamic filtering](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#dynamic-filtering), which uses code execution to filter results before they reach the context window for better performance and reduced token cost.
516516* The [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool), [web fetch tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool), [tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool), [tool use examples](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#providing-tool-use-examples), and [memory tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool) no longer require a beta header.
from line 517
517517 
518518### February 7, 2026
519519 
520* We’ve launched [fast mode](https://platform.claude.com/docs/en/build-with-claude/fast-mode) in research preview for Opus 4.6, providing significantly faster output token generation through the `speed` parameter. Fast mode is up to 2.5x as fast at premium pricing. Interested customers should join the [waitlist](https://claude.com/fast-mode).
520* We’ve launched [fast mode](https://platform.claude.com/docs/en/build-with-claude/fast-mode) in research preview for Claude Opus 4.6, providing significantly faster output token generation through the `speed` parameter. Fast mode is up to 2.5x as fast at premium pricing. Interested customers should join the [fast mode waitlist](https://claude.com/fast-mode).
521521 
522522### February 5, 2026
523523 
524* We’ve [launched Claude Opus 4.6](https://www.anthropic.com/news/claude-opus-4-6), our most intelligent model for complex agentic tasks and long-horizon work. Opus 4.6 recommends [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`thinking: {type: "adaptive"}`); manual thinking (`type: "enabled"` with `budget_tokens`) is deprecated. Opus 4.6 does not support prefilling assistant messages. Learn more in [What’s new in Claude 4.6](https://platform.claude.com/docs/en/about-claude/models/whats-new-claude-4-6).
524* We’ve [launched Claude Opus 4.6](https://www.anthropic.com/news/claude-opus-4-6), our most intelligent model for complex agentic tasks and long-horizon work. For Opus 4.6, we recommend [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`thinking: {type: "adaptive"}`); manual thinking (`type: "enabled"` with `budget_tokens`) is deprecated. Opus 4.6 does not support prefilling assistant messages. Learn more in [Claude Opus 4.6](https://platform.claude.com/docs/en/models/opus-4-6/overview).
525525* The [effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort) no longer requires a beta header and now supports Claude Opus 4.6. Effort replaces `budget_tokens` for controlling thinking depth on new models.
526526* We’ve launched the [compaction API](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold) in beta, providing server-side context summarization for effectively infinite conversations. Available on Opus 4.6.
527527* We’ve introduced [data residency controls](https://platform.claude.com/docs/en/manage-claude/data-residency), allowing you to specify where model inference runs with the `inference_geo` parameter. US-only inference is available at 1.1x pricing for models released after February 1, 2026.
from line 552
552552 
553553* We’ve [launched Claude Opus 4.5](https://www.anthropic.com/news/claude-opus-4-5), our most intelligent model combining maximum capability with practical performance. Ideal for complex specialized tasks, professional software engineering, and advanced agents. Features step-change improvements in vision, coding, and computer use at a more accessible price point than previous Opus models. Learn more in [Models overview](https://platform.claude.com/docs/en/models/overview).
554554* We’ve launched [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) in beta, allowing Claude to call tools from within code execution to reduce latency and token usage in multi-tool workflows.
555* We’ve launched the [tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) in beta, enabling Claude to dynamically discover and load tools on-demand from large tool catalogs.
555* We’ve launched the [tool search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) in beta, enabling Claude to dynamically discover and load tools on demand from large tool catalogs.
556556* We’ve launched the [effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort) in beta for Claude Opus 4.5, allowing you to control token usage by trading off between response thoroughness and efficiency.
557557* We’ve added [client-side compaction](https://platform.claude.com/docs/en/build-with-claude/context-editing#client-side-compaction-sdk) to our Python and TypeScript SDKs, automatically managing conversation context through summarization when using `tool_runner`.
558558 
from line 582
582582 
583583* We’ve [launched Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills) (`skills-2025-10-02` beta), a new way to extend Claude’s capabilities. Skills are organized folders of instructions, scripts, and resources that Claude loads dynamically to perform specialized tasks. The initial release includes:
584584 
585 * **Anthropic-managed Skills:** Pre-built Skills for working with PowerPoint (.pptx), Excel (.xlsx), Word (.docx), and PDF files
586 * **Custom Skills:** Upload your own Skills through the Skills API (`/v1/skills` endpoints) to package domain expertise and organizational workflows
587 * Skills require the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) to be enabled
588 * Learn more in [Agent Skills](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview) and [API reference](https://platform.claude.com/docs/en/api/skills/create)
585 * **Anthropic-managed Skills:** Prebuilt Skills for working with PowerPoint (.pptx), Excel (.xlsx), Word (.docx), and PDF files.
586 * **Custom Skills:** Upload your own Skills through the Skills API (`/v1/skills` endpoints) to package domain expertise and organizational workflows.
587 * Skills require the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) to be enabled.
588 * Learn more in [Agent Skills](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview) and the [Create Skill](https://platform.claude.com/docs/en/api/skills/create) API reference.
589589 
590590### October 15, 2025
591591 
from line 593
593593 
594594### September 29, 2025
595595 
596* We’ve launched [Claude Sonnet 4.5](https://www.anthropic.com/news/claude-sonnet-4-5), our best model for complex agents and coding, with the highest intelligence across most tasks. Learn more in the [models overview](https://platform.claude.com/docs/en/models/overview).
597* We’ve introduced [global endpoint pricing](https://platform.claude.com/docs/en/about-claude/pricing#cloud-platform-pricing) for Amazon Bedrock and Vertex AI. The Claude API (1P) pricing is unaffected.
598* We’ve introduced a new stop reason `model_context_window_exceeded` that allows you to request the maximum possible tokens without calculating input size. Learn more in [Handling stop reasons](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons).
596* We’ve launched [Claude Sonnet 4.5](https://www.anthropic.com/news/claude-sonnet-4-5), our best model for complex agents and coding, with the highest intelligence across most tasks. Learn more in [Models overview](https://platform.claude.com/docs/en/models/overview).
597* We’ve introduced [global endpoint pricing](https://platform.claude.com/docs/en/about-claude/pricing#cloud-platform-pricing) for Amazon Bedrock and Vertex AI. Claude API pricing is unaffected.
598* We’ve introduced a new stop reason `model_context_window_exceeded` that allows you to request the maximum possible tokens without calculating input size. Learn more in [Stop reasons and fallback](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons).
599599* We’ve launched the memory tool in beta, enabling Claude to store and consult information across conversations. Learn more in [Memory tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool).
600600* We’ve launched context editing in beta, providing strategies to automatically manage conversation context. The initial release supports clearing older tool results and calls when approaching token limits. Learn more in [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing).
601601 
from line 607
607607 
608608* We’ve unified our developer offerings under the Claude brand. You should see updated naming and URLs across our platform and documentation, but **our developer interfaces will remain the same**. Here are some notable changes:
609609 
610 * Claude Console ([console.anthropic.com](https://console.anthropic.com)) → Claude Console ([platform.claude.com](https://platform.claude.com)). The console will be available at both URLs until January 12, 2026. After that date, [console.anthropic.com](https://console.anthropic.com) will automatically redirect to [platform.claude.com](https://platform.claude.com).
611 * Anthropic Docs ([docs.anthropic.com](https://docs.anthropic.com)) → Claude Docs ([docs.claude.com](https://docs.claude.com))
612 * Anthropic Help Center ([support.anthropic.com](https://support.anthropic.com)) → Claude Help Center ([support.claude.com](https://support.claude.com))
610 * Anthropic Console ([console.anthropic.com](https://console.anthropic.com)) → Claude Console ([platform.claude.com](https://platform.claude.com)). The Claude Console will be available at both URLs until January 12, 2026. After that date, [console.anthropic.com](https://console.anthropic.com) will automatically redirect to [platform.claude.com](https://platform.claude.com).
611 * Anthropic Docs ([docs.anthropic.com](https://docs.anthropic.com)) → Claude Docs ([docs.claude.com](https://docs.claude.com)).
612 * Anthropic Help Center ([support.anthropic.com](https://support.anthropic.com)) → Claude Help Center ([support.claude.com](https://support.claude.com)).
613613 * API endpoints, headers, environment variables, and SDKs remain the same. Your existing integrations will continue working without any changes.
614614 
615615### September 10, 2025
616616 
617* We’ve launched the web fetch tool in beta, allowing Claude to retrieve full content from specified web pages and PDF documents. Learn more in [Web fetch tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool).
617* We’ve launched the web fetch tool in beta, allowing Claude to retrieve full content from specified webpages and PDF documents. Learn more in [Web fetch tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool).
618618* We’ve launched the [Claude Code Analytics API](https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api), enabling organizations to programmatically access daily aggregated usage metrics for Claude Code, including productivity metrics, tool usage statistics, and cost data.
619619 
620620### September 8, 2025
621621 
622* We launched a beta version of the [C# SDK](https://github.com/anthropics/anthropic-sdk-csharp).
622* We launched the [C# SDK](https://github.com/anthropics/anthropic-sdk-csharp) in beta.
623623 
624624### September 5, 2025
625625 
from line 631
631631 
632632### September 2, 2025
633633 
634* We’ve launched v2 of the [Code Execution Tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) in beta, replacing the original Python-only tool with Bash command execution and direct file manipulation capabilities, including writing code in other languages.
634* We’ve launched v2 of the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) in beta, replacing the original Python-only tool with Bash command execution and direct file manipulation capabilities, including writing code in other languages.
635635 
636636### August 27, 2025
637637 
638* We launched a beta version of the [PHP SDK](https://github.com/anthropics/anthropic-sdk-php).
638* We launched the [PHP SDK](https://github.com/anthropics/anthropic-sdk-php) in beta.
639639 
640640### August 26, 2025
641641 
from line 648
648648 
649649### August 18, 2025
650650 
651* We’ve released the [Usage & Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api), allowing administrators to programmatically monitor their organization’s usage and cost data.
651* We’ve released the [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api), allowing administrators to programmatically monitor their organization’s usage and cost data.
652652* We’ve added a new endpoint to the Admin API for retrieving organization information. For details, see the [Organization Info Admin API reference](https://platform.claude.com/docs/en/api/beta/organization/retrieve).
653653 
654654### August 13, 2025
from line 670
670670 
671671### August 5, 2025
672672 
673* We’ve launched [Claude Opus 4.1](https://www.anthropic.com/news/claude-opus-4-1), an incremental update to Claude Opus 4 with enhanced capabilities and performance improvements. Opus 4.1 does not allow both `temperature` and `top_p` parameters to be specified. Use only one. Learn more in [Models overview](https://platform.claude.com/docs/en/models/overview).
673* We’ve launched [Claude Opus 4.1](https://www.anthropic.com/news/claude-opus-4-1), an incremental update to Claude Opus 4 with enhanced capabilities and performance improvements. On Opus 4.1, you can specify `temperature` or `top_p`, but not both. Learn more in [Models overview](https://platform.claude.com/docs/en/models/overview).
674674 
675675### July 28, 2025
676676 
from line 702
702702 
703703### June 11, 2025
704704 
705* We’ve launched [fine-grained tool streaming](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming) in beta, a feature that enables Claude to stream tool use parameters without buffering / JSON validation. To enable fine-grained tool streaming, use the [beta header](https://platform.claude.com/docs/en/api/beta-headers) `fine-grained-tool-streaming-2025-05-14`.
705* We’ve launched [fine-grained tool streaming](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming) in beta, a feature that enables Claude to stream tool use parameters without buffering or JSON validation. To enable fine-grained tool streaming, use the [beta header](https://platform.claude.com/docs/en/api/beta-headers) `fine-grained-tool-streaming-2025-05-14`.
706706 
707707### May 22, 2025
708708 
from line 710
710710* The default behavior of [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) in Claude 4 models returns a summary of Claude’s full thinking process, with the full thinking encrypted and returned in the `signature` field of `thinking` block output.
711711* We’ve launched [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#interleaved-thinking) in beta, a feature that enables Claude to think in between tool calls. To enable interleaved thinking, use the [beta header](https://platform.claude.com/docs/en/api/beta-headers) `interleaved-thinking-2025-05-14`.
712712* We’ve launched the [Files API](https://platform.claude.com/docs/en/build-with-claude/files) in beta, enabling you to upload files and reference them in the Messages API and code execution tool.
713* We’ve launched the [Code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) in beta, a tool that enables Claude to execute Python code in a secure, sandboxed environment.
713* We’ve launched the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) in beta, a tool that enables Claude to run Python code in a secure, sandboxed environment.
714714* We’ve launched the [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) in beta, a feature that allows you to connect to remote MCP servers directly from the Messages API.
715715* To increase answer quality and decrease tool errors, we’ve changed the default value for the `top_p` [nucleus sampling](https://en.wikipedia.org/wiki/Top-p_sampling) parameter in the Messages API from 0.999 to 0.99 for all models. To revert this change, set `top_p` to 0.999. Additionally, when extended thinking is enabled, you can now set `top_p` to values between 0.95 and 1.
716716* Our [Go SDK](https://github.com/anthropics/anthropic-sdk-go) has moved from beta to its first stable release.
from line 726
726726 
727727### May 1, 2025
728728 
729* Cache control must now be specified directly in the parent `content` block of `tool_result` and `document.source`. For backwards compatibility, if cache control is detected on the last block in `tool_result.content` or `document.source.content`, it will be automatically applied to the parent block instead. Cache control on any other blocks within `tool_result.content` and `document.source.content` will result in a validation error.
729* You must now specify cache control directly in the parent `content` block of `tool_result` and `document.source`. For backward compatibility, if the API detects cache control on the last block in `tool_result.content` or `document.source.content`, it will automatically apply that cache control to the parent block instead. Cache control on any other blocks within `tool_result.content` and `document.source.content` will result in a validation error.
730730 
731731### April 9, 2025
732732 
733* We launched a beta version of the [Ruby SDK](https://github.com/anthropics/anthropic-sdk-ruby).
733* We launched the [Ruby SDK](https://github.com/anthropics/anthropic-sdk-ruby) in beta.
734734 
735735### March 31, 2025
736736 
from line 741
741741 
742742* We’ve added URL source blocks for images and PDFs in the Messages API. You can now reference images and PDFs directly through a URL instead of having to base64-encode them. Learn more in [Vision](https://platform.claude.com/docs/en/build-with-claude/vision) and [PDF support](https://platform.claude.com/docs/en/build-with-claude/pdf-support).
743743* We’ve added support for a `none` option to the `tool_choice` parameter in the Messages API that prevents Claude from calling any tools. Additionally, you’re no longer required to provide any `tools` when including `tool_use` and `tool_result` blocks.
744* We’ve launched an OpenAI-compatible API endpoint, allowing you to test Claude models by changing just your API key, base URL, and model name in existing OpenAI integrations. This compatibility layer supports core chat completions functionality. Learn more in [OpenAI SDK compatibility](https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/openai-sdk).
744* We’ve launched an OpenAI-compatible API endpoint, allowing you to test Claude models by changing only your API key, base URL, and model name in existing OpenAI integrations. This compatibility layer supports core chat completions functionality. Learn more in [OpenAI SDK compatibility](https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/openai-sdk).
745745 
746746### February 24, 2025
747747 
748748* We’ve launched [Claude Sonnet 3.7](https://www.anthropic.com/news/claude-3-7-sonnet), our most intelligent model yet. Claude Sonnet 3.7 can produce near-instant responses or show its extended thinking step-by-step. One model, two ways to think. Learn more about all Claude models in [Models overview](https://platform.claude.com/docs/en/models/overview).
749749 
750* We’ve added vision support to Claude Haiku 3.5, enabling the model to analyze and understand images.
750* We’ve added vision support to Claude Haiku 3.5, enabling the model to analyze images.
751751 
752752* We’ve released a token-efficient tool use implementation, improving overall performance when using tools with Claude. Learn more in [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
753753 
754754* We’ve changed the default temperature in the [Console](https://console.anthropic.com/workbench) for new prompts from 0 to 1 for consistency with the default temperature in the API. Existing saved prompts are unchanged.
755755 
756* We’ve released updated versions of our tools that decouple the text edit and bash tools from the computer use system prompt:
756* We’ve released updated versions of our tools that decouple the text editor and bash tools from the computer use system prompt:
757757 
758 * `bash_20250124`: Same functionality as previous version but is independent from computer use. Does not require a beta header.
759 * `text_editor_20250124`: Same functionality as previous version but is independent from computer use. Does not require a beta header.
760 * `computer_20250124`: Updated computer use tool with new command options including `hold_key`, `left_mouse_down`, `left_mouse_up`, `scroll`, `triple_click`, and `wait`. This tool requires the `computer-use-2025-01-24` anthropic-beta header. Learn more in [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
758 * `bash_20250124`: Same functionality as the previous version, but independent of computer use. Does not require a beta header.
759 * `text_editor_20250124`: Same functionality as the previous version, but independent of computer use. Does not require a beta header.
760 * `computer_20250124`: Updated computer use tool with new command options including `hold_key`, `left_mouse_down`, `left_mouse_up`, `scroll`, `triple_click`, and `wait`. This tool requires the `computer-use-2025-01-24` beta header.
761761 
762 Learn more in [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
763 
762764### February 10, 2025
763765 
764766* We’ve added the `anthropic-organization-id` response header to all API responses. This header provides the organization ID associated with the API key used in the request.
from line 771
769771 
770772### January 23, 2025
771773 
772* We’ve launched citations capability in the API, allowing Claude to provide source attribution for information. Learn more in [Citations](https://platform.claude.com/docs/en/build-with-claude/citations).
774* We’ve launched the citations capability in the API, allowing Claude to provide source attribution for information. Learn more in [Citations](https://platform.claude.com/docs/en/build-with-claude/citations).
773775* We’ve added support for plain text documents and custom content documents in the Messages API.
774776 
775777### January 21, 2025
from line 795
793795 
794796* The following features are now available in the Claude API without a beta header:
795797 
796 * [Models API](https://platform.claude.com/docs/en/api/models/list): Query available models, validate model IDs, and resolve [model aliases](https://platform.claude.com/docs/en/models/overview) to their canonical model IDs.
797 * [Message Batches API](https://platform.claude.com/docs/en/build-with-claude/batch-processing): Process large batches of messages asynchronously at 50% of the standard API cost.
798 * [Token counting API](https://platform.claude.com/docs/en/build-with-claude/token-counting): Calculate token counts for Messages before sending them to Claude.
799 * [Prompt Caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): Reduce costs by up to 90% and latency by up to 80% by caching and reusing prompt content.
798 * [Models API](https://platform.claude.com/docs/en/api/models/list): Query available models, validate model IDs, and resolve [model aliases](https://platform.claude.com/docs/en/about-claude/models/model-ids-and-versions) to their canonical model IDs.
799 * [Message Batches API](https://platform.claude.com/docs/en/build-with-claude/batch-processing): Process large batches of messages asynchronously at 50 percent of the standard API cost.
800 * [Token counting API](https://platform.claude.com/docs/en/build-with-claude/token-counting): Calculate token counts for messages before sending them to Claude.
801 * [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching): Reduce costs by up to 90 percent and latency by up to 80 percent by caching and reusing prompt content.
800802 * [PDF support](https://platform.claude.com/docs/en/build-with-claude/pdf-support): Process PDFs to analyze both text and visual content within documents.
801803 
802804* We also released new official SDKs:
from line 844
842844 
843845### October 8, 2024
844846 
845* The Message Batches API is now available in beta. Process large batches of queries asynchronously in the Claude API for 50% less cost. Read more in [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing).
847* The Message Batches API is now available in beta. Process large batches of queries asynchronously in the Claude API for 50 percent less cost. Read more in [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing).
846848* We’ve loosened restrictions on the ordering of `user`/`assistant` turns in our Messages API. Consecutive `user`/`assistant` messages will be combined into a single message instead of erroring, and we no longer require the first input message to be a `user` message.
847849* We’ve deprecated the Build and Scale plans in favor of a standard feature suite (formerly referred to as Build), along with additional features that are available through sales. Read more in our [API pricing information](https://claude.com/platform/api).
848850 
from line 866
864866 
865867### August 19, 2024
866868 
867* 8,192-token outputs on Claude Sonnet 3.5 are out of beta and no longer require the `max-tokens-3-5-sonnet-2024-07-15` header.
869* Outputs of 8,192 tokens on Claude Sonnet 3.5 are out of beta and no longer require the `max-tokens-3-5-sonnet-2024-07-15` header.
868870 
869871### August 14, 2024
870872 
871* [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) is now available as a beta feature in the Claude API. Cache and re-use prompts to reduce latency by up to 80% and costs by up to 90%.
873* [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) is now available as a beta feature in the Claude API. Cache and reuse prompts to reduce latency by up to 80 percent and costs by up to 90 percent.
872874 
873875### July 15, 2024
874876 

about-claude/api-credits-for-subscribers Changed · +1 / -1 lines

from line 50
5050| Where | Required role |
5151| ------------------------------- | ------------------------------------------------------------ |
5252| **Claude plan** | Max or Ultra: the subscriber<br />Team: Primary Owner, Owner |
53| **Claude Console organization** | Owner, Admin, or Billing |
53| **Claude Console organization** | Admin or Billing |
5454 
5555If you don’t have a Claude Console organization, create one in the Console at [platform.claude.com](https://platform.claude.com/) first, or create one during the claim flow.
5656 

agents-and-tools/mcp-tunnels/console Changed · +1 / -1 lines

from line 14
1414 
1515* **One or more MCP servers** running in your private network. The tunnel routes traffic to them; it does not host them. See [Remote MCP servers](https://platform.claude.com/docs/en/agents-and-tools/remote-mcp-servers) for examples you can deploy.
1616 
17* **A Console role with the Manage tunnels permission**, so you can create and archive tunnels, rotate the token, and manage certificates. Organization admins and owners have it by default; custom roles and per-account grants can also include it. Roles without it have read-only access to the **MCP tunnels** page and tunnel details.
17* **The admin role in your organization**, so you can create and archive tunnels, rotate the token, and manage certificates. With the developer role, you can view the **MCP tunnels** page and tunnel details, but not change them.
1818 
1919* **A way for your stack to authenticate to the Tunnels API.** Choose one:
2020 

agents-and-tools/remote-mcp-servers Changed · +1 / -1 lines

from line 26
2626 
2727## Remote MCP server examples
2828 
29<MCPServersTable platform="mcpConnector" />
29<MCPServersTable />
3030 
3131<Note>
3232 **Looking for more?** [Find hundreds more MCP servers on GitHub](https://github.com/modelcontextprotocol/servers).

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

from line 1757
17571757 // When handling Claude's coordinates, scale them back up
17581758 BiConsumer<Integer, Integer> executeClick =
17591759 (x, y) -> performClick(x / scale, y / scale);
1760 // ...
1760 // ...
17611761 }
17621762 ```
17631763 

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

from line 1595
15951595 func handleEditorTool(input map[string]any) string {
15961596 command, _ := input["command"].(string)
15971597 filePath, _ := input["path"].(string)
1598 // ...
1598 // ...
15991599 
16001600 switch command {
16011601 case "view":
from line 1739
17391739 result := handleEditorTool(input)
17401740 
17411741 toolResult := anthropic.NewToolResultBlock(block.ID, result, false)
1742 // ...
1742 // ...
17431743 }
17441744 }
17451745 ```

build-with-claude/fast-mode Changed · +1 / -1 lines

from line 364
364364 "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
365365 "type": "message",
366366 "role": "assistant",
367// ...
367 // ...
368368 "usage": {
369369 "input_tokens": 8,
370370 "output_tokens": 12,

build-with-claude/refusals-and-fallback Changed · +2 / -2 lines

from line 921
921921 
922922 ```go Go
923923 import (
924 // ...
924 // ...
925925 "github.com/anthropics/anthropic-sdk-go/v2/lib/betafallback"
926 // ...
926 // ...
927927 )
928928 
929929 func main() {

build-with-claude/skills-guide Changed · +1 / -1 lines

from line 2147
21472147 import com.anthropic.models.skills.Skill;
21482148 // ...
21492149 void main() throws Exception {
2150 // ...
2150 // ...
21512151 AnthropicClient client = AnthropicOkHttpClient.fromEnv();
21522152 
21532153 // Option 1: Using a zip file

cli-sdks-libraries/libraries/apple-foundation-models Changed · +1 / -1 lines

from line 146
146146 App Attest requires a physical device. The Simulator, and hardware without a Secure Enclave, cannot perform App Attest. Use `.apiKey` while iterating in the Simulator, and `.appAttest` when running on a device.
147147</Note>
148148 
149To set up App Attest, you need your Apple Developer Team ID and the admin, owner, or primary owner role in your Claude Console organization. Configure your Xcode project and register your app in the [Claude Console](https://platform.claude.com/):
149To set up App Attest, you need your Apple Developer Team ID and the admin role in your Claude Console organization. Configure your Xcode project and register your app in the [Claude Console](https://platform.claude.com/):
150150 
1511511. In Xcode, add the **App Attest** capability to your app target under **Signing & Capabilities**.
1521522. In the Claude Console, go to the [App integrations](https://platform.claude.com/settings/app-integrations) page (`platform.claude.com/settings/app-integrations`) and click **Create app integration**.
Feedback