Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Harness Engineering: how to design execution environments for AI agents

Harness engineering is the practice of designing the software layer and working environment that let an AI model complete multi-step tasks, use tools, verify results and stop safely. A model alone does not provide authorization, durable state or reliable execution. This guide explains how to build those capabilities and evaluate them in coding and business agents.

AI
Published Written by Reading time 11 min read
On this page Contents: quick navigation between sections

What is harness engineering, and how does it differ from prompt engineering?

Layers of an agent system
Layer Responsibility Example check
Model Proposed action Response correctness
Context engineering Information selection Source relevance
Harness Execution and state Step limit, approval, result record
Sandbox Execution isolation Unauthorized access denied
Evals Quality assessment Independent acceptance test

There is no single normative definition. In the narrower sense, a harness controls model calls, tools, state and termination. In a broader sense, it includes the working environment: project documentation, automated checks, diagnostic feedback and architectural constraints. OpenAI's Codex case study illustrates the latter approach, but does not establish that every organization can dispense with human engineers. [1][2]

Prompt engineering shapes instructions; context engineering selects information available to a model call; harness engineering implements execution and control. Orchestration is the part of the harness that coordinates actions and components. A sandbox is a separate isolation environment. None of these terms alone describes a complete agent system. [3][4]

The agent loop and component responsibilities

A typical cycle loads state, assembles context, calls the model, validates its proposed action, executes an authorized tool and records the result. The agent can then make another decision. Separate orchestration from the model provider adapter, access policy, tool executors and state repository. Changing models should not require rewriting business rules. [2][4]

Define explicit states: pending, running, awaiting approval, completed, failed and cancelled. Enforce step, time, token, cost and concurrency limits. A model that stops calling tools has not necessarily finished its task: completion must satisfy independent acceptance criteria. Exceeding a budget means stopping and persisting state, not automatically authorizing further spending. [5]

Extend the state model with result verification and an uncertain external outcome. Reserve the maximum permitted cost before dispatch; concurrent workers must share an atomic budget reservation. Stopping the loop does not undo a completed action. On cancellation, stop scheduling new work and reconcile in-flight operations according to the tool contract. [5][19]

Tool contracts, MCP and action control

Give each tool a clear purpose, typed arguments, bounded data access and predictable error categories. Return structured results, an operation identifier and evidence of confirmed execution. A JSON schema validates shape, not authorization or business rules. Model Context Protocol (MCP) simplifies tool and data integration but does not replace access policy or the agent loop. [6][20]

Derive user and tenant identity from a trusted session, never from model-generated arguments. Separate reads, proposals and writes. Before an irreversible or costly action, show its exact parameters, recipient, effects and cost; bind approval to an immutable operation version. Changed parameters require a fresh decision, and rejection must not be bypassed through another tool. [7][8]

Related reading: the POLPROG MCP guide. [17] Use the POLPROG MCP Tool Schema Builder to validate example arguments and results against a selected specification revision. It does not replace authorization tests or calls to a real server. [18]

An approval should identify the task, approved parameters, approving identity, expiry and policy version. On resume, recheck permissions and resource state. Treat MCP tools as dependencies: approve servers and changes to their contracts rather than trusting claims that an operation is read-only. Never pass through tokens intended for another audience. [7][12][20]

Context, durable state and recovery

Persist the goal, acceptance criteria, task state, operation identifiers, test results and artifact references. The model context remains limited working memory. Retrieve documentation when needed; treat summaries as auxiliary because they can omit critical decisions. Do not send secrets or entire databases to the model merely because the context window is large. [3][9]

After interruption, restore the last committed state and reconcile the external system before retrying a write. A timeout does not prove that the action failed. Use idempotency keys where the destination supports them and reconciliation elsewhere. Do not promise exactly-once execution across system boundaries without mechanisms that actually provide it. [5][9]

In a managed architecture, separate the controller from the tool execution environment. Anthropic describes this pattern in Managed Agents: persistent session state lives outside the context window and execution workers can be replaced independently. Define a contract between layers and safe credential delivery; restoring a process does not necessarily restore unsaved files. [16]

Durable execution is not the same as durable conversation history. Persist an operation intent before dispatch and its outcome after confirmation. If the process stops between an external write and local confirmation, reuse the same idempotency key on resume. If the destination offers neither deduplication nor reconciliation, route the uncertain outcome to manual review. Protect state transitions against concurrent changes by multiple workers. [19]

Separate task working memory, persistent user facts and records of past experience. Recent Anthropic research also examines periodic memory consolidation from session records. Such a design requires provenance, expiry, correction and deletion mechanisms, and tenant isolation. Model-generated observations must not automatically become higher-trust instructions. [21]

Security: isolation, permissions and untrusted data

Apply least privilege, filesystem isolation and outbound network restrictions. Choose an isolation boundary appropriate to the threat model when executing untrusted code: a container alone does not guarantee security. Use short-lived scoped credentials, separate workspaces and resource limits. Enforce authorization on the server independently of model instructions. [4][10]

Web pages, documents, repositories and tool results may contain prompt injection. Provenance labels and instructions to ignore external commands help but are not security boundaries. Check every action before execution and recheck permissions after resuming. Do not assume one guardrail mechanism covers every tool type; coverage depends on the integration. [8][11][12]

Define access boundaries between agent processes, credential storage and downstream services. An isolated worker should not receive a general administrative key merely because it runs in a sandbox. Test denial of cross-tenant access, blocked access to unauthorized services and behavior after credential revocation. Review tool and skill updates like other software dependencies. [10][11][12]

A harness for coding agents

Keep a short repository entry point, such as AGENTS.md, linking to versioned architecture documentation, naming conventions, setup and verification commands. Instruction scope depends on the agent implementation. Enforce domain boundaries, imports and dependency rules through CI rather than relying solely on prose. [1][2]

Each task should specify the initial state, expected behavior, prohibited changes and acceptance tests. Work in a dedicated branch or worktree, make a bounded change, run appropriate unit, integration and regression tests, then present the diff for review. A worktree is not a security sandbox. Do not let an agent remove tests or change success criteria merely to pass. [1][9][13]

For long-running coding tasks, split requirements into measurable increments. Maintain a decision log, outstanding requirements and test status. Separate evaluation from implementation: acceptance criteria and regression tests must not depend on the agent's own claims. For UI work, verify actual browser behavior, error states, accessibility and mobile layouts; a screenshot alone does not demonstrate that an application works. [1][22]

Example: a support ticket agent

Suppose an agent analyzes customer tickets and drafts replies. Read tools retrieve only tickets available to the authenticated operator. The agent may draft a message, but sending requires approval of the exact text and recipient. A separate service performs the approved write with a ticket-version check. Ticket contents cannot expand the agent's permissions.

Illustrative per-task limits: 12 steps, 120 seconds and USD 0.50 in model calls. These are arbitrary design assumptions, not provider recommendations. If sending times out, reconcile the operation identifier with the sending service instead of blindly resending. Acceptance tests confirm that rejected approval, another tenant's ticket and a retry after timeout cannot cause an unauthorized send. [7][11]

Evals, observability and cost per accepted outcome

Build representative tasks and negative test cases. Grade actual end state, such as a correctly stored booking or independent test results, rather than the model's claim. Compare models, prompts, tools and harness configurations on the same tasks and repeat trials to account for variability. A model-based grader can complement deterministic tests but needs calibration against human judgments. [13]

Record task IDs, model and harness versions, policy decisions, tool calls, latency, cost and verification results. Restrict trace access and redact sensitive data. In a hypothetical test, variant A succeeds on 80 of 100 tasks for USD 40 (USD 0.50 per success); variant B succeeds on 90 for USD 63 (USD 0.70 per success). Higher success does not automatically mean lower cost. Also track policy violations, escalation rates and p95 latency; include failed attempts in costs. [13][14]

Distinguish single-attempt success from repeated reliability. Pass@k measures the chance of at least one success in k attempts; pass^k measures the chance of success in all k attempts. The former helps when selecting the best result, the latter when judging routine user-facing work. Compare versions using the same tasks and limits and a separate holdout set. Account for workers, tools, infrastructure and human review in costs. [13]

How to choose and roll out a harness

For fixed steps and deterministic rules, start with a conventional workflow and individual AI calls. A dynamic agent is justified when the next action depends on prior observations. Compare SDKs and managed services by state access, permissions, isolation, recovery, trace export and costs. Do not assume multiple agents improve every outcome: communication and coordination add cost and failure modes. [4][15]

Roll out in stages: read-only tools and controlled evaluations first, then human-approved writes, then bounded autonomy with monitoring and a stop mechanism. Version policies, evaluation sets and environment configuration; roll back harness regressions, recognizing that completed external actions may require separate compensation. Readiness means repeatable, safe outcomes within budget, not a long feature list.

Before production, define acceptance thresholds for success, cost, latency and escalation, and separate release blockers for policy violations. Test process interruption after a write, revoked approval, concurrent resume, unavailable tools and exhausted budgets. Roll out new versions on a limited task set and attach the configuration version to each run. Capture operational events without logging full prompts and responses by default. [14][23]

A well-designed harness does not eliminate model errors. It limits their consequences and makes results verifiable. Define tool contracts, trust boundaries and acceptance criteria before adding longer runs, greater autonomy or more agents. Increase complexity only when measurements justify it.

Tools for this topic

Harness Engineering AI Agents Agent Runtime Context Engineering Agent Loop MCP Sandbox Human-in-the-loop AI Evals Observability AI Security

Frequently asked questions

Is a harness an agent framework?

Not necessarily. A framework may supply the loop and integrations; the harness also includes the particular system's configuration, state, execution rules and controls.

Do I need MCP to build an agent?

No. Typed functions or proprietary APIs are sufficient. MCP is an optional interoperability layer.

Does AGENTS.md ensure code quality?

No. Combine instructions with tests, architecture checks, isolation and change review.

Does a larger context window replace durable memory?

No. Persistent state supports recovery and confirms external operations independently of conversation history.

Does a sandbox eliminate prompt injection?

No. It limits consequences; permission enforcement and data access controls are also needed.

When should I use multiple agents?

When independent work or specialization produces measurable gains that justify coordination costs and additional risks.

Sources and references

  1. OpenAI, Harness engineering↩1↩2↩3↩4
  2. OpenAI, Unrolling the Codex agent loop↩1↩2↩3
  3. Anthropic, Effective context engineering for AI agents↩1↩2
  4. OpenAI, Sandbox Agents↩1↩2↩3↩4
  5. OpenAI Agents SDK, Running agents↩1↩2↩3
  6. Anthropic, Writing effective tools for AI agents↩
  7. OpenAI Agents SDK, Human-in-the-loop↩1↩2↩3
  8. OpenAI Agents SDK, Guardrails↩1↩2
  9. Anthropic, Effective harnesses for long-running agents↩1↩2↩3
  10. OpenAI, Inside the Codex sandbox↩1↩2
  11. OWASP GenAI Security Project, Top 10 for Agentic Applications↩1↩2↩3
  12. Model Context Protocol, Security Best Practices↩1↩2↩3
  13. Anthropic, Demystifying evals for AI agents↩1↩2↩3↩4
  14. OpenAI Agents SDK, Tracing↩1↩2
  15. Anthropic, Building effective AI agents↩
  16. Anthropic, Scaling Managed Agents with stable interfaces↩
  17. POLPROG, Model Context Protocol↩
  18. POLPROG, MCP Tool Schema Builder↩
  19. Temporal, Activity Definition↩1↩2
  20. Model Context Protocol, Tools↩1↩2
  21. Anthropic, The components of agent memory↩
  22. Anthropic, Harness design for long-running application development↩
  23. OpenTelemetry, Generative AI semantic conventions↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning