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.
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:
- A procedure book. Each job is found by its name. That's the dispatch table.
- A manager's signature. Big refunds wait. That's the approval rule.
- A shift clock. The day has an end. That's the turn budget.
- 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:
| Option | What it does for you | What you control |
|---|---|---|
| The SDK's tool runner | Runs your tool functions and sends the results back | The least |
| The Claude Agent SDK | A ready-made harness: the loop, built-in tools and hooks | Through its options and hooks |
| Your own loop | Nothing; you write it | Every 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
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_useleaves the loop. - Before a tool runs, the loop asks the guard. Then it runs the tool through the table.
- Every
tool_usegets exactly onetool_resultwith the same id, and a failure is markedis_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
TOOLSis what Claude sees: each tool's name and input schema.HANDLERSis 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_orderisn'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_resultwithis_errorand the reason. - Looping until
end_turnwith 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_usestill needs itstool_result, even when you didn't run the tool.
Quick recap
| Check | Where | What it does |
|---|---|---|
| Dispatch | dispatch() | Maps a tool name to a function; unknown names get an error result |
| Approve | hold_reason() | Holds risky calls (refunds over 100) for a person; the tool doesn't run |
| is_error | run_block() | Tells Claude exactly what went wrong |
| Budget | Budget | Caps 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.
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.