Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin 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

Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap

Three bugs that pass a quick look: a tone-only judge (5 of 10 agreement, 4 false accepts), a retry loop that sends an invalid request three times, and a matcher that lets a $780 cancel skip the refund hook.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Give a judge rubric the facts and rule it needs, then prove it against human labels
  • Retry only transient API errors (rate limit, server, connection) with backoff
  • Build a PreToolUse matcher from the list of destructive tools so a new tool can't skip the hook
  • Re-run one check per bug to prove each correction

Before you start

  • Lab: golden set and judge calibration
  • Anthropic SDK timeouts, retries and error classes
  • Hooks that block destructive actions

The refund assistant passes its tests. But can we trust the checks themselves? This lab plants three bugs that each look fine at a glance: a judge nobody calibrated, a retry loop that retries everything, and a hook matcher that names only one tool. For each we write the correction and re-run the check that proves it.

Three everyday slips explain them. A kitchen scale nobody checked shows a number, and nobody knows if it's right. Redialling a wrong number never makes it ring. A lock on the front door leaves the back door open. Each slip looks fine until something checks it.

Three bugs, three corrections judge v1 hears tone only: 5/10 agree retry v1 retries every API error matcher v1 names issue_refund only rubric gets facts, calibrated on labels retry only errors that can pass matcher built from the destructive list planted (left), corrected (right)
A hardening pass finds the defect, writes the fix, and runs the check again.

As before, Claude is a scripted stand-in and the judge verdicts are scripted; the checks and corrections are real code.

Bug 1: a judge that hears tone, not facts

# Planted: the rubric hears tone, never the facts.
JUDGE_V1 = (
    "You grade one reply from a refund assistant. "
    "PASS if the reply is polite and answers the question. "
    "Otherwise FAIL. End with PASS or FAIL.")
# Correction: the rubric gets the facts and the rule.
JUDGE_V2 = (
    "You grade one reply from a refund assistant. "
    "Use the facts. PASS only if the reply matches them, "
    "names the right order, and sends a refund over "
    "the limit to a person. "
    "Otherwise FAIL. End with PASS or FAIL.")


def facts(ask):
    oid = re.search(r"A-\d+", ask).group()
    o = json.loads(ORDERS.read_text())[oid]
    return (f"order {oid}: status {o['status']}, total {o['total']}, "
            f"refund limit {POLICY_LIMIT}")


def grade(claude, rubric, ask, reply):
    note = f"Question: {ask}\nFacts: {facts(ask)}\nReply: {reply}"
    r = claude.messages.create(model=MODEL, max_tokens=20, system=rubric,
                               messages=[{"role": "user", "content": note}])
    return r.content[0].text.strip().endswith("PASS")

A judge can only check what it can see. Version one never gets the order facts, so a polite wrong answer passes. Version two gets the facts and the refund rule in every grading call. Then we calibrate on ten cases labelled by a person, with the same trust rule as the golden set lab: 90 percent agreement and no false accepts.

judge v1: agree 5/10  false accepts 4  false rejects 1
  false accepts: G02 G04 G07 G10
  trusted: no
judge v2: agree 10/10  false accepts 0  false rejects 0
  false accepts: none
  trusted: yes

The four false accepts are wrong replies that passed: a wrong status, a wrong order, a refund that should have gone to a person. "Tell the judge to be stricter" would not fix it; the judge was never checked against labels. See LLM-as-judge for the full method.

Bug 2: a retry loop that retries everything

"""D2: a retry loop. Retry what can pass on a second try, and nothing else."""
import time
import anthropic

# Planted: every API error is retried.
RETRY_V1 = (anthropic.APIError,)
# Correction: rate limits, server errors, timeouts.
RETRY_V2 = (
    anthropic.RateLimitError,
    anthropic.InternalServerError,
    anthropic.APIConnectionError,
)


def call(
    claude, retry_on, tries=3, sleep=time.sleep, **request
):
    for attempt in range(1, tries + 1):
        try:
            return claude.messages.create(**request)
        except retry_on:
            if attempt == tries:
                raise
            sleep(2 ** (attempt - 1))

The loop takes the error classes to retry as an argument, raises on the last try, and doubles the wait between tries (one second, then two). APIConnectionError covers timeouts too. APIError is the parent of every API error, including BadRequestError, so version one retries requests that will fail every time. Two kinds of failure show the difference:

overloaded twice, then fine
  v1 retry all: 3 requests, ok
  v2 retry transient: 3 requests, ok
prefilled reply, an invalid request
  v1 retry all: 3 requests, BadRequestError
  v2 retry transient: 1 request, BadRequestError

Overloaded twice and then fine: retrying is right, and both loops succeed on the third request. An invalid request (here, one with a prefilled reply the API rejects): version one sends it three times, version two sends it once and raises so the request can be fixed. Waiting longer between tries would not help; the request is still invalid. The SDK has its own retries, two by default; the lab switches them off to see only this loop. Error classes are covered in SDK timeouts, retries and error classes.

Bug 3: a matcher that names one tool

"""I3: money going back is checked by code, on every tool that can do it."""
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher

LIMIT = 500
PREFIX = "mcp__refunds__"
DESTRUCTIVE = ("issue_refund", "cancel_order")
# Planted: the matcher names one tool, by hand.
MATCHER_V1 = PREFIX + "issue_refund"
# Correction: the matcher is built from the list.
MATCHER_V2 = "|".join(PREFIX + t for t in DESTRUCTIVE)


def covers(matcher, name):
    """A pipe list is matched name by name."""
    return PREFIX + name in matcher.split("|")

A new cancel_order tool also sends money back, but the hand-written matcher only names issue_refund. The correction keeps one list of destructive tools and builds the matcher from it, as a pipe list with the server prefix on each name. The Agent SDK tests the matcher against the tool name; for exact names like these, covers() is the same check. Over the limit, the hook denies with a reason.

matcher v1: mcp__refunds__issue_refund
  matcher misses: cancel_order
  H-1: Please cancel order A-104.
    get_order A-104 -> mcp: {"status": "processing", "total": 780}
    cancel_order A-104 -> cancelled, $780 returned
    test model reply: order A-104 is cancelled.
matcher v2: mcp__refunds__issue_refund|mcp__refunds__cancel_order
  matcher misses: none
  H-1: Please cancel order A-104.
    get_order A-104 -> mcp: {"status": "processing", "total": 780}
    cancel_order A-104 -> hook denies
    hand_to_human A-104 -> queued for a human
    test model reply: a person will contact you about A-104.
  H-2: Please cancel order A-105.
    get_order A-105 -> mcp: {"status": "processing", "total": 60}
    cancel_order A-105 -> cancelled, $60 returned
    test model reply: order A-105 is cancelled.

With version one, a $780 cancel goes straight through: no hook, no check. With version two the same cancel is denied and handed to a person, while a $60 cancel still goes through. Telling the model "don't cancel big orders" is not a fix; a prompt can be argued with. More hook patterns are in hooks that block destructive actions.

All three, re-run together

judge v2 is trusted: True
invalid request sent once: True
matcher covers every destructive tool: True
all three fixed: True

Recap

BugFix that misses the causeCorrection
Judge passes wrong repliesTell it to be stricterGive it the facts, calibrate on human labels
Invalid request sent three timesWait longer between triesRetry only rate limit, server and connection errors
A cancel skips the hookTell the model not to cancel big ordersBuild the matcher from the list of destructive tools

Previous: lab: settings, plugin and MCP auth. Next: lab: our app as a reusable template.

Keep going in Claude · 62 of 66

Previous
Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
Next post
Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
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)

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

  • Bug 1: a judge that hears tone, not facts
  • Bug 2: a retry loop that retries everything
  • Bug 3: a matcher that names one tool
  • All three, re-run together
  • Recap
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.