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

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • 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
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Agents and MCP

Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget

Write the agent loop yourself and own the checks around it: a dispatch table for tool names, an approval rule that holds big refunds, failures sent back as is_error results, and a turn budget that ends a runaway loop.

Chaand Sheikh

·27 November 2026Agents and MCP

What you will learn

  • Wrap a Claude tool loop in a harness that checks every tool call before it runs
  • Map tool names to functions with a dispatch table and answer unknown tools with an error result
  • Hold risky calls for a person and report failures to Claude with is_error
  • End every loop with a turn budget

Before you start

  • The agentic loop and stop_reason
  • Claude tool use: tool_use and tool_result
  • Basic Python

A support agent can look up orders and send refunds. A customer writes: Refund order 2077. Claude asks for the issue_refund tool. A plain loop just runs it: 250 refunded, and nobody checked.

That's one worry. A tool name that doesn't exist is another. A loop that never ends is a third. Claude decides what to ask for. Your code decides what actually runs. The code that sits around the loop and makes those decisions is the harness.

A counter clerk with four rules

Think of a clerk at a shop counter. Customers give orders, and the clerk keeps four rules:

  1. A procedure book. Each job is found by its name. That's the dispatch table.
  2. A manager's signature. Big refunds wait. That's the approval rule.
  3. A shift clock. The day has an end. That's the turn budget.
  4. An outcome slip. Every job gets one, even a failed job. That's the tool result.

Claude gives the orders. The clerk keeps the rules.

Who runs the loop

You have three ways to run a Claude agent loop:

OptionWhat it does for youWhat you control
The SDK's tool runnerRuns your tool functions and sends the results backThe least
The Claude Agent SDKA ready-made harness: the loop, built-in tools and hooksThrough its options and hooks
Your own loopNothing; you write itEvery checkpoint

Write it yourself when you need custom control over how tools run. That's what this article builds. (The agentic loop article covers the bare loop and its stop rule; here we add the checks.)

One tool use, three checkpoints

The harness: guard, dispatch, result, inside a turn budget turn budget: the loop ends after max_turns, whatever happens Claude stop_reason: tool_use 1. guard hold_reason() 2. dispatch name -> function None 3. one tool_result, same tool_use_id is_error: true when held, unknown or failed held: tool not run back to Claude
Nothing Claude asks for runs until the loop has asked the guard and the table.

harness/loop.py

The project runs against a stand-in model (the Anthropic SDK on an httpx mock transport), so it needs no API key; replies are scripted and say "test model reply".

"""A custom agent loop: we own the checks."""
from harness.guards import Budget, hold_reason
from harness.tools import TOOLS, dispatch


def run_block(block, turn):
    """Answer one tool_use block with one tool_result."""
    held = hold_reason(block.name, block.input)
    if held:
        content, is_error = held, True
    else:
        content, is_error = dispatch(block.name, block.input)
    status = "error" if is_error else "ok"
    print(f"  turn {turn}: {block.name} -> {status}")
    result = {"type": "tool_result", "tool_use_id": block.id}
    result["content"] = content
    if is_error:
        result["is_error"] = True
    return result


def run_agent(client, task, max_turns=4):
    messages = [{"role": "user", "content": task}]
    budget = Budget(max_turns)
    while budget.turn():
        n = budget.turns
        response = client.messages.create(
            model="claude-sonnet-5-5", max_tokens=1024,
            tools=TOOLS, messages=messages)
        if response.stop_reason != "tool_use":
            print(f"  turn {n}: {response.stop_reason}")
            return "".join(b.text for b in response.content
                           if b.type == "text")
        messages.append({"role": "assistant",
                         "content": response.content})
        results = []
        for b in response.content:
            if b.type == "tool_use":
                results.append(run_block(b, n))
        messages.append({"role": "user", "content": results})
    return f"stopped: the budget of {max_turns} turns is used up"
  • A turn budget ends every loop, whatever happens.
  • Any stop reason other than tool_use leaves the loop.
  • Before a tool runs, the loop asks the guard. Then it runs the tool through the table.
  • Every tool_use gets exactly one tool_result with the same id, and a failure is marked is_error, so Claude is told.

harness/tools.py: the dispatch table

"""The tools the agent may ask for, and the table that runs them"""
import json
import pathlib

DATA = pathlib.Path(__file__).resolve().parent.parent / "data"
ORDERS = json.loads((DATA / "orders.json").read_text())

SCHEMA = {"type": "object", "required": ["order_id"],
          "properties": {"order_id": {"type": "string"}}}
TOOLS = [
    {"name": "lookup_order", "description": "Find an order.",
     "input_schema": SCHEMA},
    {"name": "issue_refund", "description": "Refund an order.",
     "input_schema": SCHEMA},
]


def lookup_order(order_id):
    if order_id not in ORDERS:
        raise LookupError(f"no order {order_id}. Check the id.")
    return ORDERS[order_id]


def issue_refund(order_id):
    return {"refunded": lookup_order(order_id)["amount"]}


HANDLERS = {"lookup_order": lookup_order,
            "issue_refund": issue_refund}


def dispatch(name, args):
    """Run the tool Claude named. Returns (content, is_error)."""
    handler = HANDLERS.get(name)
    if handler is None:
        known = ", ".join(HANDLERS)
        return f"unknown tool {name}. Available: {known}", True
    try:
        return json.dumps(handler(**args)), False
    except Exception as err:
        return f"{type(err).__name__}: {err}", True
  • TOOLS is what Claude sees: each tool's name and input schema.
  • HANDLERS is the dispatch table: a name maps to a function.
  • An unknown name doesn't crash the loop. It returns an error result that lists what is available.
  • An exception inside a tool becomes an error result too, with the reason in plain words.

These are client tools: your code runs them. Server tools, by contrast, run at Anthropic, and you don't dispatch them.

harness/guards.py: the budget and the approval rule

"""Two guards around the loop: a turn budget, an approval rule."""
from harness.tools import ORDERS

REFUND_LIMIT = 100
HELD = "held: a refund over {} needs a person. Not run."


class Budget:
    def __init__(self, max_turns):
        self.max_turns = max_turns
        self.turns = 0

    def turn(self):
        """Count one more turn. False once the budget is used up."""
        self.turns += 1
        return self.turns <= self.max_turns


def hold_reason(name, args):
    """Why a tool call must wait for a person, or None to go ahead."""
    if name == "issue_refund":
        order = ORDERS.get(args.get("order_id"), {})
        if order.get("amount", 0) > REFUND_LIMIT:
            return HELD.format(REFUND_LIMIT)
    return None

The limit of 100 is the shop's own rule. Over it, the call is held: the tool never runs, and Claude is told why in the error result. The orders file has two orders: 1042 (wireless headphones, 40) and 2077 (standing desk, 250).

Run, hold, explain

python main.py tools sends three requests:

task: Where is order 1042?
  turn 1: lookup_order -> ok
  turn 2: end_turn
  answer: test model reply: your wireless headphones have shipped.
task: Refund order 1042.
  turn 1: lookup_order -> ok
  turn 2: issue_refund -> ok
  turn 3: end_turn
  answer: test model reply: your refund of 40 was sent.
task: Refund order 2077.
  turn 1: lookup_order -> ok
  turn 2: issue_refund -> error
  turn 3: end_turn
  answer: test model reply: a person will review that refund first.

The lookup runs and ends. The refund of 40 is under the limit, so it runs. The refund of 250 is over it, so it's held and marked as an error; Claude hears why and tells the customer a person will review it first. The replies are scripted by the stand-in.

Unknown tool, runaway loop

python main.py limits sends two harder requests:

task: Cancel order 1042.
  turn 1: cancel_order -> error
  turn 2: end_turn
  answer: test model reply: I cannot cancel orders. I can look them up and refund them.
task: Keep checking order 9999 until it shows up.
  turn 1: lookup_order -> error
  turn 2: lookup_order -> error
  turn 3: lookup_order -> error
  turn 4: lookup_order -> error
  answer: stopped: the budget of 4 turns is used up
  • cancel_order isn't in the table. The harness sends back an error result instead of crashing, and Claude recovers by saying what it can do instead.
  • Order 9999 doesn't exist, so the lookup fails every time. Claude may call a failed tool again, so the loop has to limit it: after four turns the budget ends it.

Common mistakes

  • Asking Claude in the prompt to "be careful with refunds". A prompt rule only hopes. A check in the loop decides. (The guardrails article places the same kind of check on inputs and outputs too.)
  • Raising an exception when a tool fails. The loop dies and Claude never learns what happened. Send a tool_result with is_error and the reason.
  • Looping until end_turn with no limit. A tool that keeps failing can keep the loop alive. Cap the turns.
  • Calling whatever name Claude sends. Look it up in a table you wrote; answer unknown names with the list of tools that exist.
  • Skipping a result for a held call. Every tool_use still needs its tool_result, even when you didn't run the tool.

Quick recap

CheckWhereWhat it does
Dispatchdispatch()Maps a tool name to a function; unknown names get an error result
Approvehold_reason()Holds risky calls (refunds over 100) for a person; the tool doesn't run
is_errorrun_block()Tells Claude exactly what went wrong
BudgetBudgetCaps the turns so the loop always ends

A custom loop gives you control, and that means the checks are yours to write. If you'd rather start from a ready-made harness with hooks, the Claude Agent SDK provides one.

Try it yourself

Add a third guard: a customer may get at most one refund per conversation. Where does the count live, in the loop or in hold_reason? What should the error result say so Claude can explain it to the customer? Then decide whether a held refund should count against the turn budget.

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 AI Engineering · 46 of 89

Previous
Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
Next post
Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript

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

Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It

A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.

What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table

LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.

Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph

A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.

LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways

Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.

On this page

  • A counter clerk with four rules
  • Who runs the loop
  • One tool use, three checkpoints
  • harness/loop.py
  • harness/tools.py: the dispatch table
  • harness/guards.py: the budget and the approval rule
  • Run, hold, explain
  • Unknown tool, runaway loop
  • Common mistakes
  • 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.