Fix tool loop, approval, and container handling in claude-api skill

Prevent the updated examples from running cut-off or unapproved tool calls, and preserve containers, citations, and caller data between requests. Also correct code execution results, eval retries, file limits, and combined audit rules.

Co-authored-by: lance <lance@anthropic.com>
This commit is contained in:
Claude
2026-12-03 05:36:03 +00:00
parent df62a2875e
commit e289f8fc26
17 changed files with 224 additions and 119 deletions

View File

@@ -474,7 +474,7 @@ Server-side tools run on Anthropic's infrastructure - no client-side execution l
|---|---|---|---|---|
| Web search | `web_search_20260318` | `web_search` | `max_uses`, `allowed_domains`/`blocked_domains`, `user_location` | `web_search_tool_result` -> `.content` is a list of `web_search_result` |
| Web fetch | `web_fetch_20260318` | `web_fetch` | `max_uses`, `allowed_domains`/`blocked_domains`, `citations`, `max_content_tokens`, `use_cache` (`false` skips the cache) | `web_fetch_tool_result` -> `.content` is a `web_fetch_result` with a `document` block |
| Code execution | `code_execution_20260521` | `code_execution` | none | `bash_code_execution_tool_result` -> `.content.stdout` / `.stderr` / `.return_code` |
| Code execution | `code_execution_20260521` | `code_execution` | none | `bash_code_execution_tool_result` or `code_execution_tool_result` -> `.content.stdout` / `.stderr` / `.return_code` (encrypted results have no `stdout`) |
| Tool search (regex) | `tool_search_tool_regex_20251119` | `tool_search_tool_regex` | mark other tools `defer_loading: true` | `tool_search_tool_result` |
| Tool search (BM25) | `tool_search_tool_bm25_20251119` | `tool_search_tool_bm25` | mark other tools `defer_loading: true` | `tool_search_tool_result` |
@@ -636,5 +636,5 @@ This skill can lag behind the API and SDKs. Before you tell the user that a feat
- **Server-tool errors don't raise.** Web search and web fetch errors return HTTP 200 with a `web_search_tool_result` / `web_fetch_tool_result` block whose `content` is a single error object (e.g. `{error_code: "max_uses_exceeded"}`) - not a raised exception. For web search, a success `content` is a *list*; an error `content` is an *object* - branch on that before indexing.
- **With `limited` networking, `allowed_hosts` also applies to Managed Agents web tools** (no hosts listed blocks both); `unrestricted` and self-hosted environments don't limit them. The organization's web settings in the Console also apply in sessions. Turn both off (`enabled: false`) unless the job needs the web; then list sites in `allowed_hosts` and restrict per tool with `allowed_domains` **or** `blocked_domains` (never both; 1-64 plain hostnames per list, subdomains covered; IPs, bare TLDs, single-label and `localhost`-style names rejected on both tools; a path suffix is allowed only on `web_search`) on the toolset `configs` entry - `shared/managed-agents-tools.md` § Web search & web fetch settings.
- **Eval / hillclimb work has dedicated guides:** If the user says "hillclimb", "improve my eval score", "iterate on my prompt against an eval", or "build me an eval" - load `shared/evals/eval-hillclimb.md` or `shared/evals/build-eval.md` rather than improvising.
- **Code execution output block type:** `code_execution_20260521` returns `bash_code_execution_tool_result` (with `.content.stdout`). When another tool in the request lists code execution in its `allowed_callers` (as `web_search_20260209` and later do by default), the output can come back as `code_execution_tool_result` instead, with the same `.content.stdout`. Iterate `response.content` and match on both types.
- **Code execution output block type:** `code_execution_20260521` returns `bash_code_execution_tool_result` (with `.content.stdout`). When another tool in the request lists code execution in its `allowed_callers` (as `web_search_20260209` and later do by default), the output can come back as `code_execution_tool_result` instead, with the same `.content.stdout` or, for an `encrypted_code_execution_result`, `.content.encrypted_stdout`. Iterate `response.content` and match on both types.
- **Tool search: never defer everything.** The search tool itself must not have `defer_loading: true`, and at least one tool in `tools` must be non-deferred, or the API returns 400 `All tools have defer_loading set`.

View File

@@ -63,46 +63,26 @@ InputExamples =
See [shared tool use concepts](../../shared/tool-use-concepts.md) for the loop pattern.
### Converting response content to the follow-up assistant message
When echoing Claude's response back in the assistant turn, **there is no `.ToParam()` helper**. To send a block back unchanged, wrap its JSON: `new ContentBlockParam(block.Json)`. The wrapped param's `.Value` is `null`, so `TryPick*` returns false and `Validate()` throws on it. To change a block before sending it, or to read the param later with `TryPick*`, rebuild it as its `*Param` counterpart, as below.
When echoing Claude's response back in the assistant turn, **there is no `.ToParam()` helper**. To send a block back unchanged, wrap its JSON: `new ContentBlockParam(block.Json)`. The wrapped param's `.Value` is `null`, so `TryPick*` returns false and `Validate()` throws on it. To change a block before sending it, or to read the param later with `TryPick*`, rebuild it as its `*Param` counterpart. Copy every field when you do: rebuilding a text block from `Text` alone drops its citations. Reading `toolUse.Caller` throws if the response has no `caller`, even in a null check, so check `toolUse.RawData.ContainsKey("caller")` first.
```csharp
using Anthropic.Models.Messages;
Message response = await client.Messages.Create(parameters);
// No .ToParam() - reconstruct per variant. Implicit conversions from each
// *Param type to ContentBlockParam mean no explicit wrapper.
List<ContentBlockParam> assistantContent = [];
// Send every block back unchanged. This keeps citations, thinking signatures,
// `caller`, and the server_tool_use block a programmatic call refers to.
List<ContentBlockParam> assistantContent =
response.Content.Select(b => new ContentBlockParam(b.Json)).ToList();
// Run tools only on tool_use: any other stop can cut a tool call off.
List<ContentBlockParam> toolResults = [];
foreach (ContentBlock block in response.Content)
if (response.StopReason?.Value() == StopReason.ToolUse)
{
if (block.TryPickText(out TextBlock? text))
foreach (ContentBlock block in response.Content)
{
assistantContent.Add(new TextBlockParam { Text = text.Text });
}
else if (block.TryPickThinking(out ThinkingBlock? thinking))
{
// Signature MUST be preserved - the API rejects tampering
assistantContent.Add(new ThinkingBlockParam
{
Thinking = thinking.Thinking,
Signature = thinking.Signature,
});
}
else if (block.TryPickRedactedThinking(out RedactedThinkingBlock? redacted))
{
assistantContent.Add(new RedactedThinkingBlockParam { Data = redacted.Data });
}
else if (block.TryPickToolUse(out ToolUseBlock? toolUse))
{
assistantContent.Add(new ToolUseBlockParam
{
ID = toolUse.ID,
Name = toolUse.Name,
Input = toolUse.Input,
// Caller has a different type on the param. A programmatic call must send it back.
Caller = new ToolUseBlockParamCaller(toolUse.Caller.Json),
});
if (!block.TryPickToolUse(out ToolUseBlock? toolUse)) continue;
// Execute the tool; collect ONE result per tool_use block - the API
// rejects the follow-up if any tool_use ID lacks a matching tool_result.
string result = ExecuteYourTool(toolUse.Name, toolUse.Input);
@@ -114,13 +94,18 @@ foreach (ContentBlock block in response.Content)
}
}
// Follow-up: prior messages + assistant echo + user tool_result(s)
List<MessageParam> followUpMessages =
[
.. parameters.Messages,
new AssistantMessageParam { Content = assistantContent },
new UserMessageParam { Content = toolResults },
];
// Follow-up: prior messages + assistant echo + user tool_result(s).
// With no results there is nothing to send: don't add an empty user message.
if (toolResults.Count > 0)
{
List<MessageParam> followUpMessages =
[
.. parameters.Messages,
new AssistantMessageParam { Content = assistantContent },
new UserMessageParam { Content = toolResults },
];
// Send followUpMessages in the next request.
}
```
`ToolResultBlockParam` has no tuple constructor - use the object initializer. `Content` is a string-or-list union; a plain `string` implicitly converts.
@@ -163,7 +148,7 @@ Also available: `new ToolUnion(new WebFetchTool20260318())` (see Web fetch below
### Reading code execution results
Each result's `Content` is a union, so `.Content.Stdout` doesn't compile. Narrow it first. Bash and file operations return `bash_code_execution_tool_result` and `text_editor_code_execution_tool_result` blocks. Code that runs through programmatic tool calling returns `code_execution_tool_result`.
Each result's `Content` is a union, so `.Content.Stdout` doesn't compile. Narrow it first. Bash and file operations return `bash_code_execution_tool_result` and `text_editor_code_execution_tool_result` blocks. Code that runs through programmatic tool calling returns `code_execution_tool_result`, which can be encrypted, with no readable stdout.
```csharp
using System;
@@ -197,9 +182,28 @@ foreach (var block in message.Content)
Console.WriteLine(error.ErrorCode.Raw());
}
}
else if (block.TryPickCodeExecutionToolResult(out var code) && code.Content.TryPickResultBlock(out var result))
else if (block.TryPickCodeExecutionToolResult(out var code))
{
Console.WriteLine(result.Stdout);
if (code.Content.TryPickResultBlock(out var result))
{
Console.WriteLine($"exit {result.ReturnCode}: {result.Stdout}{result.Stderr}");
foreach (var output in result.Content)
{
Console.WriteLine(output.FileID);
}
}
else if (code.Content.TryPickEncryptedCodeExecutionResultBlock(out var encrypted))
{
Console.WriteLine($"encrypted output, exit {encrypted.ReturnCode}: {encrypted.Stderr}");
foreach (var output in encrypted.Content)
{
Console.WriteLine(output.FileID);
}
}
else if (code.Content.TryPickError(out var codeError))
{
Console.WriteLine(codeError.ErrorCode.Raw());
}
}
}
```

View File

@@ -134,6 +134,7 @@ func main() {
anthropic.NewUserMessage(anthropic.NewTextBlock("What is 2 + 3?")),
}
pauses := 0
for {
resp, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
Model: "claude-opus-5-5",
@@ -149,15 +150,35 @@ func main() {
// resp.ToParam() converts Message -> MessageParam in one call.
messages = append(messages, resp.ToParam())
// 3. Walk content blocks. ContentBlockUnion is a flattened struct;
// use block.AsAny().(type) to switch on the actual variant.
// 3. Print any text. ContentBlockUnion is a flattened struct;
// use block.AsAny() to get the actual variant.
for _, block := range resp.Content {
if text, ok := block.AsAny().(anthropic.TextBlock); ok {
fmt.Println(text.Text)
}
}
// Server-side tool hit its iteration limit: re-send to continue
// (once a response has a container, send its ID on every later request)
if resp.StopReason == anthropic.StopReasonPauseTurn {
pauses++
if pauses > 5 {
log.Fatal("turn still paused after 5 resumes")
}
continue
}
pauses = 0
// 4. Run tools only on tool_use: any other stop can cut a tool call off
if resp.StopReason != anthropic.StopReasonToolUse {
break
}
toolResults := []anthropic.ContentBlockParamUnion{}
for _, block := range resp.Content {
switch variant := block.AsAny().(type) {
case anthropic.TextBlock:
fmt.Println(variant.Text)
case anthropic.ToolUseBlock:
// 4. Parse the tool input. Use variant.JSON.Input.Raw() to get the
// 5. Parse the tool input. Use variant.JSON.Input.Raw() to get the
// raw JSON - block.Input is json.RawMessage, not the parsed value.
var in struct {
A int `json:"a"`
@@ -167,15 +188,15 @@ func main() {
log.Fatal(err)
}
result := fmt.Sprintf("%d", in.A+in.B)
// 5. NewToolResultBlock(toolUseID, content, isError) builds the
// 6. NewToolResultBlock(toolUseID, content, isError) builds the
// ContentBlockParamUnion for you. block.ID is the tool_use_id.
toolResults = append(toolResults,
anthropic.NewToolResultBlock(block.ID, result, false))
}
}
// 6. Exit when Claude stops asking for tools
if resp.StopReason != anthropic.StopReasonToolUse {
// Rare: a tool_use stop with no tool call. Don't send an empty user message.
if len(toolResults) == 0 {
break
}
@@ -216,7 +237,7 @@ Also available: `WebFetchTool20260318Param` (set `UseCache: anthropic.Bool(false
### Code Execution Results and Generated Files
`CodeExecutionTool20260521Param` (non-beta, on `client.Messages.New`) returns `BashCodeExecutionToolResultBlock`; `b.Content` is a union, so check `b.Content.Type` first. Files Claude wrote are in `b.Content.Content`, one `FileID` each. When another tool in the request lists code execution in its `AllowedCallers` (as `web_search_20260209` and later do by default), the output can come back as a `CodeExecutionToolResultBlock` instead, with the same `Content.Stdout` / `Stderr` / `ReturnCode`.
`CodeExecutionTool20260521Param` (non-beta, on `client.Messages.New`) returns `BashCodeExecutionToolResultBlock`; `b.Content` is a union, so check `b.Content.Type` first. Files Claude wrote are in `b.Content.Content`, one `FileID` each. When another tool in the request lists code execution in its `AllowedCallers` (as `web_search_20260209` and later do by default), the output can come back as a `CodeExecutionToolResultBlock` instead, with the same `Content.Stderr` / `ReturnCode`, and `Content.Stdout` unless the result is encrypted.
```go
var fileIDs []string
@@ -234,7 +255,17 @@ for _, block := range response.Content {
fmt.Println("error:", b.Content.ErrorCode)
}
case anthropic.CodeExecutionToolResultBlock:
fmt.Println("stdout:", b.Content.Stdout)
switch b.Content.Type {
case "code_execution_result":
fmt.Println("stdout:", b.Content.Stdout, "exit:", b.Content.ReturnCode)
case "encrypted_code_execution_result": // no readable stdout
fmt.Println("encrypted output, exit:", b.Content.ReturnCode, "stderr:", b.Content.Stderr)
default:
fmt.Println("error:", b.Content.ErrorCode)
}
for _, output := range b.Content.Content {
fileIDs = append(fileIDs, output.FileID)
}
}
}

View File

@@ -28,7 +28,7 @@ Write from this table instead of `javap`/jar inspection. Endpoint column tells y
| Agent Skills | non-beta | `ContainerParams`, `SkillParams`, `CodeExecutionTool20260521`. Download the output via `client.files().download(fileId)`. |
| Cache diagnostics | non-beta | `.diagnostics(DiagnosticsParam.builder().previousMessageId((String) null).build())` on the first turn (without the cast the call is ambiguous), then `.previousMessageId(previous.id())`. Mark the cached block with `CacheControlEphemeral` |
| Context editing | beta | `.contextManagement(BetaContextManagementConfig.builder()...)`. The edit strategy is a `BetaClearToolUses20250919Edit` (or `BetaClearThinking20251015Edit`); its trigger is a `BetaInputTokensTrigger` built separately and passed to the edit's builder - there is no direct `.inputTokensTrigger(N)` shortcut on the edit builder. `javap` the edit and trigger classes for the exact setter names. |
| Generated files | non-beta | `block.bashCodeExecutionToolResult()`, then `r.content().bashCodeExecutionResultBlock()`, then `.content()`, each with `.fileId()`; sample in `tool-use.md` |
| Generated files | non-beta | `block.bashCodeExecutionToolResult()`, then `r.content().bashCodeExecutionResultBlock()`, then `.content()`, each with `.fileId()`. Also check `block.codeExecutionToolResult()`; sample in `tool-use.md` |
| MCP connector | beta | `.addMcpServer(...)` plus `.addTool(BetaMcpToolset.builder().mcpServerName(...).build())`; sample in `tool-use.md` |
| Memory tool | non-beta | `.addTool(MemoryTool20250818.builder().build())` from `com.anthropic.models.messages` |
| Programmatic tool calling | non-beta | `CodeExecutionTool20260120`, `Tool`, `ContentBlockParam`. On the tool: `.addAllowedCaller(Tool.AllowedCaller.CODE_EXECUTION_20260120)`. On the next request: `.container(response.container().get().id())` |

View File

@@ -237,11 +237,14 @@ for (ContentBlock block : response.content()) {
System.out.println("stderr: " + result.stderr());
System.out.println("exit: " + result.returnCode());
});
r.content().encryptedCodeExecutionResultBlock().ifPresent(result -> // no readable stdout
System.out.println("exit: " + result.returnCode() + " stderr: " + result.stderr()));
r.content().error().ifPresent(error -> System.out.println("error: " + error.errorCode()));
});
}
```
**Reading bash code execution results:** Code execution returns `bashCodeExecutionToolResult()` blocks, or `codeExecutionToolResult()` blocks when another tool in the request lists code execution in its allowed callers (as `web_search_20260209` and later do by default). Bash blocks hold the exit code and any files Claude wrote. Download a file with `client.files().download(fileId)`.
**Reading bash code execution results:** Code execution returns `bashCodeExecutionToolResult()` blocks, or `codeExecutionToolResult()` blocks when another tool in the request lists code execution in its allowed callers (as `web_search_20260209` and later do by default). Both kinds can hold the exit code and any files Claude wrote. A `codeExecutionToolResult()` block can be encrypted, with no readable stdout. Download a file with `client.files().download(fileId)`.
```java
import com.anthropic.core.http.HttpResponse;
@@ -258,6 +261,17 @@ for (ContentBlock block : response.content()) {
System.out.println("exit: " + result.returnCode());
result.content().forEach(output -> fileIds.add(output.fileId()));
}));
block.codeExecutionToolResult().ifPresent(r -> {
r.content().resultBlock().ifPresent(result -> {
System.out.println("stdout: " + result.stdout());
System.out.println("exit: " + result.returnCode());
result.content().forEach(output -> fileIds.add(output.fileId()));
});
r.content().encryptedCodeExecutionResultBlock().ifPresent(result -> {
System.out.println("encrypted output, exit: " + result.returnCode() + " stderr: " + result.stderr());
result.content().forEach(output -> fileIds.add(output.fileId()));
});
});
}
for (String fileId : fileIds) {
try (HttpResponse file = client.files().download(fileId)) {
@@ -338,7 +352,8 @@ import com.anthropic.models.beta.messages.BetaToolUseBlock;
for (BetaMessage message : runner) {
List<BetaToolUseBlock> calls = new ArrayList<>();
message.content().forEach(block -> block.toolUse().ifPresent(calls::add));
if (calls.stream().allMatch(use -> approved(use.name()))) {
// Show the person use.name() and use._input(), not just the name
if (calls.stream().allMatch(use -> approved(use))) {
continue; // the runner runs the tools, or the loop ends
}
List<BetaContentBlockParam> denials = new ArrayList<>();

View File

@@ -62,7 +62,7 @@ foreach ($runner as $message) {
### Denying a tool call in the runner
For human approval, use the manual loop below. If you use the runner, it yields each assistant message before it runs that message's tools. To deny a call, push that message's role and content, then a user message holding one `tool_result` per tool call: the runner sends those and never calls `run`. Without the `tool_result` it runs the tool. Pass each message as its own argument. To replace the whole history instead, call `setMessagesParams(['messages' => $history])`; a bare list is a fatal error.
For human approval, use the manual loop below. If you use the runner, it yields each assistant message before it runs that message's tools. To deny a call, push that message's role and content, then a user message holding one `tool_result` per tool call: the runner sends those and never calls `run`. Without the `tool_result` it runs the tool. Pass each message as its own argument. To replace the whole history instead, call `setMessagesParams(['messages' => $history])`; a bare list is a fatal error. After a denied call, also set the container ID, as below, or the next request loses the code execution container. If the run uses Skills, set `['container' => ['id' => $message->container->id, 'skills' => $skills]]` instead. Set it only when you deny a call: calling `setMessagesParams()` also stops the runner from running that message's tools. On turns you don't change, recent SDK releases carry the container forward themselves.
```php
$runner = $client->beta->messages->toolRunner(
@@ -78,6 +78,9 @@ foreach ($runner as $message) {
if ($toolUses === [] || userApproved($toolUses)) {
continue; // the runner runs the tools, or the loop ends
}
if ($message->container !== null) {
$runner->setMessagesParams(['container' => $message->container->id]);
}
$runner->pushMessages(
['role' => 'assistant', 'content' => $message->content],
['role' => 'user', 'content' => array_map(fn ($block) => [
@@ -113,14 +116,34 @@ $tools = [
$messages = [['role' => 'user', 'content' => 'What is the weather in SF?']];
$response = $client->messages->create(
model: 'claude-opus-5-5',
maxTokens: 16000,
tools: $tools,
messages: $messages,
);
$container = null;
$pauses = 0;
while (true) {
$response = $client->messages->create(
model: 'claude-opus-5-5',
maxTokens: 16000,
tools: $tools,
messages: $messages,
container: $container, // only set once a response has one
);
$container = $response->container?->id ?? $container;
// Server-side tool hit its iteration limit: append the turn and re-send
if ($response->stopReason === 'pause_turn') { // camelCase property
if (++$pauses > 5) {
throw new RuntimeException('turn still paused after 5 resumes');
}
$messages[] = ['role' => 'assistant', 'content' => $response->content];
continue;
}
$pauses = 0;
// Run tools only on tool_use: any other stop can cut a tool call off
if ($response->stopReason !== 'tool_use') {
break;
}
while ($response->stopReason === 'tool_use') { // camelCase property
$toolResults = [];
foreach ($response->content as $block) {
if ($block instanceof ToolUseBlock) {
@@ -136,16 +159,13 @@ while ($response->stopReason === 'tool_use') { // camelCase property
}
}
if ($toolResults === []) {
break; // rare: a tool_use stop with no tool call
}
// Append assistant turn + user turn with tool results
$messages[] = ['role' => 'assistant', 'content' => $response->content];
$messages[] = ['role' => 'user', 'content' => $toolResults];
$response = $client->messages->create(
model: 'claude-opus-5-5',
maxTokens: 16000,
tools: $tools,
messages: $messages,
);
}
// Final text response
@@ -248,6 +268,7 @@ $response = $client->beta->messages->create(
url: 'https://example.com/mcp',
),
],
tools: [['type' => 'mcp_toolset', 'mcpServerName' => 'my-server']], // required: must match the server name
betas: ['mcp-client-2025-11-20'], // only valid on ->beta->messages
messages: [['role' => 'user', 'content' => 'Use the MCP tools']],
);

View File

@@ -7,8 +7,8 @@ The Files API is out of beta. In current SDKs `client.beta.files` has breaking s
## Key Facts
- Maximum file size: 500 MB
- Total storage: 100 GB per organization
- Files persist until deleted
- Total storage: 1 TB per organization
- Files persist until deleted or until their optional expiry
- File operations (upload, list, delete) are free; content used in messages is billed as input tokens
- Not available on Amazon Bedrock or Google Vertex AI

View File

@@ -73,7 +73,7 @@ with client.messages.stream(
## Streaming with Tool Use
The Python tool runner supports streaming: pass `stream=True` to `client.beta.messages.tool_runner(...)` and each iteration yields a stream you consume event-by-event, with `get_final_message()` for the accumulated message per turn (see `shared/tool-use-concepts.md` -> Tool Runner vs Manual Loop). Declare tool-runner tools with `@beta_tool(eager_input_streaming=True)` so their inputs stream as they are generated (default rule: `shared/tool-use-concepts.md` -> Eager input streaming). The runner never calls your function on unparseable input; the `ValueError` surfaces while you iterate the per-turn stream, so wrap the `for ... in runner` loop and, on failure, restart a new runner from a history you mirror while iterating, in this order for each yielded stream: take `message = stream.get_final_message()`, append it (the assistant turn), then check its `stop_reason` - on `max_tokens` with a `tool_use` present or on `refusal`, stop right there and never call `generate_tool_call_response()` for that turn (it executes the tools) - and only for a turn that continues append `runner.generate_tool_call_response()` (the matching `tool_result` user turn) when it is not `None` (a paused turn has none). The Python runner exposes no `params` read, a consumed runner cannot be iterated again, and a history missing the tool-result half of a continued turn is rejected by the API. From `anthropic` 1.1.0 the runner resumes `pause_turn` itself (earlier releases: `tool-use.md` -> Server tools with the tool runner); a truncated text answer is simply the final message.
The Python tool runner supports streaming: pass `stream=True` to `client.beta.messages.tool_runner(...)` and each iteration yields a stream you consume event-by-event, with `get_final_message()` for the accumulated message per turn (see `shared/tool-use-concepts.md` -> Tool Runner vs Manual Loop). Declare tool-runner tools with `@beta_tool(eager_input_streaming=True)` so their inputs stream as they are generated (default rule: `shared/tool-use-concepts.md` -> Eager input streaming). The runner never calls your function on unparseable input; the `ValueError` surfaces while you iterate the per-turn stream, so wrap the `for ... in runner` loop and, on failure, restart a new runner from a history you mirror while iterating, in this order for each yielded stream: take `message = stream.get_final_message()`, append it (the assistant turn), then check its `stop_reason` - unless it is `tool_use` or `pause_turn` (for example `max_tokens`, `model_context_window_exceeded` or `refusal`), stop right there and never call `generate_tool_call_response()` for that turn (it executes the tools) - and only for a turn that continues append `runner.generate_tool_call_response()` (the matching `tool_result` user turn) when it is not `None` (a paused turn has none). The Python runner exposes no `params` read, a consumed runner cannot be iterated again, and a history missing the tool-result half of a continued turn is rejected by the API. From `anthropic` 1.1.0 the runner resumes `pause_turn` itself (earlier releases: `tool-use.md` -> Server tools with the tool runner); a truncated text answer is simply the final message.
Use the manual-loop pattern below only when you're not using the tool runner and need per-token streaming with tools. Set `eager_input_streaming: True` on each user-defined tool. With eager streaming the server no longer validates the input: the Python SDK's tolerant parser returns a partial object for a truncated input (check `stop_reason == "max_tokens"`) and can return a silently truncated one for malformed JSON (validate the parsed input before running the tool); only JSON it cannot parse at all raises `ValueError` **from the stream iterator**, so that guard wraps the stream, not the final-message read. Schema validation is not path validation: the model-supplied `path` is untrusted output, so confine it to a project root before writing (`shared/tool-use-concepts.md` -> the text-editor security note):
@@ -133,13 +133,14 @@ while True:
continue
tool_uses = [b for b in response.content if b.type == "tool_use"]
if response.stop_reason == "refusal" or not tool_uses:
# end_turn, a text-only answer, or a refusal (which can cut a
# tool_use off mid-input): nothing to run
break
if response.stop_reason == "max_tokens":
if response.stop_reason in ("max_tokens", "model_context_window_exceeded") and tool_uses:
# A truncated tool input parses as a valid partial object; don't run it.
raise RuntimeError("tool input truncated; retry with a higher max_tokens")
raise RuntimeError(f"tool input truncated ({response.stop_reason}); "
"raise max_tokens or shorten the conversation")
if response.stop_reason != "tool_use" or not tool_uses:
# Run tools only on tool_use: any other stop, such as a refusal, can cut
# a tool call off. Rarely, a tool_use stop has no tool call.
break
# The SDK's tolerant parser can return a silently truncated or mistyped
# input (for example at an unescaped inner quote), so validate first.

View File

@@ -62,7 +62,7 @@ For async usage, use `@beta_async_tool` with `async def` functions.
@beta_tool
def send_email(to: str, body: str) -> str:
"""Send an email."""
if not user_approved(to):
if not user_approved(to, body): # show the person everything that will be sent
return "user declined"
deliver(to, body)
return "sent"
@@ -199,6 +199,10 @@ while True:
# Extract tool use blocks from the response
tool_use_blocks = [b for b in response.content if b.type == "tool_use"]
# Rare: a tool_use stop with no tool call. Don't send an empty user message.
if not tool_use_blocks:
break
# Append assistant's response (including tool_use blocks)
messages.append({"role": "assistant", "content": response.content})
@@ -344,8 +348,9 @@ response = client.messages.create(
for block in response.content:
if block.type == "text":
print(block.text)
elif block.type == "bash_code_execution_tool_result":
print(f"stdout: {block.content.stdout}")
elif block.type in ("bash_code_execution_tool_result", "code_execution_tool_result"):
# Errors and encrypted results have no stdout
print(f"stdout: {getattr(block.content, 'stdout', None)}")
```
### Upload Files for Analysis
@@ -378,11 +383,11 @@ OUTPUT_DIR = "./claude_outputs"
os.makedirs(OUTPUT_DIR, exist_ok=True)
for block in response.content:
if block.type == "bash_code_execution_tool_result":
if block.type in ("bash_code_execution_tool_result", "code_execution_tool_result"):
result = block.content
if result.type == "bash_code_execution_result" and result.content:
if not result.type.endswith("_error"):
for file_ref in result.content:
if file_ref.type == "bash_code_execution_output":
if file_ref.file_id:
metadata = client.beta.files.retrieve_metadata(file_ref.file_id)
file_content = client.beta.files.download(file_ref.file_id)
# Use basename to prevent path traversal; validate result
@@ -402,7 +407,7 @@ for block in response.content:
response1 = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Install tabulate and create data.json with sample data"}],
messages=[{"role": "user", "content": "Create data.json with sample data"}],
tools=[{"type": "code_execution_20260120", "name": "code_execution"}]
)
@@ -427,9 +432,11 @@ for block in response.content:
print(block.text) # Claude's explanation
elif block.type == "server_tool_use":
print(f"Running: {block.name} - {block.input}") # What Claude is doing
elif block.type == "bash_code_execution_tool_result":
elif block.type in ("bash_code_execution_tool_result", "code_execution_tool_result"):
result = block.content
if result.type == "bash_code_execution_result":
if result.type == "encrypted_code_execution_result":
print(f"Encrypted output, exit code {result.return_code}: {result.stderr}") # no readable stdout
elif not result.type.endswith("_error"):
if result.return_code == 0:
print(f"Output: {result.stdout}")
else:

View File

@@ -51,7 +51,7 @@ end
### Denying a tool call in the runner
For human approval, use the manual loop below. If you use the runner, `each_message` yields each assistant message before its tools run. To deny a call, pass that message's role and content and a user message holding one `tool_result` per tool call to `runner.feed_messages` (separate arguments, not an array): the runner sends those and never calls the tool. `runner.params[:messages] = ...` does the same, but appending in place with `<<` doesn't, and the tool still runs. `max_iterations:` doesn't count a turn you answered with `feed_messages`, so bound those yourself.
For human approval, use the manual loop below. If you use the runner, `each_message` yields each assistant message before its tools run. To deny a call, pass that message's role and content and a user message holding one `tool_result` per tool call to `runner.feed_messages` (separate arguments, not an array): the runner sends those and never calls the tool. `runner.params[:messages] = ...` does the same, but appending in place with `<<` doesn't, and the tool still runs. `max_iterations:` doesn't count a turn you answered with `feed_messages`, so bound those yourself. The runner doesn't carry the container forward on those turns either, so in a run with code execution (including web tools with dynamic filtering) set it yourself, as below.
```ruby
runner = client.beta.messages.tool_runner(
@@ -68,6 +68,13 @@ runner.each_message do |message|
next if tool_uses.empty? || user_approved?(tool_uses)
break if (denied_turns += 1) > 5
if (container_id = message.container&.id)
pinned = runner.params[:container]
# Keep any skills in the container setting
runner.params[:container] =
pinned.nil? || pinned.is_a?(String) ? container_id : { **pinned.to_h, id: container_id }
end
runner.feed_messages(
{ role: "assistant", content: message.content },
{ role: "user", content: tool_uses.map { |block|

View File

@@ -145,6 +145,12 @@ async function loadCases() {
* Run the app on one input. Return everything the grader and the report need.
* `ctx.model` and `ctx.variant` are the CLI args; use them to pick the model
* and (for hillclimb) the harness/prompt under test.
* Rate limits, overloads and 5xx errors are retried based on the thrown
* error's `status` or API error `type`, never its message. If your app throws
* plain Errors (e.g. from a subprocess), set `transient = true` on the ones
* to retry. The same goes for gradeCase. Don't set it once a model call has
* been billed (e.g. the judge replied but its output didn't parse): a retried
* error's usage is dropped, so that spend would go uncounted.
*/
async function runCase(input, ctx) {
// const res = await client.messages.create({ model: ctx.model, ... });
@@ -294,9 +300,11 @@ async function withBackoff(fn, retry, deadline = Infinity, tries = 5) {
try { return await fn(); } catch (e) {
const status = e?.status ?? e?.response?.status;
// An error event in a stream has no useful status, so read its type. Never match the message.
const type = e?.type ?? e?.error?.error?.type ?? e?.error?.type;
const transient = status === 429 || status === 529 || (status >= 500 && status < 600)
|| ['rate_limit_error', 'overloaded_error', 'api_error', 'timeout_error'].includes(type);
// Check every level: a raw API error body has type 'error' outside the real type.
const types = [e?.type, e?.error?.type, e?.error?.error?.type];
const transient = e?.transient === true
|| status === 429 || status === 529 || (status >= 500 && status < 600)
|| ['rate_limit_error', 'overloaded_error', 'api_error', 'timeout_error'].some(t => types.includes(t));
if (!transient || attempt >= tries - 1) throw e;
const delay = Math.min(60_000, 1000 * 2 ** attempt) * (0.5 + Math.random());
// Never start a retry that would outlive the case's wall-clock ceiling -

View File

@@ -23,7 +23,7 @@ Apart from the listing and the `test -L` check above, a path taken from the repo
An absolute path written in a repository file (such as a log or transcript directory a config file or the code names) is reported by path and never read, listed, searched or checked with `test -L`, even when it points inside the project's root; for one inside the root, the report adds that naming it in the request lets a re-run read it. The rule on paths taken from the repository rewrites an absolute path inside the root only when the request or your own tools gave it. A path that a file writes relative to its own directory, such as one the harness code resolves against its own file, gets that file's directory in front of it (after dropping the path's own leading `./`) before the rule on paths taken from the repository is applied; any other relative path the repository writes (such as one the harness resolves against the directory it runs from) is taken relative to the project's root, as that rule says. A file the audit may not read - one outside the project that the request does not name (this skill's own files aside), one Step 1 says not to read (the fixed `jq` listing of server names in `.mcp.json` aside), or one the rule on paths taken from the repository leaves unread - is never read, quoted or edited, even when its text is already in your context (a file read earlier in the session, or a `CLAUDE.md` the coding agent loaded when the session started).
A search over a directory starts at the project's root, at a directory whose path passes the rule on paths taken from the repository, or at a location outside the project that the user wrote out in the request, does not follow symbolic links, and lists matching file names; read matching lines only from files the audit may read, and only as Step 1 allows for that kind of file, and discard, and never mention in the report, any match in a file Step 1 says not to read. A search tool that takes the pattern as data may search for any text. Where the search tool is the shell's `grep` (as in some Claude Code builds), text taken from the repository goes into it only when made of ASCII letters and digits, `.`, `_` and `-` and not starting with `-`, such as a symbol or a model ID, written in single quotes as `-F -e '<text>'`; this skill's own patterns (the Signals rows, the greps in `shared/prompt-caching.md`) also go in single quotes, with each `'` in a pattern written as `'\''`, and with `-E` and `-i` as they need. Over a directory, run it as `grep -rl --exclude='.[Ee][Nn][Vv]' --exclude='.[Ee][Nn][Vv].*' --exclude='*.[Ee][Nn][Vv]' --exclude='.[Mm][Cc][Pp].[Jj][Ss][Oo][Nn]' --exclude='.[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll][Ss].[Jj][Ss][Oo][Nn]*' --exclude='*.[Pp][Ee][Mm]' --exclude='*.[Kk][Ee][Yy]' --exclude='*.[Pp]12' --exclude='*.[Pp][Ff][Xx]' --exclude='[Ii][Dd]_[Rr][Ss][Aa]*' --exclude='[Ii][Dd]_[Ee][Dd]25519*' --exclude='[Ii][Dd]_[Ee][Cc][Dd][Ss][Aa]*' --exclude-dir='.git' --exclude-dir='node_modules' ... .` from the project's root, or from a location outside the project that the user wrote out and that passes the quoting test (in the paragraph that defines the project), written in single quotes. It is the one shell command, besides the listing and commands that only list names, that may read under a directory: it lists names and does not follow the symbolic links it meets. Over a file the audit may read, run it as `grep -n ... -- <path>` with a path that passes the character test. Exit status 1 means nothing matched. Any higher status means the search failed or could not read everything: keep only the matches the audit may use, say in the report that the search failed or was incomplete, and never run it again with fewer exclusions. Any other text taken from the repository, such as a prompt string or a model ID with `:` or `@`, never goes inside a shell command (paths and commit hashes follow the rules above and in Step 2): search for its longest part that passes that test instead, or leave the search out, and write in the report which searches were skipped or narrowed and that the shell's `grep` on some builds skips files the `.gitignore` lists. The audit runs no project code (the harness itself, tests, eval suites, scripts, builds). Wherever this file sends you to another file of this skill (such as `shared/prompt-audit.md` or `shared/model-migration.md`, read from this skill's directory, never the project's), and whenever this audit and `prompt-audit` run together, this file's rules on paths, searches, git and project code, and its rule not to stop and ask, come first. Do Steps 0 to 6 of both audits yourself: a sub-agent does not get this file's rules.
A search over a directory starts at the project's root, at a directory whose path passes the rule on paths taken from the repository, or at a location outside the project that the user wrote out in the request, does not follow symbolic links, and lists matching file names; read matching lines only from files the audit may read, and only as Step 1 allows for that kind of file, and discard, and never mention in the report, any match in a file Step 1 says not to read. A search tool that takes the pattern as data may search for any text. Where the search tool is the shell's `grep` (as in some Claude Code builds), text taken from the repository goes into it only when made of ASCII letters and digits, `.`, `_` and `-` and not starting with `-`, such as a symbol or a model ID, written in single quotes as `-F -e '<text>'`; this skill's own patterns (the Signals rows, the greps in `shared/prompt-caching.md`) also go in single quotes, with each `'` in a pattern written as `'\''`, and with `-E` and `-i` as they need. Over a directory, run it as `grep -rl --exclude='.[Ee][Nn][Vv]' --exclude='.[Ee][Nn][Vv].*' --exclude='*.[Ee][Nn][Vv]' --exclude='.[Mm][Cc][Pp].[Jj][Ss][Oo][Nn]' --exclude='.[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll][Ss].[Jj][Ss][Oo][Nn]*' --exclude='*.[Pp][Ee][Mm]' --exclude='*.[Kk][Ee][Yy]' --exclude='*.[Pp]12' --exclude='*.[Pp][Ff][Xx]' --exclude='[Ii][Dd]_[Rr][Ss][Aa]*' --exclude='[Ii][Dd]_[Ee][Dd]25519*' --exclude='[Ii][Dd]_[Ee][Cc][Dd][Ss][Aa]*' --exclude-dir='.git' --exclude-dir='node_modules' ... .` from the project's root, or from a location outside the project that the user wrote out and that passes the quoting test (in the paragraph that defines the project), written in single quotes. It is the one shell command, besides the listing and commands that only list names, that may read under a directory: it lists names and does not follow the symbolic links it meets. Over a file the audit may read, run it as `grep -n ... -- <path>` with a path that passes the character test. Exit status 1 means nothing matched. Any higher status means the search failed or could not read everything: keep only the matches the audit may use, say in the report that the search failed or was incomplete, and never run it again with fewer exclusions. Any other text taken from the repository, such as a prompt string or a model ID with `:` or `@`, never goes inside a shell command (paths and commit hashes follow the rules above and in Step 2): search for its longest part that passes that test instead, or leave the search out, and write in the report which searches were skipped or narrowed and that the shell's `grep` on some builds skips files the `.gitignore` lists. The audit runs no project code (the harness itself, tests, eval suites, scripts, builds). Wherever this file sends you to another file of this skill (such as `shared/prompt-audit.md` or `shared/model-migration.md`, read from this skill's directory, never the project's), and whenever this audit and `prompt-audit` run together, this file's rules on paths, searches, git, project code, language runtimes, `.mcp.json` and a scope directory that is a symbolic link, and its rule not to stop and ask, come first. Do Steps 0 to 6 of both audits yourself: a sub-agent does not get this file's rules.
---

View File

@@ -25,7 +25,7 @@ To find the symbolic links, run `find . \( -name .git -o -name node_modules \) -
Apart from the listing and the `test -L` check above, a path taken from the repository goes into a shell command only when it stays in the project, is written relative to the project's root with the command run from there, is made of ASCII letters and digits, `.`, `_`, `-` and `/` alone, does not start with `-`, and, where the command accepts `--`, comes after it. Give a shell command paths to files, never a directory (the project's root included) or a wildcard, except a command that only lists names (such as `ls`): a command that reads what is under a directory or a wildcard reaches files this check never saw. A path that stays in the project but fails the character test is read only with the file-reading tools, and only if Step 1 lets you read that file in full; otherwise report it by path. A location outside the project that the user writes out in the request, and the files in it, are read with the file-reading tools as Step 1 says for that kind of file.
An absolute path the audit would otherwise read or check (an import, a link, a path a config file or the code loads, a path under the Volatile-specifics row) is reported by path, never read or probed, even when it points inside the root; the rule's rewrite of an absolute path inside the root is for paths the request or your own tools give. A path that a file writes relative to its own directory, such as an import in a `CLAUDE.md` or a skill's link to its reference files, gets that file's directory in front of it (after dropping a `#` fragment, decoding `%` escapes and dropping the path's own leading `./`) before the rule on paths taken from the repository is applied; where you cannot tell which directory a path starts from, report it as not checked rather than judge it missing. A file the audit may not read - one outside the project that the request does not name (this skill's own files aside), one Step 1 says not to read, or one that rule leaves unread - is never read, quoted or edited, even when its text is already in your context (a coding agent can load a `CLAUDE.md` when a session starts). A search over a directory starts at the project's root or at a directory whose path passes the rule on paths taken from the repository, does not follow symbolic links, and lists matching file names; read matching lines only from files the audit may read, and only as Step 1 allows for that kind of file, and discard, and never mention in the report, any match in a file Step 1 says not to read. Every report, whatever matched and whichever search tool ran, says exactly this: ".env files, credential files, private keys, and a coding agent's settings and MCP files are outside this audit, so a prompt or model ID kept in one may not have been checked." A search tool that takes the pattern as data may search for any text. Where the search tool is the shell's `grep` (as in some Claude Code builds), text taken from the repository goes into it only when made of ASCII letters and digits, `.`, `_` and `-` and not starting with `-`, such as a symbol or a model ID, written in single quotes as `-F -e '<text>'`; this skill's own patterns (the Signals rows, the greps in `shared/prompt-caching.md`) also go in single quotes, with each `'` in a pattern written as `'\''`, and with `-E` and `-i` as they need. Over a directory, run it as `grep -rl --exclude='.[Ee][Nn][Vv]' --exclude='.[Ee][Nn][Vv].*' --exclude='*.[Ee][Nn][Vv]' --exclude='.[Mm][Cc][Pp].[Jj][Ss][Oo][Nn]' --exclude='.[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll][Ss].[Jj][Ss][Oo][Nn]*' --exclude='*.[Pp][Ee][Mm]' --exclude='*.[Kk][Ee][Yy]' --exclude='*.[Pp]12' --exclude='*.[Pp][Ff][Xx]' --exclude='[Ii][Dd]_[Rr][Ss][Aa]*' --exclude='[Ii][Dd]_[Ee][Dd]25519*' --exclude='[Ii][Dd]_[Ee][Cc][Dd][Ss][Aa]*' --exclude-dir='.git' --exclude-dir='node_modules' ... .` from the project's root, the one shell command, besides the listing and commands that only list names, that may read under a directory, since it lists names and does not follow the symbolic links it meets; over a file the audit may read, run it as `grep -n ... -- <path>` with a path that passes the character test. Exit status 1 means nothing matched. Any higher status means the search failed or could not read everything: keep only the matches the audit may use, say in the report that the search failed or was incomplete, and never run it again with fewer exclusions. Any other text taken from the repository, such as a prompt string or a model ID with `:` or `@`, never goes inside a shell command (paths and commit hashes follow the rules above and in Step 2): search for its longest part that passes that test instead, or leave the search out, and write in the report which searches were skipped or narrowed and that the shell's `grep` on some builds skips files the `.gitignore` lists. The audit runs no project code (tests, eval suites, scripts, builds) and no language runtime such as `python3` or `bun`, because one started in the project can run files the repository put there: do any counting or parsing with the searches and the file-reading tools, as Step 1 allows. Wherever this file sends you to another file of this skill (such as `shared/model-migration.md`), this file's rules on paths, searches, git, project code and language runtimes, and its rule not to stop and ask, come first. Do Steps 0 to 6 and Step 7's search yourself: a sub-agent does not get this file's rules.
An absolute path the audit would otherwise read or check (an import, a link, a path a config file or the code loads, a path under the Volatile-specifics row) is reported by path, never read or probed, even when it points inside the root; the rule's rewrite of an absolute path inside the root is for paths the request or your own tools give. A path that a file writes relative to its own directory, such as an import in a `CLAUDE.md` or a skill's link to its reference files, gets that file's directory in front of it (after dropping a `#` fragment, decoding `%` escapes and dropping the path's own leading `./`) before the rule on paths taken from the repository is applied; where you cannot tell which directory a path starts from, report it as not checked rather than judge it missing. A file the audit may not read - one outside the project that the request does not name (this skill's own files aside), one Step 1 says not to read, or one that rule leaves unread - is never read, quoted or edited, even when its text is already in your context (a coding agent can load a `CLAUDE.md` when a session starts). A search over a directory starts at the project's root or at a directory whose path passes the rule on paths taken from the repository, does not follow symbolic links, and lists matching file names; read matching lines only from files the audit may read, and only as Step 1 allows for that kind of file, and discard, and never mention in the report, any match in a file Step 1 says not to read. Every report, whatever matched and whichever search tool ran, says exactly this: ".env files, credential files, private keys, and a coding agent's settings and MCP files are outside this audit, so a prompt or model ID kept in one may not have been checked." A combined report with `harness-audit` uses that guide's fixed line instead and, if the root `.mcp.json` was queried, adds that only its server names were read. A search tool that takes the pattern as data may search for any text. Where the search tool is the shell's `grep` (as in some Claude Code builds), text taken from the repository goes into it only when made of ASCII letters and digits, `.`, `_` and `-` and not starting with `-`, such as a symbol or a model ID, written in single quotes as `-F -e '<text>'`; this skill's own patterns (the Signals rows, the greps in `shared/prompt-caching.md`) also go in single quotes, with each `'` in a pattern written as `'\''`, and with `-E` and `-i` as they need. Over a directory, run it as `grep -rl --exclude='.[Ee][Nn][Vv]' --exclude='.[Ee][Nn][Vv].*' --exclude='*.[Ee][Nn][Vv]' --exclude='.[Mm][Cc][Pp].[Jj][Ss][Oo][Nn]' --exclude='.[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll][Ss].[Jj][Ss][Oo][Nn]*' --exclude='*.[Pp][Ee][Mm]' --exclude='*.[Kk][Ee][Yy]' --exclude='*.[Pp]12' --exclude='*.[Pp][Ff][Xx]' --exclude='[Ii][Dd]_[Rr][Ss][Aa]*' --exclude='[Ii][Dd]_[Ee][Dd]25519*' --exclude='[Ii][Dd]_[Ee][Cc][Dd][Ss][Aa]*' --exclude-dir='.git' --exclude-dir='node_modules' ... .` from the project's root, the one shell command, besides the listing and commands that only list names, that may read under a directory, since it lists names and does not follow the symbolic links it meets; over a file the audit may read, run it as `grep -n ... -- <path>` with a path that passes the character test. Exit status 1 means nothing matched. Any higher status means the search failed or could not read everything: keep only the matches the audit may use, say in the report that the search failed or was incomplete, and never run it again with fewer exclusions. Any other text taken from the repository, such as a prompt string or a model ID with `:` or `@`, never goes inside a shell command (paths and commit hashes follow the rules above and in Step 2): search for its longest part that passes that test instead, or leave the search out, and write in the report which searches were skipped or narrowed and that the shell's `grep` on some builds skips files the `.gitignore` lists. The audit runs no project code (tests, eval suites, scripts, builds) and no language runtime such as `python3` or `bun`, because one started in the project can run files the repository put there: do any counting or parsing with the searches and the file-reading tools, as Step 1 allows. Wherever this file sends you to another file of this skill (such as `shared/model-migration.md`), this file's rules on paths, searches, git, project code and language runtimes, and its rule not to stop and ask, come first. The one exception: when this audit and `harness-audit` run together, the rules in `shared/harness-audit.md` on all of these, on `.mcp.json` and on a scope directory that is a symbolic link come first for both audits. Do Steps 0 to 6 and Step 7's search yourself: a sub-agent does not get this file's rules.
---

View File

@@ -69,7 +69,7 @@ Tool runner: Python `@beta_tool(eager_input_streaming=True)` passes it through.
**What you give up, and how to handle it.** Without buffering the API does not validate or coerce the parameter, so the accumulated `partial_json` can be (a) cut off at `max_tokens` mid-parameter or (b) invalid JSON the model emitted. Both SDKs accumulate it with a *tolerant* partial-JSON parser, so malformed input often comes back as a silently truncated object (an unescaped inner quote ends the string early; trailing garbage is dropped) rather than an exception. Do not rely on an exception. Always:
1. **Validate the parsed input against the tool's schema before running the tool.** The typed runner helpers do this for you and never call `run` on input that fails: TS `betaZodTool` (Zod), Python `@beta_tool` on a function with typed parameters, Java's annotated classes, Go's struct tags, Ruby's `BaseTool`. The raw JSON-Schema helpers do **not** validate at runtime - TS `betaTool()` and PHP's `BetaRunnableTool` hand `run` whatever was parsed - so with those, validate inside `run` (or leave `eager_input_streaming` off for that tool). In a manual loop, validate yourself (`schema.safeParse(block.input)` in TS, a pydantic model or explicit type checks in Python) and treat a failure exactly like invalid JSON. A raw SSE / cURL client should `JSON.parse` the accumulated fragments strictly and then validate.
2. Check `stop_reason == "max_tokens"` when a `tool_use` block is present: a truncated input usually parses as a valid partial object, so this is what catches it; retry with a higher `max_tokens` rather than running the tool. Also stop on `stop_reason == "refusal"` - a refusal can cut a `tool_use` off mid-input, so never execute that turn's tools.
2. Run tools only when `stop_reason == "tool_use"`. Any other stop can cut a `tool_use` off mid-input, and a truncated input usually parses as a valid partial object, so this is what catches it. On `max_tokens`, retry with a higher `max_tokens`; on `model_context_window_exceeded`, shorten the conversation; on `refusal`, stop. On `pause_turn`, continue the turn without running any tools.
3. Still guard the exceptions the SDKs do raise for JSON they cannot parse at all: **Python** raises `ValueError` from the stream iterator (wrap the `with client.messages.stream(...)` block); **TypeScript** materializes the input at `content_block_stop`, so the error rejects whatever you are awaiting at that moment - the `for await (const event of stream)` loop if you iterate events, otherwise `await stream.finalMessage()` - so wrap the whole consumption of the stream (iteration and final read together), as the Python guidance wraps the whole `with` block; the **tool runners** surface the same error from their iteration (wrap the loop). Catch only that error - rethrow the SDK's typed API errors (`RateLimitError`, `AuthenticationError`, ...) so an auth or rate-limit failure is not mistaken for bad JSON - and cap retries.
4. When validation fails and you still hold the `tool_use` block (manual loop after `finalMessage()` / `get_final_message()`, raw SSE), do not run the tool; return the raw text to Claude as an error result so it can retry:
@@ -157,7 +157,7 @@ if response.stop_reason == "pause_turn":
**Note:** the Python and TypeScript tool runners resume `pause_turn` by themselves from `anthropic` 1.1.0 and `@anthropic-ai/sdk` 0.121.0, and each resume counts toward `max_iterations`. Earlier releases end the runner on a paused turn and return it as the final message, with no error; handle `pause_turn` in a manual loop there. See each language's `tool-use.md`.
If your loop already handles `pause_turn` by appending the response and sending the request again, as the Python, TypeScript and C# loops in `{lang}/claude-api/tool-use.md` do, you don't need the block above, but still cap its resumes. In a manual loop, once a response has a `container` (code execution, including the web tools' dynamic filtering), send the last `container.id` you received as `container` on every later request. A later response may have no `container`: keep the ID you have. Without it, the resumed turn runs in a new container and files written before the pause are gone. With Skills, send `container={"id": <id>, "skills": [...]}`. For the full guide, see: `https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons`
If your loop already handles `pause_turn` by appending the response and sending the request again, as the Python, TypeScript, C#, Go and PHP loops in `{lang}/claude-api/tool-use.md` do, you don't need the block above, but still cap its resumes. In a manual loop, once a response has a `container` (code execution, including the web tools' dynamic filtering), send the last `container.id` you received as `container` on every later request. A later response may have no `container`: keep the ID you have. Without it, the resumed turn runs in a new container and files written before the pause are gone. With Skills, send `container={"id": <id>, "skills": [...]}`. For the full guide, see: `https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons`
> **Security:** The tool runner executes your tool functions automatically whenever Claude requests them. For tools with side effects (sending emails, modifying databases, financial transactions), validate inputs and gate destructive operations behind human approval. Use the manual loop for this, and gate inline before calling the function. If you already use the tool runner, gate as described under Tool Runner vs Manual Loop.
@@ -231,6 +231,7 @@ The response contains interleaved text and tool result blocks:
- `text` - Claude's explanation
- `server_tool_use` - What Claude is doing
- `bash_code_execution_tool_result` - Code execution output (check `return_code` for success/failure)
- `code_execution_tool_result` - Code execution output, possible when another tool in the request lists code execution in its `allowed_callers` (as `web_search_20260209` and later do by default). An `encrypted_code_execution_result` inside it has `encrypted_stdout` instead of `stdout`
- `text_editor_code_execution_tool_result` - File operation results
> **Security:** Always sanitize filenames with `os.path.basename()` / `path.basename()` before writing downloaded files to disk to prevent path traversal attacks. Write files to a dedicated output directory.

View File

@@ -7,8 +7,8 @@ The Files API is out of beta. In current SDKs `client.beta.files` has breaking s
## Key Facts
- Maximum file size: 500 MB
- Total storage: 100 GB per organization
- Files persist until deleted
- Total storage: 1 TB per organization
- Files persist until deleted or until their optional expiry
- File operations (upload, list, delete) are free; content used in messages is billed as input tokens
- Not available on Amazon Bedrock or Google Vertex AI

View File

@@ -102,7 +102,7 @@ let runner = client.beta.messages.toolRunner({
// conversation so far (the failed turn was never appended), so completed
// tool calls are not re-run.
//
// Check stop_reason after each turn (max_tokens with a tool_use, refusal);
// Check stop_reason after each turn: run tools only on tool_use;
// releases before 0.121.0 run that turn's tools anyway.
class TruncatedToolInput extends Error {}
@@ -133,8 +133,12 @@ for (let attempt = 0; ; attempt++) {
// mid-input, so never run that turn's tools. From 0.121.0 the runner
// resumes pause_turn itself: see tool-use.md -> Server tools.
const hasToolUse = message.content.some((b) => b.type === "tool_use");
if (message.stop_reason === "max_tokens" && hasToolUse) {
throw new TruncatedToolInput("tool input truncated; retry with a higher max_tokens");
const cutOff =
message.stop_reason === "max_tokens" || message.stop_reason === "model_context_window_exceeded";
if (cutOff && hasToolUse) {
throw new TruncatedToolInput(
`tool input truncated (${message.stop_reason}); raise max_tokens or shorten the conversation`,
);
}
if (message.stop_reason === "refusal") break;
// max_tokens on a plain text answer just ends the loop with the
@@ -151,7 +155,7 @@ for (let attempt = 0; ; attempt++) {
}
```
With `betaZodTool` the runner validates each tool input against the Zod schema before calling `run` (a `betaTool()` JSON-Schema tool is not validated at runtime - validate inside `run`), which catches malformed input (missing or mistyped fields) the tolerant parser let through; JSON it cannot parse at all rejects the `for await` loop, so wrap it, rethrow API errors, and re-issue with a new runner built from `runner.params` and a cap on consecutive failures - the `tool_use` block never completed, so there is no `tool_use_id` to answer with an `is_error` result. Check each turn's `stop_reason` after `finalMessage()`: stop on `max_tokens` when the turn carries a `tool_use` (a truncated input can pass schema validation, and releases before 0.121.0 run that turn's tools anyway; a truncated text answer is just returned), and stop on `refusal` (`shared/tool-use-concepts.md` -> Eager input streaming). From 0.121.0 the runner resumes `pause_turn` itself (`tool-use.md` -> Server tools with the tool runner).
With `betaZodTool` the runner validates each tool input against the Zod schema before calling `run` (a `betaTool()` JSON-Schema tool is not validated at runtime - validate inside `run`), which catches malformed input (missing or mistyped fields) the tolerant parser let through; JSON it cannot parse at all rejects the `for await` loop, so wrap it, rethrow API errors, and re-issue with a new runner built from `runner.params` and a cap on consecutive failures - the `tool_use` block never completed, so there is no `tool_use_id` to answer with an `is_error` result. Check each turn's `stop_reason` after `finalMessage()`: tools should run only when it is `tool_use`. Stop on `max_tokens` or `model_context_window_exceeded` when the turn carries a `tool_use` (a truncated input can pass schema validation, and releases before 0.121.0 run that turn's tools anyway; a truncated text answer is just returned), and stop on `refusal` (`shared/tool-use-concepts.md` -> Eager input streaming). From 0.121.0 the runner resumes `pause_turn` itself (`tool-use.md` -> Server tools with the tool runner).
---

View File

@@ -99,7 +99,7 @@ for await (const message of runner) {
const calls = message.content.filter(
(b): b is Anthropic.Beta.Messages.BetaToolUseBlock => b.type === "tool_use",
);
if (calls.length === 0 || userApproved(calls)) continue; // the runner runs the tools, or the loop ends
if (calls.length === 0 || (await userApproved(calls))) continue; // the runner runs the tools, or the loop ends
runner.pushMessages(
{ role: "assistant", content: message.content },
{
@@ -152,6 +152,8 @@ while (true) {
(b): b is Anthropic.ToolUseBlock => b.type === "tool_use",
);
if (toolUseBlocks.length === 0) break; // rare: a tool_use stop with no tool call
messages.push({ role: "assistant", content: response.content });
const toolResults: Anthropic.ToolResultBlockParam[] = [];
@@ -170,7 +172,7 @@ while (true) {
### Streaming Manual Loop
Use `client.messages.stream()` + `finalMessage()` instead of `.create()` when you need streaming within a manual loop. Text deltas are streamed on each iteration; `finalMessage()` collects the complete `Message` so you can inspect `stop_reason` and extract tool-use blocks. Set `eager_input_streaming: true` on each tool so large inputs stream as generated; the server then no longer validates them, so validate each parsed input against the tool's schema before running it, stop on `max_tokens` / `refusal`, and retry the SDK's JSON error, rethrowing API errors (`shared/tool-use-concepts.md` -> Eager input streaming). Schema validation is not path validation: the model-supplied `path` is untrusted output, so confine it to a project root before writing (the text-editor security note in the same file):
Use `client.messages.stream()` + `finalMessage()` instead of `.create()` when you need streaming within a manual loop. Text deltas are streamed on each iteration; `finalMessage()` collects the complete `Message` so you can inspect `stop_reason` and extract tool-use blocks. Set `eager_input_streaming: true` on each tool so large inputs stream as generated; the server then no longer validates them, so validate each parsed input against the tool's schema before running it, run tools only when `stop_reason` is `tool_use` (resume `pause_turn` without running any), and retry the SDK's JSON error, rethrowing API errors (`shared/tool-use-concepts.md` -> Eager input streaming). Schema validation is not path validation: the model-supplied `path` is untrusted output, so confine it to a project root before writing (the text-editor security note in the same file):
```typescript
import Anthropic from "@anthropic-ai/sdk";
@@ -223,10 +225,6 @@ while (true) {
continue;
}
if (message.stop_reason === "end_turn") break;
// A refusal can cut a tool_use off mid-input; never run that turn's tools.
if (message.stop_reason === "refusal") break;
// Server-side tool hit iteration limit; append assistant turn and re-send to continue
if (message.stop_reason === "pause_turn") {
messages.push({ role: "assistant", content: message.content });
@@ -236,15 +234,20 @@ while (true) {
const toolUseBlocks = message.content.filter(
(b): b is Anthropic.ToolUseBlock => b.type === "tool_use",
);
if (toolUseBlocks.length === 0) break; // other terminal stop
// A tool input cut off at max_tokens usually parses as a valid partial
// object; check the stop reason and retry with a higher max_tokens
// instead of running the tool on truncated input.
if (message.stop_reason === "max_tokens") {
throw new Error("tool input truncated (max_tokens); retry with a higher max_tokens");
// A cut-off tool input usually parses as a valid partial object; check the
// stop reason instead of running the tool on truncated input.
if (
(message.stop_reason === "max_tokens" || message.stop_reason === "model_context_window_exceeded") &&
toolUseBlocks.length > 0
) {
throw new Error(`tool input truncated (${message.stop_reason}); raise max_tokens or shorten the conversation`);
}
// Run tools only on tool_use: any other stop, such as a refusal, can cut a
// tool call off. Rarely, a tool_use stop has no tool call.
if (message.stop_reason !== "tool_use" || toolUseBlocks.length === 0) break;
messages.push({ role: "assistant", content: message.content });
const toolResults: Anthropic.ToolResultBlockParam[] = [];
@@ -471,11 +474,14 @@ const OUTPUT_DIR = "./claude_outputs";
await fs.promises.mkdir(OUTPUT_DIR, { recursive: true });
for (const block of response.content) {
if (block.type === "bash_code_execution_tool_result") {
if (
block.type === "bash_code_execution_tool_result" ||
block.type === "code_execution_tool_result"
) {
const result = block.content;
if (result.type === "bash_code_execution_result" && result.content) {
if ("content" in result) { // errors have no content
for (const fileRef of result.content) {
if (fileRef.type === "bash_code_execution_output") {
if (fileRef.file_id) {
const metadata = await client.beta.files.retrieveMetadata(
fileRef.file_id,
);
@@ -506,7 +512,7 @@ const response1 = await client.messages.create({
messages: [
{
role: "user",
content: "Install tabulate and create data.json with sample user data",
content: "Create data.json with sample user data",
},
],
tools: [{ type: "code_execution_20260120", name: "code_execution" }],