Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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.
Three checkpoints: description, schema, result Claude reads the card Our handler checks the input Refund service does the work tool_use tool_result is_error + category 1. the words 2. the shape 3. the result
Claude picks by the card, our code checks the input, and the result tells Claude what to do next.

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 pattern on order_id allows digits only, so a letter is rejected.
  • The enum on reason allows exactly three values: damaged, late or other.
  • required lists 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

PieceJobKey parts
DescriptionGets the tool pickedWhat, input, example, boundary
input_schemaShapes the callTypes, pattern, enum, required
Handler checkCatches meaning the schema can'tLimits, roles, service health
Error resultTells the agent what to do nextis_error, a category, a retryable flag, a message
Empty resultA valid answerSuccess, 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?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 35 of 66

Previous
Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
Next post
Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet

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.

On this page

  • A refund counter with a sign, a form and a slip
  • tool_def.py: the card Claude reads
  • handler.py: the schema is a contract, so check it
  • errors.py: building the tool result
  • Run it: the agent reads each result
  • Two guards: shape and meaning
  • Break it: one message for everything
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.