---
title: "What is an agent harness? The code around the model · CloudSat"
description: "An agent harness is the code that turns a model into an agent: prompts, tools, permissions, context, state and stop rules. See each part and how to judge one."
url: https://cloudsat.io/learn/agent-harness-explained
updated: 2026-11-18T12:00:00Z
source: CloudSat (https://cloudsat.io/). Prices in USD.
---

[AI and machine learning](https://cloudsat.io/learn/topic/ai)

# What is an agent harness? The code around the model

An agent harness is the code that turns a model into an agent: prompts, tools, permissions, context, state and stop rules. See each part and how to judge one.

CloudSat team November 18, 2026 8 min read

A language model on its own answers one request and stops. It cannot open a file, run a test or remember yesterday. Everything that makes it an agent, from the instructions it reads to the tools it may call and the moment it decides it is done, lives in the software around it. That software is the harness. Two products built on the same model can behave very differently because their harnesses differ, so it pays to know what one contains before you pick a tool or build your own.

## A working definition

The harness is all the code between the model's API and the outside world. Each turn, it chooses what the model gets to see, which actions are allowed, how they execute and when the whole run stops. The word comes from test harnesses and wiring harnesses: a fixed structure that connects one component to everything it has to work with. The model supplies judgment. The harness supplies eyes, hands, memory and limits.

## The parts of a harness

| Part | What it does | In a coding agent |
| --- | --- | --- |
| Prompt assembly | Builds the system prompt and context from layered sources | Base instructions, `AGENTS.md` files, the tool list, environment details |
| Tools | Defines actions with names, schemas and descriptions | Read and edit files, run a shell, search, fetch a URL, MCP servers |
| Execution environment | Runs tool calls in a defined place | A working directory, a container, a remote sandbox |
| Permissions | Decides allow, ask or deny for each call | Rules by tool and argument pattern, plus approval prompts |
| Context management | Keeps the conversation inside the window | Truncated tool output, old turns compacted into summaries |
| State and memory | Carries work across turns and sessions | Session history, checkpoints, progress notes, git commits |
| Control loop | Calls the model, runs tools, decides when to stop | Turn limits, budgets, a finish signal, subagents |
| Observability | Records what happened | Transcripts, tool logs, token counts, traces |

Remove any row and you notice. Without context management, long sessions get worse as they go. Without permissions, every shell command is a bet. Without state, a crash loses the afternoon.

## Harness, scaffold, framework, SDK

The words overlap, and vendors use them loosely. A split that holds up in practice:

- **Harness:** the complete runtime around a model for one kind of work, ready to use. Claude Code, Codex CLI and OpenCode are harnesses for coding.
- **Scaffold:** the usual research and benchmark term for the agent code wrapped around a model under test. Leaderboards such as SWE-bench report results per model and scaffold pair, because the scaffold changes the score.
- **Framework:** building blocks for assembling your own harness: graphs, state, retries, integrations. LangGraph is a well-known example.
- **SDK:** a vendor's harness packaged as a library, such as the Claude Agent SDK or the OpenAI Agents SDK, so the same machinery can run inside your product.

## Why the harness moves results as much as the model

Three harness decisions shape outcomes whatever the model:

- **Tool design.** Mature harnesses give models dedicated tools for reading, searching and editing instead of leaving everything to improvised shell commands, and they report tool errors explicitly so the model can react instead of guessing.
- **What enters the context.** A 5,000-line log pasted into the prompt crowds out the instructions. The relevant 50 lines plus a file path do not.
- **How work survives the context window.** Long tasks outlast any single window, so something outside the conversation has to carry the plan.

Anthropic's engineering team described one answer to the third problem in November 2025. In its harness for long-running coding work, a first session set the project up: a feature list in JSON with every feature marked as failing, an `init.sh` script to start the app, a `claude-progress.txt` log and an initial git commit. They chose JSON for the list because the model was less likely to rewrite it wholesale. Every later session read the progress file, the git log and the feature list, ran a basic end-to-end check, then worked on one feature and left the code clean. Both kinds of session used the same model, tools and system prompt; only the opening prompt and the files around it differed.

## Two harness parts in code

The [guardrails guide](https://cloudsat.io/learn/ai-agent-loop-guardrails-for-production) builds a control loop with stop rules and checkpoints. Two other parts are just as small at their core: a registry that describes tools to the model, and a permission check that runs before any of them.

```python
import fnmatch
import json
import subprocess
from pathlib import Path

WORKSPACE = Path.cwd().resolve()
TOOLS = {}

def tool(name, description, params):
    """Register a function as a tool the model can call."""
    def wrap(fn):
        TOOLS[name] = {"fn": fn, "spec": {"type": "function", "function": {
            "name": name, "description": description,
            "parameters": {"type": "object", "properties": params, "required": list(params)}}}}
        return fn
    return wrap

@tool("read_file", "Read a UTF-8 text file inside the workspace.", {"path": {"type": "string"}})
def read_file(path):
    target = (WORKSPACE / path).resolve()
    if not target.is_relative_to(WORKSPACE):
        raise PermissionError("path is outside the workspace")
    return target.read_text(encoding="utf-8")[:20_000]

@tool("shell", "Run a shell command in the workspace and return its output.", {"command": {"type": "string"}})
def shell(command):
    done = subprocess.run(command, shell=True, cwd=WORKSPACE, capture_output=True, text=True, timeout=120)
    return f"exit {done.returncode}\n{done.stdout[-10_000:]}{done.stderr[-5_000:]}"

# Ordered rules: the last match wins
RULES = [("shell", "*", "ask"), ("shell", "git status*", "allow"), ("shell", "pytest*", "allow"),
         ("shell", "git push*", "deny"), ("read_file", "*", "allow"), ("read_file", "*.env*", "ask")]

def decide(name, args):
    target = args.get("command") or args.get("path") or ""
    effect = "ask"
    for rule_tool, pattern, rule_effect in RULES:
        if rule_tool == name and fnmatch.fnmatch(target, pattern):
            effect = rule_effect
    if name == "shell" and effect == "allow" and any(c in target for c in ";&|`$<>\n"):
        effect = "ask"   # never auto-approve chained or redirected commands
    return effect

def run_tool(name, args, interactive=True):
    effect = decide(name, args)
    if effect == "ask":
        approved = interactive and input(f"Allow {name} {json.dumps(args)}? [y/N] ").lower() == "y"
        effect = "allow" if approved else "deny"
    if effect == "deny":
        return f"DENIED by policy: {name} {json.dumps(args)}"
    try:
        return TOOLS[name]["fn"](**args)
    except Exception as exc:
        return f"ERROR {type(exc).__name__}: {exc}"

tool_specs = [t["spec"] for t in TOOLS.values()]   # pass as tools= to an OpenAI-compatible chat API
```

Three details carry most of the safety. Denials and errors go back to the model as text, so it can adjust instead of retrying blindly. In an unattended run, every ask becomes a deny. And the check for `;`, `|` and friends exists because a pattern like `git status*` would otherwise approve `git status; rm -rf ~`. Production harnesses parse the command properly; OpenCode, for one, splits compound commands and checks each part. Even then, this is a seatbelt, not a sandbox: the commands still run with the account's full rights.

## How to judge a harness before you adopt it

- **Can you see the full prompt?** You should be able to print exactly what the model receives, tool definitions and injected files included.
- **How fine are the permissions?** Per tool is the minimum. Per argument pattern, with denies that a saved approval cannot override, is better.
- **Where do commands run?** In your user account, a container or a remote sandbox, and what can that place reach on the network?
- **What happens when the context fills?** Look for truncated tool output and summaries you can read, not silent drops.
- **Can a run resume?** After a crash or a closed laptop, does the session continue or start from nothing?
- **Is the model swappable?** Some harnesses are tied to one vendor; others take any OpenAI-compatible endpoint, including your own.
- **What does it log?** Transcripts and tool calls are your audit trail and your best debugging record.

## Build or adopt

For coding, adopt one of the established agents; a great deal of tool design and permission work is already in them. For a product feature, start from an SDK so you inherit the loop, the tools and the context handling. Reach for a framework when you need an explicit workflow graph with branches and human checkpoints. Write your own only when the task is narrow, the tool set small and you need control over every token, and even then copy the parts above instead of inventing new ones.

A harness needs little compute of its own unless it also hosts the model, so a CloudSat [Cloud VPS](https://cloudsat.io/cloud-vps) from $1.98 a month can run one; a [GPU server](https://cloudsat.io/gpu-servers) matters only once the model runs on your own hardware.

## FAQ

### Is a harness the same as an agent framework?

No. A framework gives you parts for building one. A harness is the assembled, working system, built with a framework, taken from an SDK or used as a finished tool.

### Will better models make the harness irrelevant?

Unlikely. Stronger models need less hand-holding in their reasoning, but something still decides which files they may touch, what they may run, how much they may spend and what gets logged. Those are harness jobs.

### Can I swap the model under an existing harness?

Often, if the harness accepts other providers. Expect to retune: prompts, tool descriptions and limits were usually shaped around one model family, and another model may need different wording.

### Where do MCP servers fit?

MCP is a standard way to plug extra tools into a harness. The harness still decides whether each call is allowed and what happens to its output.

**Run it on CloudSat.** Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. [See plans](https://cloudsat.io/plans) or [deploy a server](https://dash.cloudsat.io/console/deploy).

## Keep reading

[All guides in AI and machine learning](https://cloudsat.io/learn/topic/ai)

- [AI agent loops in production: budgets, checkpoints, backoff](https://cloudsat.io/learn/ai-agent-loop-guardrails-for-production): AI and machine learning AI agent loops in production: budgets, checkpoints, backoff 7 min read
- [OpenCode 2 on a server: models, permissions, remote access](https://cloudsat.io/learn/opencode-2-on-a-server): AI and machine learning OpenCode 2 on a server: models, permissions, remote access 8 min read
- [Run AI agents unattended on a VPS: services, timers, limits](https://cloudsat.io/learn/run-ai-agents-unattended-on-a-vps): AI and machine learning Run AI agents unattended on a VPS: services, timers, limits 6 min read
- [Hosted AI chat or open-weight models: how to choose](https://cloudsat.io/learn/hosted-ai-chat-or-open-weight-models): AI and machine learning Hosted AI chat or open-weight models: how to choose 6 min read
