Skip to content
Jordan Hudgens
A small courier robot holds a sealed envelope beside a lit workbench of precise instruments.
Guide 01IntermediateAgents and tool useEvaluation and testingPlaceholder

Build, Break, and Repair a Reliable Tool-Using Agent

Implement a bounded tool loop, diagnose a seeded failure, and prove the final state instead of trusting a success message.

Reading
35 min
Workshop
90 min
Video
31 min
Stack
TS · Node 22
Version
1.0.0
Last verified
Oct 12, 2026
Sample values
Sample

What you will build and be able to do

Each outcome has an observable criterion. The lab and the assessment check exactly these, nothing more and nothing less.

  1. OBJ-001

    Implement a bounded tool loop

    The agent completes the support task in at most 8 steps and stops on its own condition.

  2. OBJ-002

    Trace every action to its result

    Your log pairs each tool_use with exactly one tool_result by id.

  3. OBJ-003

    Diagnose a seeded failure

    You name the malformed result and the repeated-action hazard, with evidence.

  4. OBJ-004

    Verify final state

    A check outside the agent confirms the ticket state matches the expected write.

Sample

Ready in ten minutes

  • Comfortable in one programming languageRefresher: TypeScript in 20 minutes
  • Basic command-line useShell basics primer
  • Has made an API call beforeYour first Messages API request
  • Node 22 and pnpm installedSetup checklist
terminalbash
# Clone the lab at the tested taggit clone <lab-repository-url>cd 01-tool-using-agent && git checkout v1.0.0 pnpm installcp .env.example .env   # add ANTHROPIC_API_KEYpnpm lab:check✓ node 22.23.3  ✓ pnpm 12.3.4  ✓ api key present  ✓ fixtures loaded

Lab repository · tested at v1.0.0

Sample

One loop, one stop condition, one independent check

Diagram: Model, Tool call, Tool result, and Verified state connected left to right, with a loop back to Model until the stop condition is met.

Figure 1. The agent repeats model, tool call, and tool result until its stop condition holds. Completion is decided by a check outside the loop.

Extended description

The diagram shows four rounded boxes in a row, joined by mint arrows that point to the right. From left to right the boxes read Model, Tool call, Tool result, and Verified state.

An amber arrow leaves the bottom of the Verified state box, runs back along the underside of the row, and points up into the Model box. The label under that arrow reads Loop until the stop condition is met.

Read the diagram as a cycle. The model requests a tool call, the tool returns a result, the result goes back to the model, and the cycle repeats. The loop ends only when a check against the real state says the stop condition holds.

Sample

Why agents fail quietly

An agent rarely crashes. It returns a confident sentence about work it did not finish. The failure lives in the gap between what the model reports and what the environment now contains, so this guide treats the environment as the source of truth.

The agent loop

Each turn, the model either answers or requests a tool. Your code runs the tool, returns the result with the same id, and asks again. The loop is yours: you decide how many steps it may take and what counts as done.

Diagram frame titled The agent loop: Model, Tool call and Tool result joined by mint lines, with an amber curve returning from Tool result to Model and the note Loop until the stop condition is met, then verify final state.
Figure 2. Animated in the video at 06:12.
src/agent.tsts
for (let step = 0; step < MAX_STEPS; step++) {  const reply = await client.messages.create({ model, tools, messages })  messages.push({ role: "assistant", content: reply.content })  if (reply.stop_reason !== "tool_use") break   // the model answered  const results = await runTools(reply.content)  // one result per tool_use id  messages.push({ role: "user", content: results })}await verifyFinalState(ticketId)   // never trust the last message

Stop conditions

A loop needs two ways to end: a step cap that protects your budget, and a stop condition that says the work is done. The step cap is a safety net. The stop condition is a claim about the world, so it belongs in code that reads the world.

Verifying final state

After the loop ends, read the ticket from the system of record and compare it with the write you expected. If the two disagree, the run failed, whatever the last message says. The lab turns this check into a command you can run after every attempt.

Sample

Lab 2: Break it on purpose, then prove the repair

You will inject a malformed tool result, watch the agent claim success, and add the check that catches it.

Acceptance checks

  • pnpm lab:test passes all 6 cases
  • Seeded failure is detected, not retried forever
  • Final ticket state equals the expected write
  • Log shows one tool_result per tool_use id
  1. Run the baseline

    $ pnpm lab:run --ticket T-1042
    Agent: "Refund issued and ticket closed."
  2. Inject the failure

    $ pnpm lab:run --ticket T-1042 --inject malformed-result
    Agent: "Refund issued and ticket closed." (it is not)
  3. Add the independent check

    $ pnpm lab:verify --ticket T-1042
    ✗ expected status=closed, found status=open
  4. Show the solution discussion

    The agent treated a malformed tool result as a success because nothing validated the result before it went back to the model.

    Validate each result against a schema, return a distinct error when validation fails, and run the independent check after the loop ends. Re-run the lab test to confirm all six cases pass.

More labs in this guide

  • Lab 1: Build the bounded loop

    Run the baseline agent against one synthetic ticket and read its log.

  • Lab 3: Stop the repeated write

    Add an idempotency key so a retry cannot refund the same ticket twice.

Sample

Four ways this breaks, and how you will know

Every failure here is reproducible in the lab with a flag. Learn the symptom first; it is what you will actually see.

  • F-01Sample failure

    Confident false completion

    Symptom
    Agent reports success; ticket is still open.
    Diagnosis
    Tool result was malformed JSON; the model filled the gap.
    Fix
    Validate tool results against a schema before returning them.
    Verify
    pnpm lab:verify shows status=closed.
  • F-02Sample failure

    Repeated write

    Symptom
    Two refunds for one ticket.
    Diagnosis
    Retry after a timeout re-ran a non-idempotent tool.
    Fix
    Add an idempotency key per action; check before writing.
    Verify
    Ledger has exactly one refund row.
  • F-03Sample failure

    Runaway loop

    Symptom
    Step count hits the cap on every run.
    Diagnosis
    Tool error text never changes, so the model never stops.
    Fix
    Return a distinct, actionable error and stop after two identical failures.
    Verify
    Loop ends with reason=repeated_error.
  • F-04Sample failure

    Orphaned tool call

    Symptom
    API rejects the next request.
    Diagnosis
    A tool_use id had no matching tool_result.
    Fix
    Return one result per id, including failures.
    Verify
    Trace shows paired ids for every step.
Sample

Transfer task and rubric

Apply the pattern to an unseen billing-dispute scenario. Scored against anchored criteria; a proposed local standard, not an official certification.

Assessment rubric: each criterion described at four score levels
Criterion0 · Missing1 · Partial2 · Meets3 · Exceeds
Loop boundsNo capStep cap onlyStep cap and stop conditionBoth, with logged end reason
Result handlingUnvalidatedChecks shapeSchema-validated with errors returnedDistinct, actionable error taxonomy
Final-state proofTrusts the replyManual checkAutomated independent checkCheck plus regression test

Proposed local standard, not an official certification

Self-check
Sample

Teach it to a room

  • Run of show

    90-minute plan with timings, checkpoints, and fallbacks

  • 12 or 100 learners

    Lab-room and training-day adaptations with helper ratios

  • Dry-run protocol

    What to rehearse, the seeded failure, and the recovery path

  • Cleared-to-teach record

    Observation rubric and a module-specific clearance form

  • Pass-rate template

    Definitions for attempts, passes, and reassessments

Sample

Watch the build, the break, and the fix

31:08 · Sample video
  1. 00:00Why agents fail quietly
  2. 03:40The loop by hand
  3. 06:12Stop conditions
  4. 11:05Seeding the failure
  5. 17:30The independent check
  6. 24:18Teaching notes
Sample

One idea per minute

  • 0:58

    The agent said done. The database says no.

    YouTube ShortsSample

  • 0:47

    One result for every tool call id

    Instagram ReelsSample

  • 1:12

    How to stop a runaway loop

    TikTokSample

  • 1:03

    Idempotency keys in 60 seconds

    YouTube ShortsSample

  • 0:52

    What to check before you say done

    Instagram ReelsSample

Sample
LinkedIn · Article · 4 minWhy I make every agent lab fail on purpose
X · Thread · 9 postsThread: the four ways a tool-using agent breaks
Sample
  • Slidespdf · 4.2 MB
  • Instructor kitpdf · 1.1 MB
  • Lab starterzip · 86 KB
  • Rubricpdf · 210 KB
Sample
  1. [1]Building effective agents · anthropic.comchecked Oct 12, 2026
  2. [2]Writing effective tools for agents · anthropic.comchecked Oct 12, 2026
  3. [3]Demystifying evals for AI agents · anthropic.comchecked Oct 12, 2026
  4. [4]Tool use with Claude · platform.claude.comchecked Oct 12, 2026

Independent work. Not affiliated with or endorsed by any vendor named in this guide.

Jordan Hudgens

Author

Jordan Hudgens

Technical educator and AI engineering leader. 16 Udemy courses, 111K students, and curricula used by 250K+ learners.

Contact Jordan

Next in the path

All guides