Skip to content
Index Ai Academy
Phase 10 · Harness foundations

What an agent harness is

The software around a model that turns it into an agent.

About 35 minutes · Model names checked November 2026 · Free lesson

What it covers9

First principles

What turns a model's text requesting an action into a real effect?

The harness owns the loop, actions, state and limits around the model. A scripted model makes those behaviors observable without needing to predict or pay for a live model's response.

  1. Starting point

    Scripted model proposes a typed report read

  2. What changes

    Harness validates, checks permission and calls the tool

  3. Result

    Harness records the result and supplies it to the next model turn

Compare all three steps
  1. Starting point

    Scripted model proposes a typed report read

  2. What changes

    Harness validates, checks permission and calls the tool

  3. Result

    Harness records the result and supplies it to the next model turn

Complete and reverse the trace

Given Scripted model proposes a typed report read and Harness records the result and supplies it to the next model turn, write down the missing step that connects them.

Compare with the worked step

Harness validates, checks permission and calls the tool

Now take Harness validates, checks permission and calls the tool and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Scripted model proposes a typed report read. Check that your implementation produces the result shown above.

Try it on a new case

If the scripted model proposes an unknown tool, what component should reject it?

Show worked reasoning

The harness should reject the tool at lookup or validation and record a bounded error. The model supplied a proposal, and the harness decides which actions are available.

Practice each learning objective
  1. Tell the model apart from the harness, and list what a harness is responsible for

    A scripted model asks to write a report before a reviewer has approved it. Say which component proposed the write, which one declines it, and which event a reviewer should see in the log.

    Compare your reasoning

    The model proposed a call. The harness validates the call and applies the approval policy before calling the tool. A denial event includes the reason and the action identifier, so a reviewer can trace what happened without inspecting the model response alone.

  2. Recognize the three meanings of "harness": agent, test and evaluation harnesses

    One program runs a model with a lookup tool, a second checks the lookup against a known record, and a third compares lookup success across 80 changed prompts. Name the type of each harness and the evidence it produces.

    Compare your reasoning

    The agent harness produces tool traces and task responses. The test harness checks a specific contract against a controlled example. The evaluation harness aggregates success on a collection of prompts to compare behavior.

  3. Choose between a hand-built loop, the SDK's tool runner, the Claude Agent SDK and managed agents

    You need an offline classroom exercise where every tool proposal comes from a script and you can pause after any step. Choose a starting runtime and name one reason you would revisit that choice for a long-running production service.

    Compare your reasoning

    A small hand-built loop makes step boundaries and scripted responses explicit without requiring a network service. If production needs durable jobs, maintained integrations, or operational controls, compare what a vendor SDK or managed runtime provides and what ownership remains with your team.

  4. Build a minimal harness with a scripted model, pluggable tools and an event log

    Sketch two event sequences for a scripted report lookup. In the first the model supplies a known tool name and valid campaign ID. In the second it gives an unknown tool name. Which events prove no tool ran in the second case?

    Compare your reasoning

    A successful sequence records proposal, validated dispatch, and result. The unknown name should produce proposal and rejection followed by a stop or bounded request for correction. Recording tool start and completion explicitly lets a reviewer distinguish a rejection from a partial dispatch.

Run, change, and build

Check this when debugging. Thinking an agent's quality comes only from the model.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. If the scripted model proposes an unknown tool, what component should reject it?

Why it matters

A model on its own only turns text into text. Everything that makes it an agent, the loop, the tools, the permissions, the memory, is software around it called a harness. Two products using the same model can differ enormously because of their harnesses. Claude Code is a model plus a very good harness. This phase teaches you to build one: to customize agents, debug them, and judge the ones you're offered.

What you'll be able to do

  • Tell the model apart from the harness, and list what a harness is responsible for
  • Recognize the three meanings of "harness": agent, test and evaluation harnesses
  • Choose between a hand-built loop, the SDK's tool runner, the Claude Agent SDK and managed agents
  • Build a minimal harness with a scripted model, pluggable tools and an event log
Quick check
Two coding assistants use exactly the same model, but one is far better at fixing bugs. What's the most likely reason?
  1. It was given a longer and more detailed system prompt
  2. Its harness: the loop, tools, context and permissions around the model
  3. It's running on a faster computer with a lot more memory
  4. It has a bigger window for showing the code it edits
Show the answer

Its harness: the loop, tools, context and permissions around the model

A model only turns text into text. What it can read, which tools it can call, how it loops and when it stops are all the harness, so with the same model the harness decides the result. This phase teaches you to build one.

The idea: the model writes, the harness acts

Recall: The agent loop built the smallest loop, and Hosts: connecting servers to a model built the program that runs a model's tool calls. A harness is that program grown up. This phase builds the rest of it.

Quick check
From the lesson on the agent loop: call the model, and while it asks for tools, run them and send the results back. Here a scripted model stands in for the real one. What does this print: the model calls, the messages in the transcript, and the final text?
SCRIPT = [{"stop_reason": "tool_use", "tool": "search"},
          {"stop_reason": "end_turn", "text": "done"}]

def scripted_model(messages):
    return SCRIPT[sum(1 for m in messages if m["role"] == "assistant")]

messages = [{"role": "user", "content": "find the tent"}]
turns = 0
while True:
    reply = scripted_model(messages)
    messages.append({"role": "assistant", "content": reply})
    turns += 1
    if reply["stop_reason"] != "tool_use":
        break
    messages.append({"role": "user", "content": "tool_result: 3 tents"})
print(turns, len(messages), reply["text"])
  1. 2 4 done
  2. 3 6 done
  3. 1 2 done
  4. 2 3 done
Show the answer

2 4 done

The first reply asks for a tool, so the loop adds the result and calls again. The second reply ends the turn. That is two model calls and four messages: the question, the tool request, the tool result and the answer. Everything else in a harness is built around this loop, and the scripted model is how this phase tests it with no API.

Engine and car

Think of the model as an engine. It's the source of power, but an engine on a workbench goes nowhere. The harness is the rest of the car: wheels, brakes, fuel system, dashboard. A great engine in a bad car is a bad car.

A model call does exactly one thing: it reads a request (system prompt, messages, tool definitions) and returns a response (text, maybe tool_use blocks, and a stop_reason). Everything else is the harness:

harness partits joblessons
the loopcall the model, run its tools, feed results back, know when to stopcore loop
toolsthe actions on offer, their schemas and how they runregistry, files, execution
permissionswhich actions need a person's approvalpermissions
hooks and skillslet users and plugins change behavior; load know-how on demandhooks and skills
context managementkeep the conversation inside the window and cheapcontext
memory and planningcarry work across long tasks and new sessionsmemory and plans
subagentshand off focused sub-tasks to fresh contextssubagents
sessions and UIstream output, allow interrupts, save and resumesessions
observability and limitslogs, traces, costs, loop detectionproduction

In plain words: the model only ever writes a reply. The harness is everything that acts on that reply.

You built the smallest possible harness in Phase 1's agent loop lesson, and a host in Phase 9. This phase builds the full set.

Worked example

What a model does alone

A model only returns text and requests. Without a harness, a request to read a file is nothing but data. Here's the same scripted reply with and without one.

def model(messages):
    if len(messages) == 1:
        return {"stop_reason": "tool_use", "tool": "read_file", "input": "notes.txt"}
    return {"stop_reason": "end_turn", "text": "The notes say: ship on Friday."}

FILES = {"notes.txt": "ship on Friday"}

# No harness: one call, and the request goes nowhere.
print("alone:", model(["What do my notes say?"]))

# A harness runs the tool and goes round again.
messages = ["What do my notes say?"]
while True:
    reply = model(messages)
    if reply["stop_reason"] == "end_turn":
        break
    messages.append(FILES[reply["input"]])
print("with a harness:", reply["text"])
It runs right here in your browser, with nothing to install.

The engine is the same in both. All the doing, like reading files, keeping the conversation and deciding when it's over, comes from the code around it.

Try it now

Step through it. The list starts with one message and ends with four. The model never touches a file: the harness did that, then wrote the result down.

Three meanings of "harness"

A horse's harness and a climber's harness are both gear around something, keeping it under control. The word turns up in software in three related senses:

  • A test harness runs code under controlled conditions and checks the results. This academy has one: harness.py runs your exercises and their checks.
  • An evaluation harness runs a model or agent across a benchmark of tasks and scores it, such as EleutherAI's lm-evaluation-harness. The eval harness lesson builds one for agents.
  • An agent harness is the subject of this phase: the runtime that turns a model into an agent.

They share an idea: a harness is the controlled environment around the thing being run.

Quick check
A coding agent keeps forgetting what it did an hour ago in a long task. Is that the model's problem or the harness's?
  1. Neither: agents can't do long tasks at all, so it should be split up by hand
  2. Only the model's: it needs more parameters to remember what it did an hour ago
  3. The operating system's: it clears the agent's memory when the task runs long
  4. Mostly the harness's: carrying work across a long task (memory, notes, context) is its job
Show the answer

Mostly the harness's: carrying work across a long task (memory, notes, context) is its job

A model only sees what the harness puts in its context. Keeping notes, summaries and plans there is harness work.

In your own words
What does the model do in one call, and what does the harness do around it?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: a harness you can script

So why build one yourself? Because every one of these is made of the parts in this phase. To configure them well, debug them when they misbehave, add what's missing, or build a harness for a domain no product covers, you need to know what's inside.

A design rule: inject the model

Pilots train in flight simulators, because they can practice an engine failure there at no risk or cost. Make the model a parameter of the harness: a function that takes messages and tools and returns a response. Production passes a function that calls the API. Tests pass a scripted model that returns prepared responses in order. Then every part of the harness can be tested quickly, cheaply and deterministically, which is how the rest of this phase works.

Worked example

Testing what you can't easily trigger

How do you test what your harness does when the model asks for a file that doesn't exist? With a real model, you'd have to coax it. With a scripted one, you write the reply yourself.

def run(model, tools):
    messages = [{"role": "user", "content": "go"}]
    while True:
        reply = model(messages)
        if reply["stop_reason"] == "end_turn":
            return messages
        try:
            result = {"content": tools[reply["tool"]](reply["input"])}
        except FileNotFoundError as err:
            result = {"content": str(err), "is_error": True}
        messages.append({"role": "user", "content": result})

script = iter([{"stop_reason": "tool_use", "tool": "read", "input": "missing.txt"},
               {"stop_reason": "end_turn"}])
def scripted(messages):
    return next(script)

def read(path):
    raise FileNotFoundError(f"No file {path}")

last = run(scripted, {"read": read})[-1]["content"]
print(last)
assert last["is_error"] is True
print("test passed, with no API call")
In the lesson you can change this and run it.

That test costs nothing, takes milliseconds and gives the same result every time. It's why this phase passes the model in as an argument.

Quick check
What does this print?
def fake_model(prompt):
    return "done"
def agent(model):
    return model("go")
print(agent(fake_model))
  1. done
  2. None
  3. go
  4. fake_model
Show the answer

done

agent calls whatever model it's given, and fake_model returns "done", so it prints done. Pass the model in as an argument and your tests can use a scripted fake.

Drill

A model you can script

Tests need a model that does exactly what you say. Write scripted(replies): return a function model(messages) that returns the next reply from the list each time it's called, records a copy of every messages list it was given in model.seen, and raises RuntimeError when it runs out.

def scripted(replies):
    def model(messages):
        return replies[0]
    return model


model = scripted(["first", "second"])
print(model([{"role": "user", "content": "hi"}]), model([]))
In the lesson, your code is checked as you write it.

The same run with a harness class

The loop gets a model, a dict of tools and an event log. Change the script in the cell below: make the first reply ask for a tool that does not exist, and read the transcript the harness writes.

Worked example

A minimal harness with a scripted model

The model is a list of prepared replies. The harness runs tools and records an event for everything that happens.

def scripted(replies):
    replies = list(replies)
    def model(messages, tools):
        return replies.pop(0)
    return model

def run(task, model, tools):
    messages = [{"role": "user", "content": task}]
    events = []
    while True:
        reply = model(messages, list(tools))
        messages.append({"role": "assistant", "content": reply["content"]})
        events.append(("model", reply["stop_reason"]))
        if reply["stop_reason"] != "tool_use":
            text = "".join(b["text"] for b in reply["content"] if b["type"] == "text")
            return text, events
        results = []
        for block in reply["content"]:
            if block["type"] == "tool_use":
                output = tools[block["name"]](**block["input"])
                events.append(("tool", block["name"]))
                results.append({"type": "tool_result", "tool_use_id": block["id"],
                                "content": str(output)})
        messages.append({"role": "user", "content": results})

model = scripted([
    {"stop_reason": "tool_use", "content": [
        {"type": "tool_use", "id": "t1", "name": "add", "input": {"a": 2, "b": 3}}]},
    {"stop_reason": "end_turn", "content": [{"type": "text", "text": "2 + 3 = 5"}]},
])
print(run("What is 2 + 3?", model, {"add": lambda a, b: a + b}))
In the lesson you can change this and run it.

Two model calls, one tool run, and an answer. Nothing here talks to a network. Swap scripted(...) for a function that POSTs to the Messages API and the same harness runs a real model. The event list is the seed of the tracing you'll add later.

Quick check
In the run above the model's first reply asks for add with a=2, b=3. What is the content of the user message the harness appends next?
  1. A second assistant message with the sum
  2. Nothing: the harness waits for the model
  3. A tool_result block with the content "5"
  4. The text "add"
Show the answer

A tool_result block with the content "5"

The harness runs the tool and appends one user message holding a tool_result block, so the model sees its own call answered.

Quick check
Why build harnesses with the model passed in as a function?
  1. Tests can use a scripted model, so every part of the harness is fast, free and repeatable to test
  2. So the model can call itself recursively, which is how it plans tasks with many steps
  3. Because the API requires the model to be passed in as a function, or it won't accept the call
  4. It makes the model smarter, since a function can add extra reasoning around each call
Show the answer

Tests can use a scripted model, so every part of the harness is fast, free and repeatable to test

It's dependency injection again. A scripted model makes behavior deterministic, so tests can check exact sequences.

Drill

Read a transcript

Write counts(messages): count the model calls (assistant messages) and the tool results (blocks of type tool_result inside user messages whose content is a list). Return {"model_calls": ..., "tool_results": ...}.

TRANSCRIPT = [
    {"role": "user", "content": "Which campaign did best?"},
    {"role": "assistant", "content": [
        {"type": "tool_use", "id": "t1", "name": "list_campaigns", "input": {}}]},
    {"role": "user", "content": [
        {"type": "tool_result", "tool_use_id": "t1", "content": "[...]"}]},
    {"role": "assistant", "content": [
        {"type": "tool_use", "id": "t2", "name": "get_stats", "input": {}},
        {"type": "tool_use", "id": "t3", "name": "get_stats", "input": {}}]},
    {"role": "user", "content": [
        {"type": "tool_result", "tool_use_id": "t2", "content": "..."},
        {"type": "tool_result", "tool_use_id": "t3", "content": "..."}]},
    {"role": "assistant", "content": [{"type": "text", "text": "Spring sale."}]},
]


def counts(messages):
    return {"model_calls": 0, "tool_results": 0}


print(counts(TRANSCRIPT))
In the lesson, your code is checked as you write it.
In your own words
Why pass the model in as a function?

Write a sentence or two, then compare it with a good answer in the lesson.

In a production harness: four ways to get one

Four common ways to get an agent running on Claude differ in who writes the loop and who runs the machine. The rows below are the ones you meet in week one of a job.

Build it, or use one

You can cook dinner from scratch, use a meal kit, heat up a ready meal or go to a restaurant. There are four common ways to get an agent running on Claude, depending on who writes the loop and who runs the machines:

approachyou writeyou get
a manual loopthe whole loop over stop_reasonfull control, no extra dependencies
the SDK's tool runner (client.beta.messages.tool_runner)your tool functionsthe loop for tools you define, with per-turn hooks; you host it
the Claude Agent SDKa prompt and optionsClaude Code's harness as a library: built-in file, bash, grep and web tools, permissions, hooks, subagents, sessions; you host it
managed agents (a hosted API)an agent config and your custom tool resultsAnthropic runs the loop and a sandbox container per session

The tool runner and the Agent SDK are easy to mix up. The tool runner is a thin helper in the normal API SDK that loops over your tools. The Agent SDK is a separate package with a full, opinionated harness and built-in tools.

Quick check
You want Claude Code's built-in file, bash and web tools, with permissions and subagents, running inside your own app. Which do you reach for?
  1. The SDK's tool runner
  2. The Claude Agent SDK
  3. A manual loop
  4. Managed agents
Show the answer

The Claude Agent SDK

The Agent SDK is Claude Code's harness as a library: built-in tools, permissions, hooks and subagents, hosted by you.

Quick check
You want Anthropic to run the agent loop and host a sandbox container for each session. Which option fits?
  1. The SDK's tool runner
  2. The Claude Agent SDK
  3. A hand-written loop
  4. Managed agents
Show the answer

Managed agents

The tool runner and the Agent SDK run on your own machines. Managed agents run the loop and the sandbox for you.

The same parts under different names

Agent frameworks compete on names, but they're built from the parts in this phase. When you meet a new one, map it onto those parts first:

the partin your own harnesswhat frameworks tend to call it
the loopwhile stop_reason == "tool_use"a runner, an executor, a graph run
toolsfunctions plus JSON schemastools, function tools, actions; MCP servers (Model Context Protocol) for shared ones
statethe messages list, plus anything you keepmemory, sessions, threads, checkpoints
control flowyour if and for around model callsgraphs (nodes and edges), crews, flows, pipelines
subagentsa function that runs a second loopsubagents, handoffs, agents as tools
permissions and hookscode that inspects inputs, outputs and tool callsguardrails, hooks, permissions, approval steps
observabilityyour log of every turntraces, tracing, observability

LangGraph's nodes and edges are control flow written as a graph. The OpenAI Agents SDK's handoffs and guardrails are the subagents and the permissions-and-hooks rows. CrewAI's crews are agents with set roles working through a list of tasks, in order or under a manager agent. And the Claude Agent SDK packages Claude Code's loop, tools, hooks and subagents. Names and APIs change between versions, so read the current docs, but the questions stay the same: who writes the loop, where state lives, and where you can put a check.

Quick check
A framework's docs describe "guardrails that run on the agent's input and output, and can stop the run". Which part of your own harness is that?
  1. The loop: the code that keeps calling the model until it stops asking for tools
  2. State: the messages and notes that the harness keeps from one turn to the next
  3. Permissions and hooks: code that inspects what goes in and out, and can stop the run
  4. Tools: the functions the model can ask your code to run on its behalf, one per call
Show the answer

Permissions and hooks: code that inspects what goes in and out, and can stop the run

Whatever it's called, a check that looks at what goes in or comes out and can halt the run is the safety-check layer, the same place your harness checks tool calls before running them.

In an engineer's week, choosing among these is the first decision, and it is usually made by who must host and own the loop. A reviewer asks the same three questions of any of them: who writes the loop, where the state lives and where a check can go.

In your own words
A framework's docs promise "guardrails" on an agent's input and output. Which part of your harness is that, and where would you check it?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 7 review cards for spaced repetition

Try a quiz question

Which of these is the model's job rather than the harness's?

  1. Choosing which tool to call next, given the conversation
  2. Running the tool's code
  3. Asking the user to approve an action
  4. Keeping the conversation within the context window

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write