Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
One refund tool, three checkpoints: the description gets it picked, the input schema shapes the call, and a structured error with is_error, a category and a retryable flag tells the agent whether to fix, retry, explain or escalate.
What you will learn
- Write an input_schema with types, a pattern, an enum and a required list
- Check the input in the handler even when a schema exists
- Return a structured error with is_error, a category and a retryable flag
- Treat an empty search result as a success, not an error
Before you start
- Tool descriptions: how Claude picks a tool
- Claude tool use: tool_use and tool_result
You ask a shop to refund your headphones, order 1042. The clerk comes back and says only: operation failed. Failed how? Should you try again, fix the form, or ask for a manager?
An agent calling a tool has the same problem. In this article we take one refund tool and get three things right: the description, the input schema and the error response. With those three, the agent knows what to pick, how to call it, and what to do when it fails.
A refund counter with a sign, a form and a slip
At a refund counter three things help you:
- The sign above the counter: Refunds, orders up to 100. Larger, see a manager. That is the description.
- The form: fixed boxes and fixed choices. That is the schema.
- The slip you get back when the form is wrong: Not accepted. The order id has letters. Write digits and come back. That is the error response.
tool_def.py: the card Claude reads
The description follows the four parts from how Claude picks a tool: what it does, the input format, an example and a boundary. The schema then shapes the call.
"""The card Claude sees for one tool: name, description, input_schema."""
REFUND_TOOL = {
"name": "process_refund",
"description": (
"Refunds part or all of one shop order and returns a refund id. "
"Input: an order id made of digits, like 1042, and an amount. "
"Example: order_id 1042, amount 49.90, reason damaged. "
"Not for refunds above 100.00: use escalate_to_human."
),
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "pattern": "^[0-9]+$",
"description": "Digits only, like 1042"},
"amount": {"type": "number",
"description": "Refund amount, like 49.90"},
"reason": {"type": "string",
"enum": ["damaged", "late", "other"]},
},
"required": ["order_id", "amount", "reason"],
},
}
- The
patternonorder_idallows digits only, so a letter is rejected. - The
enumonreasonallows exactly three values: damaged, late or other. requiredlists all three fields, so there is no call without them.
handler.py: the schema is a contract, so check it
A schema describes the shape you expect. Your handler still checks it, so a bad id never reaches the refund service.
"""Your code runs the tool. The schema is a contract, so check it."""
import re
from errors import ok_result, error_result
from tool_def import REFUND_TOOL
PROPS = REFUND_TOOL["input_schema"]["properties"]
def check_input(args):
for name in REFUND_TOOL["input_schema"]["required"]:
if name not in args:
return f"Missing required field {name}"
if not re.match(PROPS["order_id"]["pattern"], args["order_id"]):
return f'order_id "{args["order_id"]}" must be digits, like 1042'
if args["reason"] not in PROPS["reason"]["enum"]:
return "reason must be damaged, late or other"
return None
def process_refund(block, service_up=True, role="support"):
uid, args = block["id"], block["input"]
problem = check_input(args)
if problem:
return error_result(uid, "validation", False, problem)
if role != "support":
return error_result(uid, "permission", False,
"This role cannot refund orders")
if not service_up:
return error_result(uid, "transient", True,
"Refund service timed out after 5 seconds")
if args["amount"] > 100:
return error_result(uid, "business", False,
"Refund 400.00 is above the 100.00 limit",
"I cannot refund that myself, but a person can.")
return ok_result(uid, {"refund_id": "R-7001", "amount": args["amount"]})
def find_orders(block):
"""A good search that found nothing: success, not an error."""
return ok_result(block["id"], {"orders": []})
Four kinds of failure, four categories:
- validation: bad input. Not retryable. Fix the input and call again.
- permission: this role can't do it. Not retryable.
- transient: a timeout. The only one marked retryable, because the same call may work next time.
- business: over the refund limit. Not retryable, and it carries a customer-friendly line the agent can pass on.
errors.py: building the tool result
"""Tool results for the Messages API. is_error is the API flag.
errorCategory and isRetryable are our own keys inside content."""
import json
def ok_result(tool_use_id, data):
return {"type": "tool_result", "tool_use_id": tool_use_id,
"content": json.dumps(data)}
def error_result(tool_use_id, category, retryable, message, say=None):
body = {"errorCategory": category, "isRetryable": retryable,
"message": message}
if say:
body["customerMessage"] = say
return {"type": "tool_result", "tool_use_id": tool_use_id,
"content": json.dumps(body), "is_error": True}
Be clear about which part is which. is_error is the flag from the Claude API, so Claude knows the call failed. errorCategory, isRetryable and customerMessage are our own convention, placed inside the content.
Run it: the agent reads each result
agent_side.py is a stand-in agent. It imitates the decisions with simple rules, so no API key is needed: retry a transient error once, fix a validation error, explain a business error, escalate anything else.
def decide(result):
data = json.loads(result["content"])
if not result.get("is_error"):
if data.get("orders") == []:
return "SUCCESS, no orders found: tell the customer"
return "SUCCESS: " + data["refund_id"]
if data["errorCategory"] == "transient":
return "RETRY once"
if data["errorCategory"] == "validation":
return "FIX the input and call again"
if data["errorCategory"] == "business":
return "EXPLAIN politely (customerMessage)"
return "ESCALATE to a human"
Eight cases, eight decisions:
works -> SUCCESS: R-7001
bad id -> FIX the input and call again
no amount -> FIX the input and call again
bad reason -> FIX the input and call again
timeout -> RETRY once
over limit -> EXPLAIN politely (customerMessage)
no access -> ESCALATE to a human
no orders -> SUCCESS, no orders found: tell the customer
Look at the last line. A search that finds nothing is a good answer, so it comes back as a success. Marking it as an error would send the agent off retrying a search that worked.
Two guards: shape and meaning
The schema catches shape: a number where a string belongs, a reason that isn't in the list, a missing field. With strict: true on the tool, the Claude docs (Strict tool use) say the inputs always match the schema.
But no schema knows your rules. An amount of 400.00 is a valid number and still over the policy. A guest role is valid input and still has no permission. Those come back from your handler as is_error: true with a category. Strict tool use removes bad shapes; business rules and permissions stay in the handler.
Break it: one message for everything
The bug is a handler that returns Operation failed for every problem. A timeout, a bad id, a policy refusal and a missing permission all look the same, so the agent can only guess. It retries, and retries, and the refund limit never changes.
The fix is one line: error_result(uid, "business", False, ...). Not retryable, so the agent stops and explains. The label costs one line; the wasted retries cost every call.
Quick recap
| Piece | Job | Key parts |
|---|---|---|
| Description | Gets the tool picked | What, input, example, boundary |
input_schema | Shapes the call | Types, pattern, enum, required |
| Handler check | Catches meaning the schema can't | Limits, roles, service health |
| Error result | Tells the agent what to do next | is_error, a category, a retryable flag, a message |
| Empty result | A valid answer | Success, not an error |
For a wrong pick, fix the descriptions first. For a failed call, return an instructive error, not a generic one. When the schema itself has a bug, the trace tells you which part to fix; that routine is in fixing a broken tool schema.
Try it yourself
Add a fifth category, not_found, for an order id that doesn't exist. Decide whether it is retryable, and what the agent should say. Is it an error at all, or a good answer like the empty search?
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.