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: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler

The refund app passes 0 of 4 eval cases. Each failure points to one layer: a vague system prompt, an amount typed as a string, and a stream handler that parses every partial_json piece on its own. Fix one at a time and watch the gate open.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Use an eval run to point at the layer where each defect lives
  • Close a format gap in the system prompt with an instruction, a constraint and one example
  • Fix a tool schema whose field type makes Claude send the wrong kind of value
  • Rebuild streamed tool input by joining input_json_delta pieces and parsing at content_block_stop

Before you start

  • Build a Claude refund app (part 2)
  • Streaming and error handling for LLM calls

The refund app is built and a release gate guards it. Today the build has three planted defects, and the first eval run passes none of its four cases. The defects sit in three different places: a prompt, a tool schema and a stream handler. We'll find each from the run, fix it where it lives, and prove each fix with the same run.

Think of a mechanic with a noisy car. First a test drive, noting each noise. Then follow each noise to one part. Then fix that part and drive the same route again. The mechanic never guesses. Our test drive is evals.py.

Three places a defect can hide Claude prompts.py shows in the reply format tools.py shows in the arguments relay.py shows in the streamed input evals.py: P1, T1, T2, S1 and one gate
The eval run points at the bug. The fix goes where the bug is.

The test drive: four cases, all failing

P1 asks where order A-101 is and checks the reply starts with the order id (a ticket filer downstream needs that). T1 and T2 check the tool trace for a small and a big refund, with the hook inside it. S1 streams one turn and rebuilds its tool call. The same four cases run on each build: all bugs planted, then one fix at a time. As in the rest of the build-along, Claude is a scripted stand-in.

== 1 all three planted
  P1 FAIL  order A-101 is shipped.
  T1 ERROR TypeError: '<=' not supported between 'str' and 'int'
  T2 ERROR TypeError: '<=' not supported between 'str' and 'int'
  S1 ERROR JSONDecodeError: Expecting value: line 1 column 1 (char 0)
0/4 passed, gate closed

Three symptoms, three different places. Read each one as a pointer, not as something to catch and hide.

Bug 1: a prompt that never names the format

"""G1: the system prompt for the refund assistant."""

SYSTEM_V1 = ("You are our refund assistant. "
             "Be short and polite.")

SYSTEM_V2 = """You are our refund assistant.
Start every reply with the order id and a colon.
After it, write one short sentence saying what happened.
Never put anything before the order id.
Example reply:
A-100: your refund was sent.
"""

"Be short and polite" is vague: it never names a format, so P1's check has nothing to hold on to. The fix stays in the system prompt, where the rules for every reply belong, apart from the customer's words. It adds three things: a clear instruction (start with the order id and a colon), an output constraint (never put anything before it), and one example showing the exact shape. See system prompt or user turn and explicit criteria vs vague prompts for the ideas behind it.

== 2 prompt fixed
  P1 pass  A-101: it is shipped.
  T1 ERROR TypeError: '<=' not supported between 'str' and 'int'
  T2 ERROR TypeError: '<=' not supported between 'str' and 'int'
  S1 ERROR JSONDecodeError: Expecting value: line 1 column 1 (char 0)
1/4 passed, gate closed

Bug 2: amount typed as a string

The type error comes from the hook comparing amount <= 500. The trace points at issue_refund, so we read its schema.

# tools_v1.py, the planted version
"input_schema": {
    "type": "object",
    "properties": {
        "order_id": {"type": "string"},
        "amount": {"type": "string"}},
    "required": ["order_id", "amount"]}
# tools.py, corrected
"input_schema": {
    "type": "object",
    "properties": {
        "order_id": {"type": "string"},
        "amount": {
            "type": "number",
            "description": "Total in dollars"}},
    "required": ["order_id", "amount"]}

Claude fills an argument the way the schema describes it. Typed as a string, amount arrives as text, and because it is required it always arrives, always as text. The fix is the type plus a description of what the field holds. Wrapping the hook in a try would hide the symptom and leave the bad type in place. More schema checks are in fix the tool schema.

== 3 schema fixed
  P1 pass  A-101: it is shipped.
  T1 pass  get_order > issue_refund
  T2 pass  get_order > issue_refund > hand_to_human
  S1 ERROR JSONDecodeError: Expecting value: line 1 column 1 (char 0)
3/4 passed, gate closed

Bug 3: parsing every stream piece on its own

When Claude streams a tool call, the input arrives in pieces, one per input_json_delta event, in delta.partial_json. None of the pieces is whole until the block stops.

"""Planted: rebuild tool calls from a stream."""
import json


def collect(events):
    calls = []
    for ev in events:
        if ev.type == "content_block_start":
            block = ev.content_block
            if block.type == "tool_use":
                calls.append({"name": block.name})
        elif ev.type == "content_block_delta":
            if ev.delta.type == "input_json_delta":
                piece = ev.delta.partial_json
                calls[-1]["input"] = json.loads(piece)
    return calls

The pieces here are an empty string, then the start of the object, then the end. json.loads("") fails on the very first one, which is exactly the "char 0" error in the run. Skipping empty pieces wouldn't help: the next piece is half an object and fails too.

Join the pieces, parse at the stop piece 1: ""piece 2: startpiece 3: end content_block_stop loads("") fails planted: parse each piece loads(raw) once fixed: raw += each piece, parse when the block is finished
A streamed tool input is only valid JSON after the block stops.
def collect(events):
    calls, raw = [], ""
    for ev in events:
        if ev.type == "content_block_start":
            block = ev.content_block
            if block.type == "tool_use":
                calls.append({"name": block.name})
                raw = ""
        elif ev.type == "content_block_delta":
            if ev.delta.type == "input_json_delta":
                raw += ev.delta.partial_json
        elif ev.type == "content_block_stop" and raw:
            calls[-1]["input"] = json.loads(raw)
            raw = ""
    return calls

A string called raw collects the pieces. At content_block_stop the input is whole, and we parse it once. More on stream events in streaming and error handling.

== 4 stream handler fixed
  P1 pass  A-101: it is shipped.
  T1 pass  get_order > issue_refund
  T2 pass  get_order > issue_refund > hand_to_human
  S1 pass  get_order {'order_id': 'A-101'}
4/4 passed, gate open

Where each fix goes

SymptomDefectFixTempting non-fix
Reply has no order id at the startPrompt gapInstruction, constraint, one example in the system promptA bigger model with the same vague prompt
TypeError in the hookSchema defectType number and a field descriptionCatch the error in the hook
JSONDecodeError on streamHandler defectJoin pieces, parse at content_block_stopSkip the empty piece

Each fix moved its own case, and the gate opened only when all four passed. Find the defect in the run, then fix it where it lives.

Previous: lab: cut the bill. Next: lab: planted bugs in settings, a plugin manifest and MCP auth.

Keep going in Claude · 60 of 66

Previous
Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
Next post
Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
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

  • The test drive: four cases, all failing
  • Bug 1: a prompt that never names the format
  • Bug 2: amount typed as a string
  • Bug 3: parsing every stream piece on its own
  • Where each fix goes
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.