You don't design an AI harness all at once, you grow it from observed failures. Anthropic recommends starting simple and adding complexity only when the simple approach falls short. Mitchell Hashimoto supplies the engine: every time the agent errs, you engineer a permanent fix. Then you systematize into guides and sensors.
Note: "AI harness" here is the software concept — the infrastructure around an LLM that turns it into a reliable agent — not harness.io (the CI/CD platform) nor the literal harness/wiring sense of the word.
Start simple, add complexity only when you need it
The first step isn't wiring up a multi-step agent. It's the smallest prompt that solves the problem. Anthropic, in "Building Effective Agents" (December 2024), is direct: start with simple prompts and add multi-step agentic systems only when simpler solutions fall short. The reason is practical. You don't know where the agent will fail until you run it, and every piece of complexity you add before seeing a real failure is a bet. Build the minimum, run it, and let the failures tell you what to engineer.
The error-to-rule loop is the engine
This is where the harness grows. Hashimoto describes the loop like this: anytime you find the agent makes a mistake, you stop and engineer a solution so the agent never makes that mistake again ("My AI Adoption Journey"). It isn't fixing it by hand and moving on. It's turning the failure into a permanent rule. In practice, each line in your AGENTS.md or CLAUDE.md is based on a bad behavior you saw. The rules file isn't written in one sitting, it's the accumulated record of everything that has gone wrong.
The five steps, in order
| Step | What to do | In the code |
|---|---|---|
| 1. Agent loop | Ask the model for an action, run it, return the result, and repeat until the final answer, with a step limit | Harness.run with max_steps |
| 2. Tools | Plain functions with a schema the model can see; each returns a dict, even when it fails | validate_zip, invoice_due_date, cancel_invoice |
| 3. Context and memory | The full history within a task; only question and final answer across tasks; rules persist in a file | history and rules.json |
| 4. Guardrail | Decide before running: known tool, valid arguments, and human approval for a destructive action | guardrail() blocks cancel_invoice without approval |
| 5. Log and eval | Each step becomes a record; cases you write give pass or fail, each with a fresh harness | Harness.log and evaluate() |
Systematize into guides and sensors
After a few cycles the patterns show up, and that's when you systematize. Birgitta Böckeler (Thoughtworks) gives the two build primitives (martinfowler.com, April 2026): guides, which direct the agent before it acts (rules, allowed tools), and sensors, which give feedback afterward (tests, linters, typecheck the agent reads). Hashimoto reinforces the sensor side: give the agent fast, high-quality tools that automatically tell it when it's wrong. Atlan proposes one more step, a "data layer", as the third stage of the sequence (guides, sensors, data layer). Worth noting that Atlan is a data-catalog company, so that step is self-interested, not neutral consensus. Guides and sensors are the core; the rest depends on your context. In the code below, the guides are the system prompt with its learned rules, plus the guardrail. The sensors are each tool result, the log, and the eval.
Running the example
Create a virtual environment, save the code from the next section as harness.py, and run it. There are no external dependencies, and the file makes no network calls.
python3 -m venv .venv
source .venv/bin/activate
python harness.pyThe complete code
This is the whole file, the same one that produced the output shown further down.
"""Minimal AI harness in Python: agent loop, tools, context, memory,
guardrails, log, and eval. Python 3.11+, standard library only.
The model here is a deterministic FAKE (no network, no key, no cost).
It exists to run the harness end to end. It is not an LLM, and the output
of this file does not measure the quality of any model.
"""
import inspect
import json
import re
import tempfile
from dataclasses import dataclass
from datetime import date, timedelta
from pathlib import Path
from typing import Protocol
# --- 1. Tools: plain functions, with what the model may ask for -----------
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
CANCELED: list[str] = [] # state of the "system" that the destructive tool changes
def validate_zip(zip_code: str) -> dict:
"""Checks the format only (5 digits, or ZIP+4). Does not check that the ZIP exists."""
zip_code = str(zip_code)
if re.fullmatch(r"\d{5}(-?\d{4})?", zip_code.strip()):
d = re.sub(r"\D", "", zip_code)
return {"valid": True, "formatted": d if len(d) == 5 else f"{d[:5]}-{d[5:]}"}
return {"valid": False, "error": "ZIP code must be 5 digits, or ZIP+4 as 00000-0000"}
def invoice_due_date(issued: str, net_days: int) -> dict:
"""Issue date + payment terms. On a weekend, also returns the next Monday. Ignores holidays."""
try:
due = date.fromisoformat(issued) + timedelta(days=net_days)
except (TypeError, ValueError, OverflowError):
return {"error": "issued must be a real date in YYYY-MM-DD format and net_days an integer"}
out = {"due": due.isoformat(), "day": DAYS[due.weekday()]}
if due.weekday() >= 5:
out["next_business_day"] = (due + timedelta(days=7 - due.weekday())).isoformat()
return out
def cancel_invoice(invoice_id: str) -> dict:
CANCELED.append(invoice_id)
return {"canceled": invoice_id}
TOOLS = {f.__name__: f for f in (validate_zip, invoice_due_date, cancel_invoice)}
STR = {"type": "string"}
SCHEMAS = [ # what the model sees of each tool (JSON Schema format)
{"name": "validate_zip", "description": validate_zip.__doc__,
"input_schema": {"type": "object", "properties": {"zip_code": STR}, "required": ["zip_code"]}},
{"name": "invoice_due_date", "description": invoice_due_date.__doc__,
"input_schema": {"type": "object", "required": ["issued", "net_days"], "properties": {
"issued": {"type": "string", "description": "YYYY-MM-DD"}, "net_days": {"type": "integer"}}}},
{"name": "cancel_invoice", "description": "Cancels an invoice. Destructive: requires human approval.",
"input_schema": {"type": "object", "properties": {"invoice_id": STR}, "required": ["invoice_id"]}},
]
# --- 2. Guardrail: decides BEFORE execution, and does not grade -----------
def guardrail(name: str, args: dict, approved: frozenset[str]) -> str | None:
if name not in TOOLS:
return f"unknown tool: {name}"
try:
inspect.signature(TOOLS[name]).bind(**args)
except TypeError:
return f"invalid arguments for {name}"
if name == "cancel_invoice" and name not in approved:
return "cancel_invoice requires human approval"
return None
# --- 3. Model client: the only part you swap for production ---------------
class ModelClient(Protocol):
def complete(self, system: str, messages: list[dict], tools: list[dict]) -> dict:
"""Returns {"type": "final", "text": ...} or
{"type": "tool_call", "id": ..., "name": ..., "args": {...}}."""
# --- 4. The harness: loop, context, memory, and log -----------------------
class Harness:
def __init__(self, model: ModelClient, memory: Path, max_steps: int = 5, max_history: int = 4):
self.model, self.memory = model, memory
self.max_steps, self.max_history = max_steps, max_history
self.history: list[dict] = [] # only question and final answer of earlier tasks
self.log: list[dict] = []
self.rules: list[str] = json.loads(memory.read_text()) if memory.exists() else []
def system(self) -> str:
base = "You are a billing assistant. Use the tools; never make up data."
return base + "".join(f"\nRule: {r}" for r in self.rules)
def run(self, text: str, approved: frozenset[str] = frozenset()) -> str:
user = {"role": "user", "content": text}
msgs = [*self.history, user]
for step in range(1, self.max_steps + 1):
resp = self.model.complete(self.system(), msgs, SCHEMAS)
if resp["type"] == "final":
self.log.append({"step": step, "event": "answer", "text": resp["text"]})
pair = [user, {"role": "assistant", "content": resp["text"]}]
self.history = [*self.history, *pair][-2 * self.max_history:]
return resp["text"]
msgs.append({"role": "assistant", "tool_call": resp})
blocked = guardrail(resp["name"], resp["args"], approved)
if blocked:
result = {"error": f"blocked: {blocked}"}
else:
result = TOOLS[resp["name"]](**resp["args"])
if "error" in result: # a tool error becomes a persistent rule
self.learn(f"{resp['name']}: {result['error']}")
self.log.append({"step": step, "event": "tool", "name": resp["name"],
"args": resp["args"], "result": result})
msgs.append({"role": "tool", "tool_call_id": resp["id"], "content": json.dumps(result)})
return "step limit reached" # a loop with no ceiling is an agent with no end
def learn(self, rule: str) -> None:
if rule not in self.rules:
self.rules.append(rule)
self.memory.write_text(json.dumps(self.rules))
# --- 5. FAKE model: routes by regex. Swap it for a real client ------------
class FakeModel:
def __init__(self, stuck: bool = False):
self.stuck, self.n = stuck, 0
def complete(self, system, messages, tools):
if self.stuck: # simulates a model that never gives a final answer
return self.call("validate_zip", {"zip_code": "0"})
last = messages[-1]
if last["role"] == "tool":
return {"type": "final", "text": self.write(json.loads(last["content"]))}
text = last["content"]
if m := re.search(r"zip\D*([\d-]+)", text, re.I):
return self.call("validate_zip", {"zip_code": m[1]})
if m := re.search(r"invoice.*?(\d{4}-\d{2}-\d{2}).*?(\d+) days", text, re.I):
return self.call("invoice_due_date", {"issued": m[1], "net_days": int(m[2])})
if m := re.search(r"cancel\w* .*?invoice (\w+)", text, re.I):
return self.call("cancel_invoice", {"invoice_id": m[1]})
return {"type": "final", "text": "I can't help with that."}
def call(self, name, args):
self.n += 1
return {"type": "tool_call", "id": f"call_{self.n}", "name": name, "args": args}
@staticmethod
def write(r: dict) -> str:
if "error" in r:
return f"I couldn't: {r['error']}."
if "formatted" in r:
return f"Valid ZIP code: {r['formatted']}."
if "canceled" in r:
return f"Invoice {r['canceled']} canceled."
extra = f" (next business day: {r['next_business_day']})" if "next_business_day" in r else ""
return f"Due on {r['due']}, {r['day']}{extra}."
# --- 6. Eval: cases you wrote, each with a fresh harness ------------------
@dataclass
class Case:
name: str
text: str
calls: list[str] # tools that must have been requested, in order
contains: str # expected snippet in the final answer
approved: frozenset[str] = frozenset()
stuck: bool = False
CASES = [
Case("valid zip", "Validate ZIP 94105", ["validate_zip"], "94105"),
Case("invalid zip", "Validate ZIP 9410", ["validate_zip"], "5 digits"),
Case("invoice due on a weekend", "Invoice issued 2026-10-23, due in 30 days", ["invoice_due_date"], "next business day: 2026-11-23"),
Case("cancel without approval", "Cancel invoice INV123", ["cancel_invoice"], "human approval"),
Case("cancel with approval", "Cancel invoice INV123", ["cancel_invoice"], "canceled", frozenset({"cancel_invoice"})),
Case("out of scope", "What's the weather tomorrow?", [], "can't help"),
Case("stuck loop", "anything", ["validate_zip"] * 5, "step limit", stuck=True),
]
def evaluate() -> list[dict]:
rows = []
for c in CASES:
CANCELED.clear()
with tempfile.TemporaryDirectory() as tmp:
h = Harness(FakeModel(c.stuck), Path(tmp) / "rules.json")
answer = h.run(c.text, c.approved)
requested = [e["name"] for e in h.log if e["event"] == "tool"]
ok = requested == c.calls and c.contains in answer
if c.name == "cancel without approval": # the side effect must not have happened
ok = ok and CANCELED == []
rows.append({"case": c.name, "ok": ok, "answer": answer})
return rows
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
memory = Path(tmp) / "rules.json"
h = Harness(FakeModel(), memory)
h.run("Validate ZIP 9410")
for line in h.log:
print(json.dumps(line))
print("memory:", memory.read_text())
print("system in a new session:", repr(Harness(FakeModel(), memory).system().splitlines()[-1]))
print("---")
rows = evaluate()
for r in rows:
print(("ok " if r["ok"] else "FAIL"), r["case"], "->", r["answer"])
print(f"{sum(r['ok'] for r in rows)}/{len(rows)} cases passed")
raise SystemExit(0 if all(r["ok"] for r in rows) else 1)Tools: plain functions with a schema
The tools are small billing tasks a support agent might handle. The Portuguese version of this guide uses Brazilian equivalents (a CEP postal code and a boleto payment slip). This version uses a ZIP code and an invoice due date instead, with the same structure.
validate_zip checks the format only: five digits, or ZIP+4. It doesn't know whether the ZIP code exists, and the description says so, because the model reads the description to decide when to call the tool. Anthropic's documentation calls the description the most important factor in tool performance and asks that it cover limits and what the tool doesn't return.
invoice_due_date adds the payment terms to the issue date and, if the result falls on a Saturday or Sunday, also returns the next Monday. Holidays are left out on purpose, and the description makes that clear. cancel_invoice is the destructive tool, and it exists so the guardrail has something to block. Every tool returns a dict, even when it fails, so the error goes back to the model as data and not as an exception.
The loop and the step limit
Harness.run is the loop. It calls the model. If the model asks for a tool, the request goes through the guardrail, the tool runs, the result is appended, and the model is called again. If the model returns a final answer, the loop returns it. max_steps keeps the loop from running forever. In the eval's "stuck loop" case, the fake model never answers, and the harness stops at step five with step limit reached.
Context and memory
Within a task, msgs holds everything: the question, the tool requests, and the results. Across tasks, history keeps only the question and the final answer, capped at the last max_history tasks. Dropping the tool traffic of old tasks keeps the context small. It also avoids leaving a tool request without its result, which the Anthropic API rejects, because the tool_result block has to come right after the matching tool_use. For how this context layer relates to RAG and to the rest of the harness, see harness vs context engineering vs RAG.
Memory is a separate thing. The rules.json file stores rules learned from tool errors, and system() injects them into every new session, as the output shows. The fake model ignores those rules. A real model reads them, and that is where the error-to-rule loop closes.
Guardrail: it blocks first and doesn't grade
guardrail runs before any execution and answers whether the action may happen, not whether it was good. It refuses an unknown tool, arguments that don't match the function signature, and cancel_invoice without human approval, which is passed in approved. In the eval, the "cancel without approval" case also checks the side effect: CANCELED has to stay empty. This is a minimal example. In a real system, the guardrail also looks at amounts, destinations, and the user's permissions. The difference between a guardrail and an eval is covered in guardrails and evals for AI agents.
Log: one record per step
Harness.log is a list of dicts, one per step, with the tool, the arguments, and the result. main prints each one as a line of JSON, a format any log collector can read. In production, add a timestamp, a task ID, and a duration. I left those out so the output below is always the same. The log is also what the eval reads to know which tools were requested.
Eval: pass or fail, not a benchmark
Each Case has the input text, the tools that must be requested, in order, and a snippet expected in the answer. evaluate runs each case with a fresh harness and fresh memory, so one case can't contaminate another. The invoice case uses an issue date of October 23, 2026 and 30-day terms, which lands on Sunday, November 22, 2026, so it requires the next Monday, November 23.
These are seven handwritten cases, and the result is a count of how many passed. This is not a benchmark. There is no sample, the model is fake, and the result only proves that the harness behaves the way you wrote it. To check that the eval catches a regression, I disabled the approval check in the guardrail. The "cancel without approval" case failed and the result was 6 of 7.
Actual output of python harness.py, on Python 3.13.5, with no network and no API key
{"step": 1, "event": "tool", "name": "validate_zip", "args": {"zip_code": "9410"}, "result": {"valid": false, "error": "ZIP code must be 5 digits, or ZIP+4 as 00000-0000"}}
{"step": 2, "event": "answer", "text": "I couldn't: ZIP code must be 5 digits, or ZIP+4 as 00000-0000."}
memory: ["validate_zip: ZIP code must be 5 digits, or ZIP+4 as 00000-0000"]
system in a new session: 'Rule: validate_zip: ZIP code must be 5 digits, or ZIP+4 as 00000-0000'
---
ok valid zip -> Valid ZIP code: 94105.
ok invalid zip -> I couldn't: ZIP code must be 5 digits, or ZIP+4 as 00000-0000.
ok invoice due on a weekend -> Due on 2026-11-22, Sunday (next business day: 2026-11-23).
ok cancel without approval -> I couldn't: blocked: cancel_invoice requires human approval.
ok cancel with approval -> Invoice INV123 canceled.
ok out of scope -> I can't help with that.
ok stuck loop -> step limit reached
7/7 cases passedSwapping the fake model for Claude
Only ModelClient.complete changes. Anthropic documents the cycle. The response arrives with stop_reason set to tool_use and tool_use blocks that carry id, name, and input. You reply in a user message with a tool_result block that repeats the tool_use_id. The adapter below translates the harness format to that format and uses the official anthropic SDK. Set ANTHROPIC_API_KEY in the environment and pass a model ID from the official list.
"""Swap the FAKE for Claude. Requires: pip install anthropic and ANTHROPIC_API_KEY."""
import anthropic
class ClaudeClient:
def __init__(self, model: str, client: anthropic.Anthropic | None = None):
self.model = model # use a model ID from Anthropic's official list
self.client = client or anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
def complete(self, system: str, messages: list[dict], tools: list[dict]) -> dict:
resp = self.client.messages.create(
model=self.model, max_tokens=1024, system=system, tools=tools,
messages=[self._translate(m) for m in messages],
# the harness handles one tool per step
tool_choice={"type": "auto", "disable_parallel_tool_use": True},
)
for block in resp.content:
if block.type == "tool_use":
return {"type": "tool_call", "id": block.id, "name": block.name, "args": block.input}
return {"type": "final", "text": "".join(b.text for b in resp.content if b.type == "text")}
@staticmethod
def _translate(m: dict) -> dict:
if m["role"] == "tool":
return {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": m["tool_call_id"], "content": m["content"]}]}
if "tool_call" in m:
c = m["tool_call"]
return {"role": "assistant", "content": [
{"type": "tool_use", "id": c["id"], "name": c["name"], "input": c["args"]}]}
return {"role": m["role"], "content": m["content"]}The SDK also has the Tool Runner, which runs the tool loop for you. The manual loop in this guide gives explicit control over the guardrail, the log, and the step limit, and Anthropic's documentation points to the manual loop when you need control over how tools run.
I tested the adapter with anthropic SDK 2.3.0 against a mocked HTTP transport, with no network and no key. The harness finished a task in two calls, and the second request carried the expected tool_result. I didn't run it against the real API, so expect to adjust details such as the model ID and API error handling. The equivalent OpenAI pattern is in its function calling documentation.
What this file doesn't do
It doesn't call a real model, has no timeouts or API error handling, doesn't write the log anywhere, and doesn't validate the free text the model returns. Memory only stores tool-error rules and doesn't stop the error from repeating if the model ignores the rule. No cost, latency, or accuracy is measured. If you need a number, measure it on your own set, with your own model, and state the size of the set.
Sources
The API facts and practices cited here come from these documents, accessed on October 27, 2026. The pages change, so check the current version.
- Anthropic: Building Effective Agents
- Claude docs: Handle tool calls
- Claude docs: Define tools
- Claude docs: Tool Runner (SDK)
- Anthropic Python SDK (GitHub)
- OpenAI: function calling
- Mitchell Hashimoto: My AI Adoption Journey
- Birgitta Böckeler: Harness engineering (martinfowler.com)
Where it comes ready (and where it has to be built)
You don't have to build the coding layer from scratch. For development, the error-to-rule loop, the guides, and the sensors already ship inside capivaOS, the open-source harness on top of Claude Code: a spec-first pipeline with mandatory tests and a state machine. It installs as a plugin and you start today. But the harness that pays off most is rarely the coding one, it's the operational harness: the same pattern applied to running your business. Nobody installs that ready-made, it's designed from your own failures, and it's the starting point of our strategic diagnosis. The account of how it gets built in production is in AI Harness in Practice.
Frequently asked questions
How do I build an AI harness from scratch?▼
Start with the smallest prompt that solves the problem and run it. When the agent errs, turn each failure into a permanent rule instead of fixing it by hand (Hashimoto's error-to-rule loop). The Python code on this page does that with a fake model, a guardrail, and a pass/fail eval, and runs without an API key. After a few cycles, systematize the rules into guides and sensors. Anthropic recommends that order: simple first, complexity only when needed.
Why start simple instead of designing everything up front?▼
Because you don't know where the agent will fail until you run it. Anthropic ("Building Effective Agents", December 2024) recommends starting with simple prompts and adding multi-step systems only when the simple approach falls short. Complexity added before seeing a real failure is a bet. The observed failures tell you what to engineer.
What is the error-to-rule loop?▼
It's the engine of the harness, described by Mitchell Hashimoto in "My AI Adoption Journey". Every time the agent makes a mistake, you engineer a solution so it never makes that mistake again. Each line in your CLAUDE.md or AGENTS.md is based on a bad behavior you observed. The rules file is the accumulated record of failures you've fixed.
What goes into guides and sensors?▼
Guides direct the agent before it acts: operating rules, CLAUDE.md, the list of allowed tools. Sensors give feedback afterward: tests, linters, and typecheck the agent can read and use to self-correct. The taxonomy is Birgitta Böckeler's (Thoughtworks, on Martin Fowler's site, April 2026). Hashimoto adds that the feedback tools need to be fast and high-quality.
Do I need a "data layer" to build a harness?▼
Atlan puts a data layer as the third step, after guides and sensors. But Atlan is a data-catalog company, so that step is self-interested, not neutral consensus. The core of any harness is guides and sensors plus the error-to-rule loop. A data layer may make sense in your context, but it isn't required to start.
Can I use a ready-made harness instead of building one?▼
For the coding layer, yes. capivaOS is an open-source harness on top of Claude Code, with a spec-first pipeline, mandatory tests, and the correction loop already built in, installed as a plugin. It handles development. The operational layer, the harness that runs the business, still has to be designed on your own stack, and that's where a strategic diagnosis comes in.
You don't design the harness. You grow it, one failure at a time.