Tutorial· · 9 min read

A hello world for agents: propose, validate, apply

An introductory example with the Claude Agent SDK: three agents that check each other to fix bugs, with the code on GitHub so you can run it in three commands.

  • claude-agent-sdk
  • ai-agents
  • multi-agent
  • python
  • hello-world

Asking a single agent to find bugs and fix them is asking it to be both judge and defendant: it decides what is wrong, how to fix it, writes the change and signs off on its own work. If along the way it “fixes” something by changing what already worked, nobody notices.

So I built the smallest example I could think of that separates those roles: one agent proposes, another judges and a third applies. It is a hello world for agents. It is not meant to be a tool, but something you can run in five minutes, read in an afternoon and break on purpose to see what happens.

What it is

Three agents in a row, each with a single job and no memory of the others. Python runs them one by one, keeps what each one returns and decides who goes next.

  1. Proposerreads the file and proposes fixes · Read only
  2. Validatorjudges each fix · no tools
  3. rejected fixes go back to the proposer once, with the validator's objection
  4. Applierapplies what was approved · Read and Edit
Figure 1 — Each box is an independent query() session. The arrows are text that Python passes from one to the next.

Goals of the example

The starting point is Anthropic’s Agent SDK quickstart: a single agent, with Read, Edit and Glob, that gets the instruction “Review utils.py for bugs that would cause crashes. Fix any issues you find.” and fixes the file on its own. It works, but it is a black box: the agent decides what a bug is, how to fix it and whether the fix is good, and you only see the result.

This example solves the same task with a few more pieces, so that control stays with the developer:

  • You will build a system of several agents, not just one. Each agent has its own context, decided by design: it knows exactly what your code hands it, and nothing else.
  • You are in control from end to end. You decide what each agent sees, which tools it has, what shape its answer must take and who speaks next. If a single agent did all three things, none of those decisions would be yours.
  • You will get hands-on with what the quickstart does not show: the conversation between agents, limiting tools and permissions, and what happens when an agent returns something unusable.

What you will learn

The goals are the why. This is what you will see, concretely, in the code:

  • That in the SDK an agent is a call to query() with a prompt, a model, some tools and, if you want, a response format.
  • How information passes from one agent to the next: Python builds each prompt from what the previous agent returned and keeps the state (the fixes and the verdicts, by id) between one call and the next.
  • The difference between tools (which tools exist for an agent) and allowed_tools (which ones run without asking for permission), and how a hook also limits which file they can touch.
  • How to ask for JSON answers with a schema and reject them when they do not match exactly.
  • How to watch what each agent does without filling the code with print.

What it is not

  • It is not a code reviewer for real use. It only looks for errors that crash the program (a KeyError, a division by zero), not logic, performance or security bugs.
  • It is not deterministic. Two runs on the same file can give different verdicts. That is part of what you observe, not a defect of the example.
  • It is not a sandbox. The hook stops the agents from reading or editing any other file with Read and Edit, but it is not an isolation boundary. Do not run it on anything you cannot recover.
  • It does not compare models or measure quality. There are no evals or benchmarks.
  • It does not cover the whole SDK. It uses no MCP servers, subagents, resumable sessions or streaming input.
  • It is not free. Each run calls three real models; by default, Opus, Sonnet and Haiku.

Before you start

You need uv and an Anthropic API key in the environment:

export ANTHROPIC_API_KEY="your-key"

The program edits the file you pass and makes no backup. That is why the example runs on a copy: examples/buggy_utils.py stays untouched and, to start over, you just copy it again. If you use it on a file of your own, make sure it is in git.

The example file

Five functions, each written to push toward a different outcome:

Function What it has What it aims for
calculate_average Divides by zero on an empty list CORRECT
get_user_name KeyError when "name" is missing CORRECT
get_first_item Its docstring says the IndexError is on purpose NOT_A_BUG
normalize Crashes on None; the “obvious” fix, str(text), changes the result for bytes INCORRECT and a second round
percentage Divides by zero when total is 0 CORRECT

“What it aims for” is the intent, not a guarantee. Further down is what happened in a real run.

An agent is a call to query()

All three agents are created the same way; what changes is the profile (model and effort) and, above all, the tools:

make_options("proposer",  model, tools=["Read"],         output_format=PROPOSAL_SCHEMA)
make_options("validator", model, tools=[],               output_format=VERDICT_SCHEMA)
make_options("applier",   model, tools=["Read", "Edit"], allowed_tools=["Read", "Edit"])

The validator has no tools at all. It cannot open the file even if it wanted to, so it judges only what the proposer handed over in writing: the current lines, three lines of context before and after, the replacement, why it crashes and what it assumes. What gets approved is exactly what will be applied.

Each agent also has its own profile, matched to how hard its task is: Opus with high effort for the proposer, Sonnet with medium effort for the validator and Haiku with low effort, without reasoning, for the applier, which only copies text that was already approved. You can change the model of any of them from the command line (--validator haiku, for example).

Permissions: configured, not requested

I could have written “do not edit other files” in the prompt. But that is a request, and a model can ignore it. In this example permissions live in three layers, and none of them is a prompt:

Layer What it decides
tools Which tools exist for that agent
allowed_tools Which ones run without asking for approval. Only the applier has it, because it runs with nobody watching
PreToolUse hook Which file each Read or Edit may touch

Neither tools nor allowed_tools says anything about paths. That is what the hook is for: it runs before every tool call and denies it if the path is not the file under review:

async def guard(input_data, tool_use_id, context):
    requested = input_data["tool_input"].get("file_path")
    if isinstance(requested, str) and os.path.realpath(requested) == allowed:
        return {}  # no decision: the normal permissions apply
    return {"hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "deny",
        "permissionDecisionReason": f"Only {allowed_path} may be accessed.",
    }}

Paths are compared after resolving .. and symbolic links, and the hook is registered with on_failure="block": if the hook itself fails, the call is blocked instead of going through.

Between agents, JSON or nothing

No agent talks to another in free text. The proposer answers with a fixed schema (id, function, line_start, line_end, before, current, after, replacement, cause, assumptions) and the validator with another (id, verdict, reason).

The validation in Python is intolerant on purpose. If a single field of a single fix does not have the expected type, or an id is repeated, the whole answer is discarded and the program exits with code 1 before calling the next agent. The validator must also return one verdict, and only one, per fix. If the proposer finds nothing, the program says so and exits without touching the file.

A second round, not endless ones

If the validator rejects a fix, the proposer gets one more chance: only the rejected fixes, each with the validator’s objection. If in that second round it returns something malformed, or “fixes” something nobody asked for, everything it returned is discarded. Two rounds at most.

What does not get fixed is not lost: the applier leaves a one-line comment above the function, # Review (not a bug): … or # Review (unresolved bug): …, with the validator’s reason.

One rule runs through the whole pipeline: the smallest fix that avoids the error, without changing the result of anything that works today. The proposer receives it as an instruction, and the validator uses it as a criterion: a fix that stops the crash but changes what another input returned is INCORRECT.

What happened in a real run

This is the diff between the example file and what the agents left behind:

 def calculate_average(numbers):
     total = 0
     for num in numbers:
         total += num
+    if len(numbers) == 0:
+        return None
     return total / len(numbers)


 def get_user_name(user):
-    return user["name"].upper()
+    try:
+        name = user["name"]
+    except KeyError:
+        name = None
+    return "" if name is None else name.upper()


 def get_first_item(items):
     """Return the first item. An empty list raises IndexError on purpose.
     Callers rely on it to detect that there is no result."""
     return items[0]


 def normalize(text):
+    if text is None:
+        return ""
     return text.strip().lower()


 def percentage(part, total):
-    return part / total * 100
+    try:
+        return part / total * 100
+    except ZeroDivisionError:
+        return None

Four fixes applied, and none changes the result of an input that already worked. But the most instructive part is what does not appear:

  • get_first_item has neither a fix nor a comment. The proposer read the docstring, understood the error was intentional and did not even propose it. Since the validator only judges what it receives, the NOT_A_BUG the example was aiming for never came to exist. It is the first lesson of any chain of agents: the next one only sees what the previous one decided to show it.
  • normalize got the minimal guard, not the str() conversion that would have changed the result for bytes. The rule against converting values did its job before the validator had to step in.
  • There is no # Review comment at all: everything that reached the end was approved.

The example aimed to show all three verdicts, and this run showed only one. That is the point: with agents, the design proposes and the run disposes.

Looking inside

By default you only see the text each agent passes to the next, which is where problems usually are. To see everything, including the reasoning, the tools used, and the cost and duration of each agent:

uv run python agent.py examples/utils.py --observer full

And to save one JSON line per event, with metadata only (never code or reasoning):

uv run python agent.py examples/utils.py --observer json 2> agent-events.jsonl

Keep playing

  • Run the same file two or three times and compare the handoffs. You will see how much the agents vary.
  • Delete the docstring of get_first_item and run it again: does it propose it now? What does the validator say?
  • Swap the validator for a smaller model (--validator haiku) and see whether it approves things it used to reject.
  • Copy a file with bugs in another language into examples/. The tools work with text, not with Python.

It is a toy example, but the underlying question is the same in any system where several agents work together: who proposes, who validates and who has permission to write.