Executing Tool Calls
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Defining a tool is the easy half. The harder half is what happens when Claude actually calls it: unexpected input, a function that throws, a result a hundred times bigger than you meant, a call that hangs. The code that sits between "Claude asked" and "here's the answer" is your executor, and it's where most of a tool-using application's reliability comes from. This lesson builds one.
What you'll learn
- How to turn every failure into a useful
tool_result instead of a crash.
- How to write error messages Claude can recover from.
- How to validate input, cap result size and handle timeouts.
- How to keep internal details out of what the model sees, in Python and PHP.
Before you start
The executor's one job
The executor takes a tool name and an input object and always gives back two things: a string for the tool_result, and a flag saying whether it's an error. The important word is always. If your executor can throw, the loop can crash halfway through a conversation, and the model is left with a tool_use that never got a result. A failed tool isn't an exception to your program, it's information for the model, and Claude is good at using it. Anthropic's docs show it recovering: an error result about a missing parameter makes Claude retry with the parameter filled in, and a "weather service is down" error becomes an honest apology to the user.
So the executor has to do six things, in this order:
- Find the tool by name, and report unknown names helpfully.
- Validate the input against the schema.
- Run it, with a time limit.
- Separate expected failures from bugs. Expected ones carry a message written for the model; bugs get logged for you and replaced with a generic message.
- Shape the result: turn objects into JSON text and cap the size.
- Return
(content, is_error), never raise.
Writing error messages for a model
Anthropic's advice is to make errors instructive. "failed" gives Claude nothing to work with; "Rate limit exceeded. Retry after 60 seconds." tells it what happened and what to do. A good tool error answers two questions: what went wrong, and what should be tried next, in terms the model can act on. Compare:
Weak: "Error"
Weak: "psycopg2.OperationalError: connection to server at 10.0.3.14 failed"
Good: "No order A9 was found for this customer. Ask them to check the order id."
Good: "The carrier service is busy. Retry after 30 seconds or tell the customer to try later."
The second weak example is the dangerous one: it leaks an internal address and tells the model nothing useful. That's why the executor splits failures into two kinds. A ToolError is one you anticipated, so its message was written on purpose and goes straight back. Any other exception is a bug: the full details go to your logs with a short reference, and the model only sees "failed with an internal error (ref 3f9a1c2b)", along with a hint not to retry.
The Python executor
This is the registry that the loop from lesson 4.2 can plug into. Registering a tool takes its definition and a function, plus options for timeout, maximum result size, risk level (used in lessons 4.7 and 4.8) and whether the function needs the trusted request context (used in lesson 4.6):
import concurrent.futures
import json
import logging
import uuid
from dataclasses import dataclass, field
from typing import Any, Callable
from tool_defs import validate_input
log = logging.getLogger("tools")
class ToolError(Exception):
"""An expected, recoverable failure. The message is written for Claude and is sent back as-is,
so make it say what went wrong and what to try next. Never put secrets or stack traces in it."""
@dataclass
class RegisteredTool:
definition: dict
func: Callable[..., Any]
timeout: float = 10.0
max_chars: int = 4000
risk: str = "read" # read | write | destructive (used by the policy layer in lesson 4.8)
needs_context: bool = False # True: func receives the trusted request context as its first argument
@dataclass
class ToolRegistry:
tools: dict[str, RegisteredTool] = field(default_factory=dict)
def register(self, definition: dict, func: Callable[..., Any], **options) -> None:
self.tools[definition["name"]] = RegisteredTool(definition, func, **options)
def definitions(self) -> list[dict]:
return [t.definition for t in self.tools.values()]
def execute(self, name: str, tool_input: dict, ctx: Any = None) -> tuple[str, bool]:
"""Always returns (content, is_error). It never raises: a failed tool becomes information for the model."""
tool = self.tools.get(name)
if tool is None:
return f"Unknown tool '{name}'. Available tools: {', '.join(sorted(self.tools))}.", True
problems = validate_input(tool.definition, tool_input)
if problems:
return "Invalid input: " + "; ".join(problems) + ". Fix the input and call the tool again.", True
args = (ctx,) if tool.needs_context else ()
pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
future = pool.submit(tool.func, *args, **tool_input)
try:
raw = future.result(timeout=tool.timeout)
except concurrent.futures.TimeoutError:
# The worker thread cannot be killed; this only stops us waiting. Use real timeouts in the tool itself.
return f"The {name} tool timed out after {tool.timeout:g} seconds. Try again later or tell the user it is unavailable.", True
except ToolError as e:
return str(e), True
except Exception: # noqa: BLE001
ref = uuid.uuid4().hex[:8]
log.exception("tool %s crashed (ref %s)", name, ref) # details stay in YOUR logs
return f"The {name} tool failed with an internal error (ref {ref}). Do not retry; tell the user it is unavailable.", True
finally:
pool.shutdown(wait=False)
return self._format(raw, tool.max_chars), False
@staticmethod
def _format(raw: Any, max_chars: int) -> str:
text = raw if isinstance(raw, str) else json.dumps(raw, ensure_ascii=False, default=str)
if not text:
return "The tool ran and returned no data."
if len(text) > max_chars:
text = text[:max_chars] + f"\n[truncated: {len(text) - max_chars} more characters. Ask for a narrower query.]"
return text
A few details are worth explaining.
- Validation comes before execution, using the same JSON Schema you sent. Even with strict mode on, keep this. It's cheap, and it covers non-strict tools and any other path into the function.
- The timeout only stops waiting. Python can't kill a running thread. So the real protection is a timeout inside the tool itself, such as an HTTP client timeout (lesson 4.5). The executor's timeout is a backstop that keeps one stuck tool from freezing the whole conversation.
- Results are text. A string passes through; a dict or list becomes JSON. Anything over the limit is cut and ends with a note telling Claude to ask for a narrower query, which turns an overflow into something the model can act on.
- An empty result says so. "The tool ran and returned no data" is clearer than an empty string.
We tested every path: an unknown tool (the reply lists the available ones), invalid input (the function was never called), a dict result converted to JSON with non-ASCII text intact, a ToolError message passed through unchanged, a crash whose secret details ("password=...", an IP address) never reached the result but did reach the log, a timeout that returned in well under two seconds, truncation with the right "more characters" count, an empty result, and context being passed as the first argument.
The same thing in PHP
For a Laravel app the idea is identical. A small registry class, a ToolError exception for expected failures, and a minimal schema check. The check below handles type, required, enum and additionalProperties: false; for the full JSON Schema language use a library such as opis/json-schema.
<?php
namespace App\Support\Tools;
use RuntimeException;
/** An expected, recoverable failure. The message is written for Claude, so say what went wrong and what to try. */
class ToolError extends RuntimeException {}
<?php
namespace App\Support\Tools;
use Closure;
use Throwable;
final class ToolRegistry
{
/** @var array<string, array{definition: array, handler: Closure, risk: string, needs_context: bool, max_chars: int}> */
private array $tools = [];
public function register(array $definition, Closure $handler, array $options = []): void
{
$this->tools[$definition['name']] = [
'definition' => $definition,
'handler' => $handler,
'risk' => $options['risk'] ?? 'read',
'needs_context' => $options['needs_context'] ?? false,
'max_chars' => $options['max_chars'] ?? 4000,
];
}
/** @return list<array> */
public function definitions(): array
{
return array_values(array_map(fn ($t) => $t['definition'], $this->tools));
}
public function risk(string $name): ?string
{
return $this->tools[$name]['risk'] ?? null;
}
/**
* Never throws. Returns [content, is_error] so a failed tool becomes information for the model.
*
* @return array{0: string, 1: bool}
*/
public function execute(string $name, array $input, mixed $ctx = null): array
{
$tool = $this->tools[$name] ?? null;
if ($tool === null) {
return ["Unknown tool '{$name}'. Available tools: ".implode(', ', array_keys($this->tools)).'.', true];
}
$problems = SchemaCheck::validate($tool['definition']['input_schema'], $input);
if ($problems !== []) {
return ['Invalid input: '.implode('; ', $problems).'. Fix the input and call the tool again.', true];
}
try {
// String keys are spread as named arguments, so the order Claude writes the JSON keys in does not matter.
$raw = $tool['needs_context'] ? ($tool['handler'])($ctx, ...$input) : ($tool['handler'])(...$input);
} catch (ToolError $e) {
return [$e->getMessage(), true];
} catch (Throwable $e) {
$ref = substr(bin2hex(random_bytes(4)), 0, 8);
error_log("tool {$name} crashed (ref {$ref}): ".$e::class.': '.$e->getMessage()); // details stay in YOUR logs
return ["The {$name} tool failed with an internal error (ref {$ref}). Do not retry; tell the user it is unavailable.", true];
}
return [$this->format($raw, $tool['max_chars']), false];
}
private function format(mixed $raw, int $maxChars): string
{
$text = is_string($raw) ? $raw : json_encode($raw, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($text === '' || $text === false || $text === null) {
return 'The tool ran and returned no data.';
}
if (mb_strlen($text) > $maxChars) {
$extra = mb_strlen($text) - $maxChars;
$text = mb_substr($text, 0, $maxChars)."\n[truncated: {$extra} more characters. Ask for a narrower query.]";
}
return $text;
}
}
<?php
namespace App\Support\Tools;
/**
* A deliberately small JSON Schema check: type, required, enum and additionalProperties:false for flat object
* schemas. For full JSON Schema use a library such as opis/json-schema. Strict tool use already guarantees the
* shape on the API side; this is the check you keep anyway.
*/
final class SchemaCheck
{
/** @return list<string> */
public static function validate(array $schema, array $data): array
{
$problems = [];
$properties = $schema['properties'] ?? [];
foreach ($schema['required'] ?? [] as $key) {
if (! array_key_exists($key, $data)) {
$problems[] = "{$key}: is required";
}
}
foreach ($data as $key => $value) {
if (! isset($properties[$key])) {
if (($schema['additionalProperties'] ?? true) === false) {
$problems[] = "{$key}: is not an allowed property";
}
continue;
}
$spec = $properties[$key];
if (isset($spec['type']) && ! self::typeMatches($spec['type'], $value)) {
$problems[] = "{$key}: must be of type {$spec['type']}";
} elseif (isset($spec['enum']) && ! in_array($value, $spec['enum'], true)) {
$problems[] = "{$key}: must be one of ".implode(', ', $spec['enum']);
}
}
return $problems;
}
private static function typeMatches(string $type, mixed $value): bool
{
return match ($type) {
'string' => is_string($value),
'integer' => is_int($value),
'number' => is_int($value) || is_float($value),
'boolean' => is_bool($value),
'array' => is_array($value) && array_is_list($value),
'object' => is_array($value),
default => true,
};
}
}
One PHP detail that matters: $handler(...$input) spreads an associative array as named arguments, so it doesn't matter what order Claude happens to write the JSON keys in. An earlier draft of this class spread them by position, which would have silently put the wrong values into the wrong parameters whenever the order differed. Tests with deliberately reordered keys are what exposed it, which is a good argument for testing that path.
The PHP side was checked with the same cases: success as JSON, a ToolError message passed through, missing required keys, wrong types, an extra key rejected, an unknown tool, a crash that hid its secret but logged it, truncation, context first, enum errors, and then a full agent loop on the official SDK against a mock API (one tool call, an unknown tool reported to the model, and the iteration limit).
The loop that goes with the PHP registry follows the same shape as the Python one and sends back Claude's whole turn, one user message of results, and stops at the iteration limit:
<?php
namespace App\Support\Tools;
use Anthropic\Client;
use RuntimeException;
final class AgentLoop
{
public function __construct(
private Client $client,
private ToolRegistry $tools,
private string $model,
) {}
/**
* @return array{text: string, stop_reason: string, iterations: int, tool_calls: list<array>}
*/
public function run(string $userText, ?string $system = null, mixed $ctx = null, int $maxIterations = 8): array
{
$messages = [['role' => 'user', 'content' => $userText]];
$calls = [];
for ($i = 1; $i <= $maxIterations; $i++) {
$params = ['maxTokens' => 1024, 'messages' => $messages, 'model' => $this->model];
if ($system !== null) {
$params['system'] = $system;
}
if ($this->tools->definitions() !== []) {
$params['tools'] = $this->tools->definitions();
}
$response = $this->client->messages->create(...$params);
// Keep Claude's whole turn, exactly as returned.
$messages[] = ['role' => 'assistant', 'content' => $response->content];
if ($response->stopReason === 'tool_use') {
$results = [];
foreach ($response->content as $block) {
if ($block->type !== 'tool_use') {
continue;
}
$input = json_decode(json_encode($block->input), true) ?? [];
[$content, $isError] = $this->tools->execute($block->name, $input, $ctx);
$calls[] = ['name' => $block->name, 'input' => $input, 'is_error' => $isError];
$results[] = array_filter([
'type' => 'tool_result',
'tool_use_id' => $block->id,
'content' => $content,
'is_error' => $isError ?: null,
], fn ($v) => $v !== null);
}
// One user message with every result; tool_result blocks first.
$messages[] = ['role' => 'user', 'content' => $results];
continue;
}
if ($response->stopReason === 'pause_turn') {
continue;
}
$text = '';
foreach ($response->content as $block) {
if ($block->type === 'text') {
$text .= $block->text;
}
}
return ['text' => $text, 'stop_reason' => (string) $response->stopReason, 'iterations' => $i, 'tool_calls' => $calls];
}
throw new RuntimeException("Still calling tools after {$maxIterations} iterations.");
}
}
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A shop's lookup tool normally returns a small JSON object. One day a customer has 400 orders and the tool returns all of them as a huge blob. Without a cap, that blob goes into the next request, costs real money, and pushes earlier messages out of context. With the executor's cap, Claude gets the first part plus "truncated: ... more characters. Ask for a narrower query", and replies to the customer with something like "you have a lot of orders, which one do you mean?". The failure turned into a good conversation.
Mistakes to avoid
- Letting exceptions out of the executor.
- Returning raw exception text or stack traces to the model.
- Error messages with no next step ("failed").
- Returning entire database rows or API payloads.
- Relying on a Python thread timeout instead of timing out inside the tool.
- Retrying forever on an internal error. The message should tell the model not to.
Security notes
The executor is your last checkpoint before real systems. It's the place to check that input is valid, that the caller is allowed (lesson 4.8), and that nothing sensitive goes back. Never include secrets, internal hostnames or SQL in a message that goes to the model: whatever the model sees, a clever user may be able to get it to repeat. Log the details yourself, and give the model a reference number it can mention.
Cost and speed
Everything a tool returns is billed as input, and it stays in the conversation for every later request. Small, shaped results are cheaper and also easier for the model to use. Set a sensible max_chars per tool, not a single global value, because a "list" tool and a "get" tool deserve different limits.
Key takeaways
- An executor never raises: it returns content and an
is_error flag for every outcome.
- Write expected errors for the model: what went wrong and what to do next.
- Log bugs yourself; show the model only a generic message and a reference.
- Validate input, cap result size, shape results, and time out inside the tool as well as outside it.
Lesson recap: the executor never raises, and the model and you each get the message you need.
Quick quiz
- What two things does the executor always return?
- What's the difference between a
ToolError and an unexpected exception?
- Why is "failed" a poor error message for a tool result?
- Why doesn't a Python thread timeout fully protect you from a slow tool?
- Why spread PHP tool input as named arguments?
Answers and explanations
- The result text and a boolean error flag.
- A
ToolError is an anticipated failure with a message written for the model. Anything else is treated as a bug: details are logged and the model sees a generic message.
- It tells the model neither what went wrong nor what to try next, so it can't recover well.
- The timeout only stops the caller waiting; the thread keeps running. The tool itself needs a real timeout, such as an HTTP client timeout.
- Claude may write JSON keys in any order, so positional spreading could put values in the wrong parameters.
Official references and further reading
Related tutorials