Agentic AI

Prompt Engineering vs Context Engineering vs Harness Engineering, Explained

Short answer

Prompt engineering is what you say to the model in one call. Context engineering is what the model sees at each step: retrieved data, tool results, memory and trimmed history. Harness engineering is the software around the model: the agent loop, tools, permissions, limits, error recovery, tracing and evaluation. They are nested layers, not rivals. Fix one-off wrong answers in the prompt or context; fix loops, unsafe actions and slow degradation in the harness.

Give the same AI model to two teams and you will often get two very different agents. One answers support tickets reliably for months. The other loops, forgets what it was doing, leaks a long tool output into every step and occasionally issues a refund nobody approved. The model is identical. Everything around it is not.

That "everything around it" is why three terms now show up in every agent discussion: prompt engineering, context engineering and harness engineering. They are often presented as a hype cycle where each one replaces the last. They are better understood as three layers of the same job, each answering a different question.

In this guide I define each layer in plain words, show how they fit together, explain what a harness actually contains, and build a minimal agent harness in about 100 lines of Python with real output. I also give you a checklist to work out which layer is failing when your agent misbehaves. If you have not built an agent before, read How to Build Your First AI Agent first; this guide picks up where that one stops.


What is prompt engineering?

Prompt engineering is writing the instructions for a single model call: the role, the task, examples, constraints and the output format you want back. It answers the question "what should I say to the model?"

It is still the first thing to get right. A vague instruction or a missing output format causes failures no amount of infrastructure can fix. Good prompt engineering means:

  • A clear role and task, stated once and early.
  • A few examples of good output (few-shot prompting) when the format matters.
  • Explicit rules for what to do when information is missing, such as "say you don't know".
  • A structured output format, such as JSON, that your code can check.

Prompt engineering works well when the job is one call: summarise this email, classify this ticket, rewrite this paragraph. It stops being enough when the model has to take several steps, call tools and remember what happened earlier. That is where the next two layers come in.

What is context engineering?

Context engineering is deciding what information the model sees at each step of a task: the system prompt, retrieved documents, tool results, memory and conversation history, trimmed to fit and ordered so the important parts stand out. It answers the question "what should the model see right now?"

The term took off in June 2025, when Shopify CEO Tobi Lütke and AI researcher Andrej Karpathy both said they preferred "context engineering" to "prompt engineering", a shift Simon Willison documented at the time. Anthropic's engineering team later described the goal as finding the smallest possible set of high-signal tokens that gives the model the best chance of doing the task.

Why does this need its own name? Because more context is not better context. Chroma's 2025 Context Rot report tested 18 large language models and found that performance becomes increasingly unreliable as input length grows, even on simple tasks. An agent that pastes every tool output and every previous turn into each call gets slower, more expensive and less accurate as the task goes on.

In practice, context engineering covers four kinds of decisions:

DecisionWhat it meansExample
SelectBring in only what is relevant to this stepRetrieve 3 policy passages, not the whole handbook
CompressShrink what you keepClip a 2,600-character tool result to 400; summarise old turns
PersistStore what matters outside the context windowWrite progress notes to a file and re-read them later
IsolateGive sub-tasks their own clean contextA sub-agent reads 50 documents and returns a one-paragraph summary

Anthropic's guidance names the same techniques: compaction (summarising a long history and starting fresh with the summary), structured note-taking (the agent keeps notes outside the context window), sub-agent architectures and just-in-time retrieval, where the agent holds lightweight references such as file paths and loads the content only when it needs it. Retrieval is a large part of this layer; my guides on RAG and semantic search cover it in depth.

What is harness engineering?

Harness engineering is building the software system around the model: the agent loop, the tools it can call, the permissions and approval gates, the limits on steps and spend, state and memory, error recovery, tracing and evaluation. It answers the question "what should the system allow, prevent, measure and correct?"

A simple way to remember it, a framing Martin Fowler's site credits to LangChain, is Agent = Model + Harness. Addy Osmani, writing on O'Reilly Radar, defines the harness as all the code, configuration and execution logic that is not the model itself. The model proposes actions. The harness decides whether they run, what happens when they fail, and when the whole thing stops.

The term spread in early 2026, helped by OpenAI's February 2026 post Harness engineering: leveraging Codex in an agent-first world. The team reported building and shipping a product over five months with no manually written code: about 1,500 pull requests, a team that grew from three engineers to seven, in roughly a tenth of the time they estimated hand-coding would take. Their effort went into the environment around the agent: linters and tests the agent had to pass, observability it could read, and a short AGENTS.md file used as a map of the codebase rather than a giant instruction manual.

Anthropic's engineering team describes similar work for long-running coding agents: an initializer agent that sets up the project, a progress file and a JSON feature list that each new session reads, one feature per session, and a rule that every session leaves the code in a clean, committed state. None of that is prompting. It is system design.

Prompt vs context vs harness engineering: what is the difference?

Prompt engineering shapes what you say to the model in one call, context engineering decides what the model sees at each step, and harness engineering builds the system that runs the model, controls its actions and measures the results. They are nested layers, not competing techniques: the prompt is part of the context, and the context is assembled by the harness.

Nested layers diagram. The innermost layer is prompt engineering: instructions, examples and output format for one model call. Around it is context engineering: retrieved documents, tool results, memory and trimmed history chosen for each step. The outer layer is harness engineering: the agent loop, tools, permissions and approval gates, step and cost limits, state, error recovery, tracing and evaluation. The model sits at the centre.
Each layer contains the one inside it. The harness assembles the context; the prompt is one part of the context. Tap to enlarge.
Prompt engineeringContext engineeringHarness engineering
Question it answersWhat should I say?What should the model see now?What should the system allow, prevent and measure?
ScopeOne model callEvery step of a taskThe whole running system, across many tasks
What you changeInstructions, examples, output formatRetrieval, history trimming, tool-output size, memory, sub-agentsLoop, tools, permissions, limits, retries, state, tracing, evals
Typical failureWrong format, ignores an instructionForgets the goal, misses a fact, slows down as the task growsLoops forever, takes an unapproved action, fails silently, gets worse over weeks
Who usually owns itAnyone using the modelThe developer building the agentThe engineering team running it in production
Main toolsA text editor and test inputsRetrievers, summarisers, token counters, memory storesCode, permissions, observability, test suites

A useful rule of thumb: if the agent gets something wrong once, look at the prompt and the context; if it degrades over time or does something it should never be able to do, look at the harness. An agent should not be able to issue a refund just because its prompt forgot to say "don't". That rule belongs in code.

Why does the harness matter more than the model?

Because the same model can be reliable or unreliable depending on the system around it, and the harness is the part you control. You cannot retrain a frontier model, but you can decide which tools it gets, what it sees, what needs approval and how failures are caught.

Three things push the harness to the front:

  • Agents take many steps. A small error rate per step compounds. A loop that runs 20 steps needs recovery, limits and checks that a single prompt cannot provide.
  • Agents take actions. Once a model can send emails, run SQL or move money, safety has to be enforced outside the model. Prompt rules can be overridden by a cleverly worded document; a permission check in code cannot. See Prompt Injection and AI Agent Security.
  • Models change. Anthropic's March 2026 post on harness design makes the point that every harness component encodes an assumption about what the model cannot do on its own. When a better model arrives, some scaffolding becomes unnecessary and should be removed, which is only possible if you know what each piece is for.

What does context engineering look like in practice?

In practice, context engineering is a function that runs before every model call and builds the message list from scratch: what to include, what to shorten and what to drop. Common techniques, roughly in the order you should try them:

  1. Clip tool outputs. Most context bloat comes from raw tool results: full API responses, long query results, entire web pages. Keep the fields the model needs and cut the rest.
  2. Trim old turns. Keep the system prompt and the user's original task; drop or summarise the oldest steps first. Drop a tool call and its result together so the model never sees an answer without its question.
  3. Retrieve, don't preload. Fetch documents when a step needs them instead of loading everything up front.
  4. Compact. When the history gets long, summarise it into decisions made, facts found and open questions, then continue from the summary.
  5. Take notes outside the window. Let the agent write progress to a file or database and read it back, which also lets a task survive a restart.
  6. Isolate with sub-agents. Send a messy sub-task to a separate agent with its own context and keep only its short answer. My guide on multi-agent systems covers when that is worth the cost.

Measure the effect. Log the token count of every model call. If it grows steadily through a task, your context builder is not doing its job.

What are the parts of an agent harness?

A production agent harness has eight parts: the loop, a tool registry, a context builder, permissions and approval gates, limits, state, error handling, and tracing with evaluation.

Agent harness loop diagram. A task enters the loop. The context builder assembles the system prompt, task, trimmed history and clipped tool results within a token budget. The model proposes either a final answer or a tool call. A tool call passes through the tool registry and a permission gate; risky actions go to a human for approval and denied actions return an error to the model. Allowed tools run and their result is added to history. A step and cost limit stops the loop and hands over to a human. Every step is written to a trace log used for evaluation.
The model only proposes. The harness builds the context, checks permissions, runs tools, enforces limits and logs every step. Tap to enlarge.
PartJobWithout it
Agent loopCall the model, run the action it asks for, feed back the result, repeatNo agent, just a chatbot
Tool registryDefine exactly which functions exist, with checked argumentsThe model invents tools or passes bad arguments
Context builderAssemble what the model sees each step, within a budgetContext rot, rising cost, forgotten goals
Permissions and approval gatesBlock or escalate risky actions in codeOne injected instruction away from a bad action
LimitsCap steps, tokens, time and spendInfinite loops and surprise bills
State and memoryKeep progress across steps, sessions and restartsEvery run starts from zero
Error handlingTurn tool failures into messages the model can act on; retry or stop cleanlyCrashes, or the model guessing after a silent failure
Tracing and evaluationLog every step; replay real tasks as testsYou cannot debug or prove the agent improved

Frameworks such as LangGraph, the OpenAI Agents SDK and the Claude Agent SDK give you several of these parts ready-made. You still have to decide the policies: which actions are risky, what the limits are, what to log and what counts as a pass. That decision-making is the engineering.

How do you build a minimal agent harness in Python?

A minimal harness needs a tool registry, a context builder with a token budget, a loop with a step limit, a permission gate for risky tools and a trace file. The version below is about 100 lines of plain Python with no dependencies. It runs a small customer-support agent with two tools: looking up an order and issuing a refund. Refunds above ₹2,000 need human approval.

To make the output repeatable, it uses a ScriptedModel that plays back fixed actions. To use a real LLM, replace it with a class whose next(messages) method calls your provider's chat API and returns the same JSON shape. The harness does not change.

"""A minimal agent harness: loop, tools, context builder, approval gate, limits, trace.

Run:  python3 harness.py   (no API key needed: it uses a scripted model so the output is repeatable)
Swap ScriptedModel for a real provider by implementing the same .next(messages) -> dict method.
"""
import json, time

# ---------- 1. Tools: the only things the agent can do ----------
ORDERS = {"A123": {"item": "Noise-cancelling headphones", "amount": 4999, "status": "delivered",
                   "history": ["placed", "packed", "shipped", "out for delivery", "delivered"] * 40}}

def get_order(order_id):
    return ORDERS.get(order_id, {"error": f"no order {order_id}"})

def issue_refund(order_id, amount):
    return {"refunded": amount, "order_id": order_id}

TOOLS = {
    "get_order":    {"fn": get_order,    "risky": lambda a: False},
    "issue_refund": {"fn": issue_refund, "risky": lambda a: a["amount"] > 2000},   # big refunds need a human
}

# ---------- 2. Context engineering: decide what the model sees each step ----------
def tokens(text):
    return len(text) // 4                       # rough estimate; use your provider's tokenizer in production

def clip(text, limit=400):
    return text if len(text) <= limit else text[:limit] + f" ...[clipped {len(text) - limit} chars]"

def build_context(system, history, budget=500):
    """System prompt always stays; tool outputs are clipped; oldest turns drop first when over budget."""
    msgs = [{"role": m["role"], "content": clip(m["content"]) if m["role"] == "tool" else m["content"]}
            for m in history]
    while msgs and tokens(system) + sum(tokens(m["content"]) for m in msgs) > budget:
        if len(msgs) < 3:
            break                               # never drop the user's task
        del msgs[1:3]                           # drop the oldest action + tool-result pair together
    return [{"role": "system", "content": system}] + msgs

# ---------- 3. Harness engineering: the loop and its guardrails ----------
SYSTEM = ("You are a support agent for an online store. Use tools to look things up; never guess order data. "
          "Reply with JSON: {\"tool\": name, \"args\": {...}} or {\"answer\": text}.")

def run_agent(task, model, approve, max_steps=5, trace_file="trace.jsonl"):
    history = [{"role": "user", "content": task}]
    with open(trace_file, "a") as trace:
        for step in range(1, max_steps + 1):
            ctx = build_context(SYSTEM, history)
            action = model.next(ctx)
            log = {"ts": round(time.time()), "task": task, "step": step,
                   "ctx_tokens": sum(tokens(m["content"]) for m in ctx), "action": action}
            if "answer" in action:
                trace.write(json.dumps({**log, "result": "done"}) + "\n")
                return action["answer"], step
            name, args = action.get("tool"), action.get("args", {})
            if name not in TOOLS:                                   # unknown tool: tell the model, don't crash
                result = {"error": f"unknown tool {name}"}
            elif TOOLS[name]["risky"](args) and not approve(name, args):
                result = {"error": "denied: needs human approval"}  # the gate, enforced in code, not in the prompt
            else:
                result = TOOLS[name]["fn"](**args)
            trace.write(json.dumps({**log, "result": result if len(json.dumps(result)) < 200 else "<large>"}) + "\n")
            history += [{"role": "assistant", "content": json.dumps(action)},
                        {"role": "tool", "content": json.dumps(result)}]
    return "Stopped: step limit reached. Handing over to a human.", max_steps

# ---------- 4. A scripted model so the demo is deterministic ----------
class ScriptedModel:
    """Plays back a fixed list of actions. Replace with a real LLM call that returns the same JSON shape."""
    def __init__(self, actions):
        self.actions, self.seen = list(actions), []
    def next(self, messages):
        self.seen.append(messages)
        return self.actions.pop(0) if self.actions else {"tool": "get_order", "args": {"order_id": "A123"}}

def human_says_no(name, args):
    print(f"   [approval gate] {name}({args}) -> DENIED")
    return False

if __name__ == "__main__":
    open("trace.jsonl", "w").close()
    runs = {
        "1. Status question": ("Where is my order A123?", [
            {"tool": "get_order", "args": {"order_id": "A123"}},
            {"answer": "Order A123 (Noise-cancelling headphones) was delivered."}]),
        "2. Risky refund": ("Refund order A123 in full.", [
            {"tool": "get_order", "args": {"order_id": "A123"}},
            {"tool": "issue_refund", "args": {"order_id": "A123", "amount": 4999}},
            {"answer": "A refund of Rs 4,999 needs a manager's approval. I've flagged it for review."}]),
        "3. Stuck in a loop": ("Has A123 shipped yet?", []),   # model keeps calling the same tool
    }
    for label, (task, script) in runs.items():
        model = ScriptedModel(script)
        answer, steps = run_agent(task, model, approve=human_says_no)
        last = model.seen[-1]
        full = 1 + 2 * (len(model.seen) - 1)                    # user task + (action, result) per earlier step
        print(f"{label}\n   task:    {task}\n   answer:  {answer}\n   steps:   {steps}")
        print(f"   last step: model saw {len(last) - 1} of {full} history messages (+ system), "
              f"~{sum(tokens(m['content']) for m in last)} tokens")
    raw = json.dumps(get_order("A123"))
    print(f"\nget_order output: {len(raw)} chars raw, {len(clip(raw))} chars after clip()")
    lines = open("trace.jsonl").read().splitlines()
    print(f"\ntrace.jsonl: {len(lines)} steps logged. Last entry:\n   {lines[-1][:160]}...")

Running python3 harness.py prints this (timestamps will differ):

1. Status question
   task:    Where is my order A123?
   answer:  Order A123 (Noise-cancelling headphones) was delivered.
   steps:   2
   last step: model saw 3 of 3 history messages (+ system), ~164 tokens
   [approval gate] issue_refund({'order_id': 'A123', 'amount': 4999}) -> DENIED
2. Risky refund
   task:    Refund order A123 in full.
   answer:  A refund of Rs 4,999 needs a manager's approval. I've flagged it for review.
   steps:   3
   last step: model saw 5 of 5 history messages (+ system), ~192 tokens
3. Stuck in a loop
   task:    Has A123 shipped yet?
   answer:  Stopped: step limit reached. Handing over to a human.
   steps:   5
   last step: model saw 7 of 9 history messages (+ system), ~400 tokens

get_order output: 2651 chars raw, 424 chars after clip()

trace.jsonl: 10 steps logged. Last entry:
   {"ts": 1795315987, "task": "Has A123 shipped yet?", "step": 5, "ctx_tokens": 400, "action": {"tool": "get_order", "args": {"order_id": "A123"}}, "result": "<lar...

Each run shows one layer doing its job:

  • Run 1, context engineering: the order lookup returns 2,651 characters, mostly a repeated status history. clip() cuts it to 424 before the model sees it, so the second call costs about 164 tokens instead of roughly 700.
  • Run 2, harness engineering: the model asks for a ₹4,999 refund. The permission gate, which is code rather than a prompt instruction, sends it to a human, who says no. The model receives an error, not a refund, and tells the customer it needs approval.
  • Run 3, both: a confused model keeps calling the same tool. The context builder drops the oldest action and result pair once the budget is exceeded (the model sees 7 of 9 history messages), and the step limit stops the loop at 5 and hands over to a human instead of running up a bill.

Every step is also written to trace.jsonl with the context size, the action and the result. That file is what you replay as test cases later. My guide AI Agents That Work shows how to turn traces into a repeatable evaluation suite.

What to add before production

  • Argument validation for every tool, using a schema, before the function runs.
  • A real tokenizer instead of the four-characters-per-token estimate.
  • Compaction of dropped turns into a summary, rather than discarding them.
  • Retries with backoff for flaky tools, and timeouts on every call.
  • Spend limits per task and per day, not only step limits.
  • Persistent state, so a task can resume after a crash.
  • Least-privilege credentials for each tool, so the harness cannot do more than the task needs.

How do you tell which layer is failing?

Match the symptom to the layer: one-off wrong answers point to the prompt or context, while loops, unsafe actions and slow degradation point to the harness. Use this table when debugging.

SymptomMost likely layerFirst fix to try
Output in the wrong formatPromptAdd an example and a strict output schema
Ignores a clear instructionPrompt or contextMove the instruction up; check it is not buried under long tool output
Makes up a fact it should have looked upContextCheck retrieval returned the right passage; add an "I don't know" path
Forgets the original goal halfway throughContextAlways keep the task in context; trim tool output; compact history
Gets slower and more expensive as the task growsContextLog tokens per call; clip and summarise
Calls the same tool again and againHarnessStep limit; detect repeated calls; return clearer tool errors
Takes an action nobody approvedHarnessPermission gate in code; least-privilege tool credentials
Fails silently or crashes on a tool errorHarnessTurn errors into messages the model can act on; add retries and timeouts
Quality drops over weeks with no code changeHarnessTrace every run; replay real tasks as regression tests; monitor pass rates
You cannot explain why it did somethingHarnessLog the full context and action at every step

Where do agent skills, MCP and agent frameworks fit?

They are building blocks for the context and harness layers, not separate disciplines.

  • MCP (Model Context Protocol) standardises how a harness connects to tools and data sources, so you do not write a custom integration for every system. It belongs to the harness's tool registry. See MCP Explained.
  • Agent Skills are an open format, originally developed by Anthropic, for packaging instructions and resources an agent can load on demand. A skill is a folder with a SKILL.md file whose name and description the agent reads at startup; the full instructions load only when a task needs them. That is context engineering by design: many skills available, very little context used. I compare skills, MCP and tools in detail in Agent Skills vs MCP vs Tools.
  • AGENTS.md and similar files give coding agents a short, stable map of a repository. OpenAI's harness engineering post recommends keeping it a table of contents rather than a manual.
  • Frameworks such as LangGraph or the agent SDKs from OpenAI and Anthropic provide the loop, state, tracing and multi-agent plumbing. They save time but do not choose your policies for you.

When is a full harness overkill?

When a single, well-written prompt already does the job, or when the agent cannot take any action with real consequences. Harnesses add code, latency and maintenance, and every component is a bet about what the model cannot do on its own.

Hugo Bowne-Anderson's July 2026 O'Reilly piece, Stop Overengineering Your Agent Harness, makes this case well: small, readable agents often beat elaborate ones, and scaffolding built for last year's model can get in the way of this year's. A practical order of work:

  1. Get the prompt right on a set of real examples.
  2. Add context engineering when the task needs data or several steps.
  3. Add harness pieces one failure at a time: a step limit after the first loop, an approval gate before the first risky tool, tracing before the first real user.
  4. Review the harness when you change models, and delete what is no longer needed.

Is harness engineering a real job skill?

Yes, though it usually appears in job descriptions under other names: AI engineer, agent engineer, applied AI engineer or forward-deployed engineer. The skills behind it are what separate a demo from a system people rely on:

  • Designing tools with clear names, narrow scopes and checked arguments
  • Building context pipelines: retrieval, trimming, summarisation and memory
  • Writing permission and approval logic, and thinking like an attacker about prompt injection
  • Instrumenting agents with traces, and turning real failures into regression tests
  • Measuring cost, latency and reliability, not just whether one answer looked right

If you are an analyst or engineer moving into this work, my agentic AI skills roadmap lays out a six-month plan that covers all three layers.

What are the most common mistakes?

  • Fixing harness problems with prompts. "Never issue refunds over ₹2,000" in a system prompt is a suggestion. The same rule in code is a guarantee.
  • Pasting every tool output into context. Raw API responses are the biggest source of context bloat.
  • No step or spend limit. Every agent loop needs a hard stop and a hand-off to a human.
  • Dropping the user's task when trimming history. The agent then optimises for whatever it saw last.
  • No traces. Without a log of what the model saw and did at each step, debugging is guesswork.
  • Testing once. Agents are not deterministic. Run each test task several times and track the pass rate.
  • Building the full harness on day one. Add components in response to real failures, and remove them when a better model makes them unnecessary.
  • Treating the three terms as rivals. You need all three, in proportion to what the agent does.

Checklist: is your agent harness ready?

  • The prompt states the role, task, output format and what to do when information is missing
  • The model's output is parsed and validated, and malformed output is handled
  • The user's task stays in context on every step
  • Tool outputs are clipped or summarised before the model sees them
  • Old history is trimmed or compacted within a token budget, and tokens per call are logged
  • Every tool is in an explicit registry with checked arguments
  • Risky actions are blocked or sent for approval in code, not by prompt instruction
  • Tool credentials have the least privilege the task needs
  • Step, token, time and spend limits stop the loop and hand over to a human
  • Tool errors become messages the model can act on; flaky tools retry with backoff
  • Progress is saved so long tasks can resume
  • Every step is traced with context size, action and result
  • Real tasks are replayed as regression tests, several runs each
  • The harness is reviewed when the model changes, and unneeded parts are removed

Sources and further reading

Key takeaways

  • Prompt engineering is what you say, context engineering is what the model sees, harness engineering is the system that runs it.
  • The three are nested layers: the harness builds the context, and the prompt is part of the context.
  • More context is not better context. Clip tool outputs, trim history and keep the task in view.
  • Rules that must never be broken belong in harness code, not in the prompt.
  • A minimal harness is a loop, a tool registry, a context builder, a permission gate, limits and a trace: about 100 lines.
  • Add harness pieces one real failure at a time, and remove them when better models make them unnecessary.

Frequently asked questions

What is harness engineering in AI?

Harness engineering is building the software system around an AI model so it works reliably as an agent: the loop that calls the model and runs tools, the tool definitions, permission checks and approval gates, step and cost limits, state and memory, error recovery, tracing and evaluation.

What is an agent harness in simple words?

An agent harness is everything in an AI agent except the model. The model suggests the next action; the harness decides whether that action is allowed, runs it, feeds the result back, stops the loop when needed and records what happened.

What is the difference between context engineering and prompt engineering?

Prompt engineering is writing the instructions for a single model call. Context engineering is deciding everything the model sees at each step of a task, including retrieved documents, tool results, memory and conversation history, and keeping it small and relevant. The prompt is one part of the context.

What is the difference between context engineering and harness engineering?

Context engineering decides what information the model sees. Harness engineering builds the whole system around the model, including the loop, tools, permissions, limits, recovery, tracing and tests. The harness is what assembles the context, so context engineering is one job inside it.

Is prompt engineering dead?

No. Clear instructions, examples and output formats are still the first thing to get right, and a weak prompt causes failures no system can fix. Prompt engineering is now one layer of building agents rather than the whole job.

What is context rot?

Context rot is the drop in a language model's reliability as its input gets longer. Chroma's 2025 study of 18 models found performance became increasingly unreliable as input length grew, which is why agents should keep context small and relevant rather than pasting in everything.

What are the main parts of an agent harness?

An agent loop, a tool registry with checked arguments, a context builder with a token budget, permission checks and approval gates for risky actions, limits on steps, tokens and spend, state and memory, error handling with retries, and tracing that feeds an evaluation suite.

Do I need a framework like LangGraph to build an agent harness?

No. A minimal harness is about 100 lines of plain Python. Frameworks such as LangGraph, the OpenAI Agents SDK or the Claude Agent SDK help with state, tracing and multi-agent workflows, but you still decide the policies: which actions are risky, what the limits are and what counts as success.

How do I know if my agent problem is a context or a harness problem?

If the agent gets something wrong once, such as missing a fact or ignoring an instruction, check the prompt and context first. If it loops, takes an action it should not be able to take, fails silently or gets worse over weeks, the fix belongs in the harness.

How do agent skills relate to context engineering?

Agent Skills package instructions and resources in a folder with a SKILL.md file. The agent reads only each skill's name and description at startup and loads the full instructions when a task needs them, so many skills are available while using very little context.


Make your agent reliable

Most agent failures I review are not model failures. They are a missing step limit, a tool output that floods the context, or a rule that lives in the prompt instead of the code. If you want help reviewing your agent's prompt, context and harness, or training your team to build all three layers, let's talk.

Next read: AI Agents That Work: How to Build, Evaluate and Secure Them

Book a free call →