What is an agent harness? The software around the model
An agent harness is the software that turns an LLM into an agent: the loop, tools, permissions, sandbox and context management. How it works, with a Python demo.

An agent harness is the software that wraps a language model and turns it into an agent: it runs the loop that calls the model, executes the tools the model asks for, decides what goes into the context on each turn, and enforces permissions, sandboxing and limits. Claude Code, OpenAI’s Codex and the Claude Agent SDK are harnesses; the model inside them only reads tokens and writes tokens.
Theo Browne put it in one line on X this month: “Harness = thing that turns an LLM into an agent.” OpenAI uses the word the same way. Its Unrolling the Codex agent loop post (January 23, 2026) describes “the Codex harness, which provides the core agent loop and execution logic that underlies all Codex experiences”. This post takes the harness apart, piece by piece, and builds a small one in Python.
What does an agent harness do?
The harnesses that OpenAI and Anthropic document all do the same core jobs, whatever they call them.
Runs the loop. Send the context to the model, get back either text or a tool call, run the tool, append the result, repeat until the model returns a final answer or a limit is hit. OpenAI’s post calls this “the agent loop” and notes that each turn always ends with an assistant message, “which signals a termination state”.
Owns the tools. The harness decides which tools exist, how they’re described to the model, and what code actually runs. Codex’s harness “executes shell/file tools in a sandbox and wires up integrations like MCP servers and skills”, per OpenAI’s App Server post (February 4, 2026). MCP servers and Agent Skills plug into the harness, not into the model.
Assembles context. System prompt, tool definitions, project instructions such as AGENTS.md or CLAUDE.md, the conversation so far, and tool results. When the window fills, the harness compacts or truncates. This is the context engineering layer.
Enforces permissions. Which commands run without asking, which need approval, which are blocked. In Codex, the server can pause a turn and send the client an approval request; the turn waits “until the client replies with either ‘allow’ or ‘deny’”.
Sandboxes execution. Limits the files, network and processes a tool call can touch, so one bad command can’t damage the machine.
Persists sessions. Saves the transcript so a session can be resumed, forked or audited. Codex calls these threads and can create, resume, fork and archive them.
Is the harness the same as the model?
No, and the distinction matters more every month. The model is a set of weights behind an API. The harness is ordinary software that someone wrote and that you can read, configure or replace. Anthropic’s Agent SDK docs make the split explicit: the SDK gives you “the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript”. Same model, same harness, different product on top.
Two practical consequences follow.
First, a benchmark score for an agent task is a score for a model inside a particular harness. Change the tools, the prompt or the context policy and you have changed what is being measured. When a lab reports a SWE-bench or Terminal-Bench number, I look for which harness ran it before I compare it with anything.
Second, a lot of what users experience as “the model got worse” or “the model got lazy” is harness behavior: a compaction that dropped a key decision, a tool description that changed, a permission prompt that the agent routed around. Anthropic’s long-running harness post (November 26, 2025) is a good example. Their fix for agents declaring victory too early wasn’t a new model. It was a harness change: an initializer agent, a JSON feature list, a progress file and git commits between sessions.
What does a minimal agent harness look like in code?
Here is a harness with the six jobs above in about 60 lines of standard-library Python: a loop, a tool registry, a sandbox directory that the model’s paths can’t escape, an approval rule for shell commands, a step budget and a transcript. The model is a script of five canned replies so it runs offline; swap model() for a real API call and the rest stays the same.
# mini_harness.py: everything around the model that makes it an agent.
# Loop + tools + permissions + sandbox + step budget + transcript. The model is scripted.
import json, pathlib, subprocess, sys, tempfile
SANDBOX = pathlib.Path(tempfile.mkdtemp(prefix="harness-")).resolve()
MAX_STEPS = 6
ASK_FIRST = {"run"} # tools that need a human "yes"
def inside(p): # every path the model names is resolved against the sandbox
path = (SANDBOX / p).resolve()
if not path.is_relative_to(SANDBOX):
raise PermissionError(f"{p} is outside the sandbox")
return path
def write_file(path, text):
inside(path).write_text(text); return f"wrote {len(text)} bytes to {path}"
def read_file(path):
return inside(path).read_text()
def run(argv):
r = subprocess.run([sys.executable, *argv[1:]] if argv[0] == "python" else argv,
cwd=SANDBOX, capture_output=True, text=True, timeout=10)
return f"exit {r.returncode}\n{r.stdout}{r.stderr}".strip()
TOOLS = {"write_file": write_file, "read_file": read_file, "run": run}
SCRIPT = iter([ # what the model "says" on each turn
{"tool": "read_file", "args": {"path": "../../etc/passwd"}},
{"tool": "write_file", "args": {"path": "add.py", "text": "print(2 + 2)\n"}},
{"tool": "run", "args": {"argv": ["rm", "-rf", "."]}},
{"tool": "run", "args": {"argv": ["python", "add.py"]}},
{"final": "add.py prints 4"},
])
def model(transcript):
return next(SCRIPT)
def approve(call): # stand-in for a UI prompt; this "human" only allows python
return call["args"]["argv"][0] == "python"
transcript = [{"role": "user", "content": "write add.py that prints 2+2 and run it"}]
for step in range(1, MAX_STEPS + 1):
msg = model(transcript)
if "final" in msg:
print(f"step {step}: done -> {msg['final']}"); break
name, args = msg["tool"], msg["args"]
if name in ASK_FIRST and not approve(msg):
result = "denied by user"
else:
try:
result = TOOLS[name](**args)
except Exception as e:
result = f"error: {e}" # errors go back to the model, they don't crash the loop
print(f"step {step}: {name}({json.dumps(args)}) -> {result.replace(chr(10), ' | ')}")
transcript += [{"role": "assistant", "content": msg}, {"role": "tool", "content": result}]
else:
print("step budget exhausted")
print(f"transcript: {len(transcript)} messages, sandbox: {sorted(p.name for p in SANDBOX.iterdir())}")
Output (Python 3.13.11, macOS):
step 1: read_file({"path": "../../etc/passwd"}) -> error: ../../etc/passwd is outside the sandbox
step 2: write_file({"path": "add.py", "text": "print(2 + 2)\n"}) -> wrote 13 bytes to add.py
step 3: run({"argv": ["rm", "-rf", "."]}) -> denied by user
step 4: run({"argv": ["python", "add.py"]}) -> exit 0 | 4
step 5: done -> add.py prints 4
transcript: 9 messages, sandbox: ['add.py']
Everything interesting in that output happened outside the model. The path traversal at step 1 was stopped by inside(), not by the model’s good judgment. The rm -rf at step 3 was stopped by the approval rule. Both failures went back into the transcript as text, so a real model would see them and change course instead of crashing the loop.
One honest caveat: my sandbox is a path check, which stops file tools from leaving the folder but does nothing about what a shell command does once it runs. That is why the run tool needs approval here. Production harnesses add OS-level isolation (containers, operating-system sandbox profiles, network rules) because a path check alone isn’t a sandbox.
What makes one harness better than another?
From reading OpenAI’s and Anthropic’s engineering posts, the differences that show up in practice are:
- Cache discipline. OpenAI points out that the agent loop is quadratic in the JSON sent over a session, and that with cache hits “sampling the model is linear rather than quadratic”. Their MCP support once listed tools in an inconsistent order, which caused cache misses. A harness that keeps its prefix stable is cheaper and faster; I explain why in prompt caching.
- Context policy. When and how it compacts, what it keeps, and whether it can hand off to a fresh session. Get this wrong and long runs drift, locked onto plans they should have dropped.
- Tool design. Fewer, clearer tools with errors the model can act on.
- Permission model. Sensible defaults, approvals that don’t train the user to click yes on everything, and audit logs.
- Embeddability. Codex exposes its harness over a JSON-RPC App Server so IDEs and apps can drive it; Anthropic ships the Claude Code loop as the Agent SDK. A harness you can embed is one you don’t have to rewrite.
What I would do
For a product team, I would not write a harness from scratch for a coding or file-heavy agent in 2026. I’d start from the Claude Agent SDK or the Codex App Server, depending on which models the team is allowed to use, and spend the effort on the parts that are specific to the product: tools, permissions, evals. Writing the loop is an afternoon. Getting sandboxing, compaction, resumable sessions and caching right takes months, and others have already paid for that.
For a narrow workflow (classify a ticket, call two APIs, write a summary), a 60-line loop like the one above is often the right answer, and a fixed workflow with no agent loop at all may be better still. Either way, I’d log every tool call and result from day one. When something goes wrong, the transcript is the only evidence you have.
FAQ
Is Claude Code a model or a harness?
A harness. Claude Code runs Claude models inside its own loop with its own tools, permission system, context management and session storage. The Agent SDK exposes that same loop as a library.
Is LangChain an agent harness?
Frameworks like LangChain or LangGraph give you parts for building a harness: loop helpers, tool wrappers, memory. Whether you call the result a harness depends on whether it runs the loop and owns tool execution. By Theo’s definition, whatever you interface the model through is the harness.
Does the harness affect benchmark results?
Yes. An agent benchmark runs a model inside some harness, with that harness’s tools and prompts. Compare scores only when the harness is the same, or when the report says which harness each model used.
Can I swap models inside the same harness?
Often, yes. That’s the cleanest way to compare models for your own work: hold the harness, tools and task set fixed, change only the model, and measure success rate and cost per task.
Sources
- OpenAI, Unrolling the Codex agent loop, January 23, 2026
- OpenAI, Unlocking the Codex harness: how we built the App Server, February 4, 2026
- Anthropic, Agent SDK overview (read October 31, 2026)
- Anthropic, Effective harnesses for long-running agents, November 26, 2025
- Theo Browne, definition of a harness on X, October 22, 2026
- Related on this site: harness engineering