Skip to main content

8.1 Tool implementation

The function-calling contract​

StepOwnerMechanics
1. DeclareYoutools: [{name, description, input_schema, strict?}]
2. DecideModelEmits tool_use blocks; stop_reason becomes tool_use
3. ExecuteYouDispatch by name, with input parsed as JSON
4. ReturnYouOne tool_result per tool_use, matching tool_use_id, all in a single user message
5. ContinueModelReasons over the results; loop until end_turn

The model never executes anything (except server-side tools). A "tool" is a described capability plus your handler.

ControlEffect
tool_choice: "auto"Default — the model decides whether to call a tool
tool_choice: "any"It must call some tool
tool_choice: {"type": "tool", "name": "x"}It must call that tool — use for forced single-shot extraction
tool_choice: "none"No tool calls this turn
disable_parallel_tool_use: trueAt most one tool_use block per turn
strict: trueValidated input; requires additionalProperties: false plus required
defer_loading: trueThe definition is not loaded until a tool-search tool finds it — for large tool sets. Never defer every tool, and never the search tool itself, or the request 400s

Writing the description​

The description is the model's only specification. It is where selection reliability comes from.

{
"name": "lookup_order",
"description": "Retrieve the status, line items, and shipping state of ONE order by its order number (format: 5-8 digits, e.g. 12345678).\n\nUse when the user references an order, a shipment, a delivery, or a tracking number.\nDo NOT use to look up a customer's account, contact details, or order history — use lookup_customer for that.\nRequires a verified customer ID from get_customer first.\nReturns an error with category 'not_found' if the order number does not exist.",
"input_schema": {
"type": "object",
"properties": {
"order_number": { "type": "string", "description": "5-8 digits, no prefix, e.g. 12345678" },
"customer_id": { "type": "string", "description": "Verified ID from get_customer" }
},
"required": ["order_number", "customer_id"],
"additionalProperties": false
},
"strict": true
}
IncludeWhy
What it does, in one sentenceThe primary selection signal
When to use it — trigger phrases and situationsMaps user language onto the tool
When not to use it, naming the sibling toolThe only reliable way to separate similar tools
Input formats with examplesPrevents format drift
PrerequisitesStates the ordering the model should follow (enforce it with a hook)
What it returns, including error shapesLets the model plan the next step
Boundaries and limitsOne order, not many; max 100 results
The canonical selection item

Two tools with minimal descriptions ("Retrieves customer information" / "Retrieves order details") and overlapping identifier formats; the model picks wrong 12% of the time. The fix is expanding both descriptions with formats, example queries, edge cases, and explicit boundaries against each other. Not few-shot examples in the system prompt, not a keyword routing layer, not merging them into one overloaded tool — those are the three distractors.

Tool set construction​

PracticeDetail
Few, well-separated toolsOverlapping tools are the main cause of misselection
One responsibility eachA tool that does three things needs a mode flag, and the model will pick the wrong mode
Consistent naming and shapesverb_noun, same field names for the same concepts across tools
Consistent result formatsOne timestamp format, one status vocabulary — or normalise in a post-tool hook
Right granularityNot one do_everything, not fifty micro-tools. Group by the unit of work the model reasons about
Scope per roleA subagent gets only its tools; a turn on untrusted content gets read-only ones
Tool search for large setsdefer_loading plus a tool-search tool keeps the window small

Structured tool errors​

An error the model reads should say what to do next.

{
"error": {
"category": "validation",
"retryable": false,
"message": "order_number must be 5-8 digits; received 'ORD-12345'.",
"next_step": "Strip the prefix and retry with '12345'."
}
}
CategoryRetryableModel's correct response
transientyesRetry, with backoff
validationnoFix the argument and call again
not_foundnoTell the user, or try a different identifier
permissionnoEscalate; do not retry
business_rulenoExplain the rule to the user; escalate if the user needs an exception

Return it as a tool_result with is_error: true, one per failed tool_use. Dropping the block leaves a dangling tool_use and breaks the conversation.

Dispatch patterns​

PatternShapeFits
Agentic harness dispatchA name → handler map in your loop, called per tool_use blockMost custom agents
SDK tool runnerThe SDK loops and dispatches; you write the functionsStandard loops with per-turn hooks
Client-side toolsExecute in your processAnything touching your data, your network, or your credentials
Server-side (Anthropic-hosted) toolsExecute on Anthropic's infrastructure; results arrive as content blocks in the same responseWeb search, web fetch, code execution — no handler to write
MCP toolsExecute in an MCP server processCapabilities reused across applications (8.2)
Programmatic tool callingClaude calls your tool from inside code execution — add allowed_callers: ["code_execution_20260120"]Loops over many tool calls without a round trip per call. Incompatible with strict: true, forced tool_choice, and disable_parallel_tool_use

Dispatch hygiene: validate the parsed input against the schema server-side anyway, run independent calls concurrently, enforce a per-tool timeout, make handlers idempotent by key, and never let a handler's exception escape as a stack trace into the model's context.

Approval patterns​

PatternMechanismWhen
Auto-approveNothingRead-only, low-risk, high-frequency
Threshold gatePre-dispatch check on an argumentAmounts, batch sizes, blast radius
Prerequisite gateRefuse until a prior step is recordedVerify identity before acting on an account
Human approvalPause and surface the pending callIrreversible or externally visible operations
Allow-listEnumerated permitted targetsPaths, domains, table names, recipients
Two-phaseprepare_x returns a plan; commit_x executes it against a plan IDComplex irreversible operations needing review of the exact effect

Approval must be enforced before the side effect, in your code. "Ask the user before doing anything destructive" in a system prompt is not an approval pattern.

Quiz​

  1. Question 1

    Logs show the agent frequently calls get_customer when users ask about orders instead of lookup_order. Both tools have minimal descriptions ("Retrieves customer information" / "Retrieves order details") and accept similar identifier formats. What is the most effective first step?

  2. Question 2

    A tool call fails because the backend is momentarily unavailable. Which tool_result body best enables the agent to recover?