Agent Harness in Agentic AI: What It Is and How to Build One in Java

  • Last Updated:
  • By: javahandson
  • Series
img

Agent Harness in Agentic AI: What It Is and How to Build One in Java

An agent harness is everything around the model in agentic AI: the loop, tools, memory and guardrails. Learn its parts and build one in Java and Spring AI.

Everyone talks about the model. GPT, Claude, Gemini, which one is smarter this month. But when you build a real AI agent, you quickly notice something. The model is only one part of the story. The agent harness around it decides whether your agent finishes the job or gets lost after three steps.

In this article, we will understand what an agent harness is in very simple terms. We will see why the model alone is not enough. Then we will look at the main parts of a harness and walk through one agent run step by step. After that, we will build a tiny harness in plain Java 21. Finally, we will see how Spring AI gives you a ready-made harness for tool calling.

All facts here come from official sources like Anthropic, OpenAI, LangChain, Spring and martinfowler.com. You will find the links in the Further Reading section.

1. What Is an Agent Harness?

Let us start with the shortest definition. LangChain explains it as a formula: Agent = Model + Harness.

In their words, a harness is “every piece of code, configuration, and execution logic that isn’t the model itself.”

So the model thinks and suggests the next step. Everything else belongs to the harness.

That “everything else” covers a lot:

  • System prompt and instructions
  • Tools the agent can call, including MCP servers
  • The loop that keeps calling the model again and again
  • Memory, files and saved state
  • Rules about what the agent may or may not do
  • Checks that test the agent’s work
  • Logs and traces so humans can see what happened

1.1 A Simple Way to Picture It

Think of a new joiner in your team. This person is very smart but has zero access on day one. No laptop, no VPN, no database login, no idea about team rules.

The intelligence is there. However, nothing useful happens until someone gives them a desk, tools, access rights and a checklist. Someone also needs to review their first few pull requests.

The model is that smart new joiner. The harness is the desk, the laptop, the access, the checklist and the code review.

1.2 Is LangChain or Spring AI a Harness?

People argue about this, and it is a fair question. Some engineers, for example at Arize, say libraries like LangChain and LangGraph are frameworks, not harnesses. Their point is simple. A framework gives you building blocks. A harness is the finished, opinionated setup that actually runs the agent.

Claude Code is a good example of a finished harness. Anthropic’s Agent SDK docs say the SDK gives you the same tools, agent loop and context management that power Claude Code.

For this article, I will keep it practical. Say you use a framework to build the loop, tools, rules and checks. Then you are building a harness with that framework.

Interview Insight
If an interviewer asks “What is an agent harness?”, start with Agent = Model + Harness. Then list four or five concrete parts: the loop, tools, context management, guardrails and verification. A crisp definition plus examples sounds far more senior than a vague answer.

2. Why the Model Alone Is Not Enough

A large language model is basically a text-in, text-out function. You send a request and you get a response back. That is it.

On its own, a model cannot do these things:

  • Remember across calls. Every API call starts fresh unless you send the history again.
  • Run code or call APIs. The model can only ask for a tool call. Your application has to execute it.
  • Check its own work reliably. Models often feel confident even when they are wrong.
  • Stop at the right time. Without a limit, a confused agent can keep looping.
  • Follow your business rules every time. A prompt is a suggestion. Code is a guarantee.

Spring AI’s documentation puts this nicely. Even though we call tool calling a model capability, it is the application that owns the tool calling logic.

Anthropic’s long-running agent research shows the memory problem very clearly. Each new session begins with no memory of the previous one. They compare it to engineers working in shifts, where every new engineer arrives with no idea what the last shift did.

So the harness fills these gaps. It remembers, it executes, it checks, and it stops the agent when needed.

3. Where the Term “Harness Engineering” Came From

The word “harness” became popular in early 2026. Here is a short timeline from primary sources.

  • 5 February 2026: Mitchell Hashimoto, co-founder of HashiCorp, wrote “My AI Adoption Journey.” One step was called “Engineer the Harness.” His idea: whenever an agent makes a mistake, build a fix so it never makes that mistake again.
  • 11 February 2026: OpenAI published “Harness engineering: leveraging Codex in an agent-first world.” A small team built a product with no hand-written code.
  • 17 February 2026: LangChain showed how harness changes alone improved their coding agent on a benchmark.
  • 10 March 2026: LangChain published “The Anatomy of an Agent Harness.”
  • 2 April 2026: Birgitta Böckeler from Thoughtworks wrote a detailed article about harness engineering on martinfowler.com.

The idea itself is older, though. Anthropic wrote about agent loops, tool design and stopping conditions back in December 2024. The new word just gave developers a shared name for that surrounding work.

4. The Core Parts of an Agent Harness

Different teams split the harness in different ways. Still, most real harnesses have the same building blocks. Let us go through them one by one.

Agent harness architecture diagram showing the four-step agent loop around the model, with tools, memory, guardrails, context, step budget and traces as supporting parts

4.1 The Agent Loop

This is the heart of the harness. Anthropic describes agents as LLMs using tools based on environmental feedback in a loop.

In simple steps, one loop looks like this:

  1. Build the context for the model.
  2. Ask the model what to do next.
  3. If the model asks for a tool, run it.
  4. Add the result to the context and check it.
  5. Repeat until the model gives a final answer or a limit hits.

Anthropic’s Agent SDK article describes the same idea in four words: gather context, take action, verify work, repeat.

The loop also needs a way out. Anthropic recommends stopping conditions such as a maximum number of iterations. In practice, I treat a step budget as mandatory, not optional.

4.2 Tools and the Tool Registry

Tools are how the agent touches the real world. A tool could read a file, call a REST API, query a database or search the web.

The harness keeps a registry of tools. Each tool has a name, a description and an input schema. The model reads these descriptions and decides which tool to call.

Good tool design matters a lot here. Anthropic suggests putting as much effort into the agent-computer interface as we normally put into a human user interface. Clear names, clear descriptions and strict input schemas reduce wrong calls.

Many harnesses today also connect to MCP servers. MCP, or Model Context Protocol, lets an agent use external tools without custom integration code for each one.

4.3 Context Management

The context window is the model’s working memory for one call. It has a fixed size, and quality drops as it fills up. LangChain calls this “context rot,” where model quality drops as the window fills.

A good harness manages context carefully. Some common techniques:

  • Compaction: Summarise older messages when the window gets close to its limit. The Claude Agent SDK does this automatically.
  • Tool output trimming: Keep only the start and end of a huge tool output in context. Save the full output to a file.
  • Sub-agents: Give a side task to a helper agent with its own clean context. It returns only the useful result.
  • Load on demand: Load skills, docs and tool details only when the agent needs them.

4.4 Memory and State

Memory is what survives after one model call. It may live in a database, in files, or in a git repository.

LangChain calls the filesystem the most foundational primitive of a harness. Files let an agent save work, store notes and continue later. Git adds history, so the agent can roll back a bad change.

For example, many coding agents read a file like AGENTS.md at startup. It holds project rules that the agent should follow in every session.

4.5 Guardrails and Permissions

This is the part I care about most, coming from payments work. A model should never decide alone whether a refund goes out.

The harness enforces rules in code:

  • Which tools this user may call
  • Actions that need human approval
  • Commands that the harness never runs
  • Data the agent can see for this customer

Never put these rules only in the prompt. A model can ignore or misread a prompt, and attackers can use prompt injection. Code checks run every single time.

4.6 Verification and Feedback

An agent that cannot check its work will happily ship broken output. Anthropic noticed that agents tend to praise their own work, even when it is clearly mediocre.

So the harness adds checks. The Claude Agent SDK article lists three styles:

  • Rules: Clear checks like linting, tests or schema validation. Anthropic calls this the best form of feedback.
  • Visual feedback: Screenshots or renders, useful for UI work.
  • LLM as a judge: Another model scores the output. Anthropic says this is generally not very robust, so use it carefully.

Martin Fowler’s site gives a nice mental model here. Böckeler splits harness controls into guides and sensors. Guides steer the agent before it acts, like AGENTS.md or skills. Sensors catch problems after it acts, like linters or ArchUnit tests.

4.7 Observability

When an agent fails, you need to know why. Was it a bad tool description? A missing permission? A wrong retrieval result?

The harness should record every step. That means each model call, each tool call, the arguments, the result and the time taken. Without these traces, debugging an agent feels like guessing.

Interview Insight
Interviewers love asking where business rules should live, in the prompt or in the code. The safe answer: describe the rules in the prompt so the model plans well, but enforce them in the harness code. The model proposes, the harness decides.

5. How One Agent Run Moves Through the Harness

Theory is fine, but a real example makes it stick. Let us follow one question in a payments support assistant.

The user types: “Why is my payout PO-1042 delayed?”

5.1 Walking Through the Request

Here is what happens inside the harness, one step at a time.

5.1.1 The Harness Builds the Context

First, the harness collects what the model needs. It adds the system prompt, the user’s question and the list of allowed tools. It also attaches the logged-in customer ID, but only for tools, not for the model to see.

5.1.2 The Model Asks for a Tool

Next, the model reads the question and the tool list. It replies with a tool call: getPayoutStatus with payoutId = PO-1042.

Notice one thing here. The model did not call anything. It only asked.

5.1.3 The Harness Checks and Runs the Tool

Now the harness takes over. It checks that the tool exists. Then it confirms that this customer owns payout PO-1042. Only after that does it call the payout service.

The service says the payout is on hold because the bank wants a beneficiary name check.

5.1.4 The Harness Feeds the Result Back

The harness adds this result to the context. If the output were huge, it would trim it first. Then it calls the model again.

5.1.5 The Model Gives a Final Answer

This time, the model has enough facts. It replies in plain language and does not ask for any more tools. The harness sees a final answer, records the trace and ends the run.

5.2 What If the Model Asks for a Refund?

Now imagine the model had asked for a refund instead. A refund changes money, so the harness would block it until a human approves. That decision lives in code, not in the model.

6. Build a Tiny Agent Harness in Plain Java

Frameworks hide the loop from you. That is great for production but bad for learning. So let us write a very small harness in plain Java 21, with no libraries at all.

We have created a complete codebase for this agent harness, and it is available on GitHub: agent-harness-java. It is a small Maven project with the harness from this section, a demo and four easy tests. It runs on a fake model, so you do not need an API key.

Our harness will have these features:

  • A loop with a step budget
  • Tool registry
  • Permission check for write actions
  • Error handling that feeds errors back to the model
  • Output trimming to protect the context
  • A simple step log

6.1 The Model and Tool Contracts

First, we define what the model can return. It can either give a final answer or ask for a tool.

// What the model sends back: "run this tool" or "here is my final answer"
public class ModelReply {

    private final String toolName;     // set when the model wants a tool
    private final String toolInput;
    private final String finalAnswer;  // set when the model is done

    private ModelReply(String toolName, String toolInput, String finalAnswer) {
        this.toolName = toolName;
        this.toolInput = toolInput;
        this.finalAnswer = finalAnswer;
    }

    public static ModelReply callTool(String toolName, String toolInput) {
        return new ModelReply(toolName, toolInput, null);
    }

    public static ModelReply answer(String text) {
        return new ModelReply(null, null, text);
    }

    public boolean isFinalAnswer() {
        return finalAnswer != null;
    }

    public String getToolName() {
        return toolName;
    }

    public String getToolInput() {
        return toolInput;
    }

    public String getFinalAnswer() {
        return finalAnswer;
    }
}

// The model is just one part the harness talks to
public interface Model {
    ModelReply next(List<String> conversation);
}

// Something the agent can use, like "look up a payout"
public interface Tool {
    String getName();
    boolean isReadOnly();   // true = only reads data, false = changes something
    String run(String input);
}

ModelReply is a plain class. Its two static methods make the code read like English: ModelReply.callTool("getPayoutStatus", "PO-1042") or ModelReply.answer("..."). On the Tool side, isReadOnly() tells the harness whether a tool only reads data or changes something, like a refund.

The Model interface hides the real LLM API. In production, you would call OpenAI, Anthropic or a local model behind it. For learning, a fake model works fine.

6.2 The Harness Class

Now the main part. Read the run method slowly, because that is the agent loop.

public class AgentHarness {

    private static final int MAX_RESULT_LENGTH = 200;

    private final Model model;
    private final Map<String, Tool> tools = new HashMap<>();
    private final int maxSteps;

    public AgentHarness(Model model, List<Tool> toolList, int maxSteps) {
        this.model = model;
        this.maxSteps = maxSteps;
        for (Tool tool : toolList) {
            tools.put(tool.getName(), tool);
        }
    }

    public String run(String question) {
        List<String> conversation = new ArrayList<>();
        conversation.add("QUESTION: " + question);

        for (int step = 1; step <= maxSteps; step++) {
            ModelReply reply = model.next(conversation);

            if (reply.isFinalAnswer()) {
                System.out.println("step " + step + ": model gave the final answer");
                return reply.getFinalAnswer();
            }

            String result = runTool(reply);
            System.out.println("step " + step + ": " + result);
            conversation.add(result);
        }
        return "Sorry, I could not finish within " + maxSteps + " steps.";
    }

    private String runTool(ModelReply reply) {
        Tool tool = tools.get(reply.getToolName());
        if (tool == null) {
            return "ERROR: no tool named " + reply.getToolName();
        }
        if (!tool.isReadOnly()) {
            return "BLOCKED: " + tool.getName() + " needs human approval";
        }
        try {
            String output = tool.run(reply.getToolInput());
            return "RESULT from " + tool.getName() + ": " + shorten(output);
        } catch (RuntimeException e) {
            return "ERROR from " + tool.getName() + ": " + e.getMessage();
        }
    }

    private String shorten(String text) {
        if (text.length() <= MAX_RESULT_LENGTH) {
            return text;
        }
        return text.substring(0, MAX_RESULT_LENGTH) + " ...[cut]";
    }
}

6.3 What Each Part Does

Let us map the code back to the harness parts we discussed:

  • The for loop is the agent loop, and maxSteps is the step budget.
  • A tools map works as the tool registry.
  • The isReadOnly check is a guardrail. A tool that changes data is blocked until a human approves it.
  • Inside try-catch, tool failures turn into messages. So the model can try another approach.
  • The shorten method protects the context window from huge outputs.
  • The System.out.println line in the loop is a very basic trace.

Also notice the if (reply.isFinalAnswer()) check. That one line decides whether the loop ends or keeps going.

6.4 Running It With a Fake Model

You do not need an API key to test the loop. A fake model is enough to check the harness logic.

public class PayoutStatusTool implements Tool {

    public String getName() {
        return "getPayoutStatus";
    }

    public boolean isReadOnly() {
        return true;
    }

    public String run(String payoutId) {
        return payoutId + " is ON_HOLD: bank asked for beneficiary name check";
    }
}

// A fake model, so we can test the harness without any API key
public class FakeModel implements Model {

    public ModelReply next(List<String> conversation) {
        String lastMessage = conversation.get(conversation.size() - 1);

        if (lastMessage.startsWith("RESULT")) {
            return ModelReply.answer("Your payout PO-1042 is on hold. "
                    + "The bank wants to verify the beneficiary name.");
        }
        return ModelReply.callTool("getPayoutStatus", "PO-1042");
    }
}

public class Demo {

    public static void main(String[] args) {
        AgentHarness harness = new AgentHarness(
                new FakeModel(),
                List.of(new PayoutStatusTool()),
                5);   // step budget

        String answer = harness.run("Why is my payout PO-1042 delayed?");
        System.out.println(answer);
    }
}

When you run this, you get the following output:

step 1: RESULT from getPayoutStatus: PO-1042 is ON_HOLD: bank asked for beneficiary name check
step 2: model gave the final answer
Your payout PO-1042 is on hold. The bank wants to verify the beneficiary name.

This tiny class is obviously not production-ready. There is no real model, no compaction and no persistent memory. Still, it shows the most important truth. The model only suggests. The harness decides what actually happens.

Interview Insight
A common follow-up is how to stop an agent from looping forever. Mention three things. First, a step budget. Second, detection of repeated identical tool calls. Third, a clear fallback message or human handoff when the budget runs out.

6.5 Testing the Harness

A harness is only useful if it makes the right decision every single time. So the codebase on GitHub comes with four small tests. Each test plays one situation and checks what the harness does.

The tests use fake models on purpose. We are not testing how smart the model is. We are testing the code around it, and a fake model gives the same reply every time, costs nothing and needs no API key.

TestSituationWhat the harness must do
Answers after using the toolThe model calls the tool, then answersReturn the model’s answer
Blocks a tool that changes dataThe model wants to run issueRefundBlock it with “needs human approval” and never run the refund
Stops when the step budget runs outThe model keeps calling tools and never finishesStop after 3 steps with “Sorry, I could not finish within 3 steps.”
Turns a tool error into a messageThe tool throws “bank API timed out”Not crash. Pass the error back to the model so it can try another way

Notice that each row maps to a harness part from section 4: the loop and its step budget, guardrails and error handling.

To run the tests, you only need JDK 21 and Maven:

git clone https://github.com/javahandson-08/java-codebase.git
cd java-codebase/agent-harness-java
mvn test

You should see Tests run: 4, Failures: 0. A good exercise is to break the harness on purpose. For example, delete the isReadOnly check in AgentHarness and run the tests again. The refund test fails at once, because the refund now runs without a human. That is exactly why harness rules belong in code, with tests around them.

7. How Spring AI Gives You a Harness for Tool Calling

Writing your own loop is fun for learning. However, in a real Spring Boot project, you would not want to maintain it yourself. Spring AI already gives you a solid tool calling harness.

One quick version note first. Spring AI 2.0 went GA on 12 June 2026. It targets Spring Boot 4.0 and 4.1 with Spring Framework 7. If your project is still on Spring Boot 3.x, you need the Spring AI 1.x line instead, and some APIs differ.

7.1 The Tool Calling Loop in Spring AI 2.x

In Spring AI 2.x, a component called ToolCallingAdvisor owns the loop. ChatClient registers it automatically. According to the docs, the loop works like this:

  1. The advisor sends the request with all tool definitions to the model.
  2. The model decides whether to call any tools.
  3. If there are tool calls, ToolCallingManager finds and runs the matching tools.
  4. The results go back into the conversation, and the advisor calls the model again.
  5. This repeats until the model replies without any tool calls.

That is exactly the loop we wrote by hand, just cleaner and better tested.

7.2 Defining a Tool With @Tool and ToolContext

Here is our payout lookup written as a Spring AI tool. Notice how ToolContext carries the customer ID.

class PayoutTools {
 
    private final PayoutService payoutService;
 
    PayoutTools(PayoutService payoutService) {
        this.payoutService = payoutService;
    }
 
    @Tool(description = "Get the current status of a payout by its payout ID")
    PayoutStatus getPayoutStatus(
            @ToolParam(description = "Payout ID, for example PO-1042") String payoutId,
            ToolContext toolContext) {
 
        String customerId = (String) toolContext.getContext().get("customerId");
        // The service checks that this customer owns the payout
        return payoutService.findStatus(payoutId, customerId);
    }
}

And here is how you call it from a service:

String answer = chatClient.prompt()
        .user("Why is my payout PO-1042 delayed?")
        .tools(new PayoutTools(payoutService))
        .toolContext(Map.of("customerId", currentUser.id()))
        .call()
        .content();

The Spring AI docs make an important point about ToolContext. Spring AI does not send this data to the model. It stays inside your tool code. That makes it a good place for tenant IDs and user IDs, which the model should never control.

7.3 Other Harness Features You Get

Spring AI covers several harness jobs out of the box:

  • Error handling: By default, runtime exceptions from tools go back to the model as messages. You can switch this with spring.ai.tools.throw-exception-on-error=true.
  • Return direct: With returnDirect = true, a tool result goes straight to the caller instead of back to the model.
  • Hooks: You can extend ToolCallingAdvisor and override methods like doBeforeCall and doAfterCall. The docs show an example that records every tool call intent for auditing.
  • Memory and observability: Other advisors, like chat memory advisors, plug into the same chain.

Here is the auditing idea in a short form, based on the official example:

public class AuditingToolCallingAdvisor extends ToolCallingAdvisor {
 
    private final AuditService audit;
 
    // constructor and builder omitted, see the Spring AI docs
 
    @Override
    protected ChatClientResponse doAfterCall(
            ChatClientResponse response, CallAdvisorChain chain) {
        var toolCalls = response.chatResponse().getResult().getOutput().getToolCalls();
        for (var call : toolCalls) {
            audit.recordIntent(call.name(), call.arguments());
        }
        return response;
    }
}

One thing to keep in mind. The builder options listed in the ToolCallingAdvisor docs do not include an iteration cap. So plan your own protection against runaway loops, for example with a custom advisor that counts iterations.

8. Lessons From Long-Running Agents

Short tasks fit in one context window. Long tasks, like building a full web app, do not. Anthropic studied this problem in their November 2025 article on long-running agents.

8.1 The Failures They Saw

Even with compaction, their agent struggled on a large app-building task. Some failures stood out:

  • Doing too much at once. The agent tried to build everything in one go and ran out of context midway.
  • Declaring victory too early. A later session saw some progress and assumed the job was done.
  • Marking features done without testing. Unit tests or curl checks passed, but the feature did not work end to end.

8.2 The Harness Fix

Their fix was not a smarter model. It was a better harness with two roles.

The initializer agent ran once. It created an init.sh script, a claude-progress.txt log and a first git commit. It also wrote a feature list with over 200 features, all marked as failing.

After that, a coding agent handled every later session. Each session picked one feature, finished it, tested it, committed to git and updated the progress file.

A few small details made a big difference:

  • The feature list used JSON, because the model was less likely to wrongly edit JSON than Markdown.
  • The coding agent could only flip a passes field. Deleting or editing tests was off limits.
  • Browser automation through a Puppeteer MCP server helped the agent test features like a real user.

In March 2026, Anthropic went one step further. They split the work into a planner, a generator and a separate evaluator agent. The reason was simple. An agent judging its own work is too generous.

Interview Insight
If asked “How would you design an agent that works for hours?”, talk about external memory. Mention a task list, a progress file, git commits and an end-to-end check before new work. The context window is not reliable memory, so the harness must save state outside it.

9. Harness Engineering in Practice

So how much does the harness really matter? A few public results give us a good idea.

9.1 LangChain: Same Model, Better Score

LangChain improved their coding agent on Terminal Bench 2.0 from 52.8 to 66.5. They kept the model fixed and only changed the harness. That moved them from outside the Top 30 to the Top 5.

The changes included better context delivery, self-verification steps and middleware hooks. None of it touched the model weights.

9.2 OpenAI: A Product With No Hand-Written Code

OpenAI’s harness engineering article describes a five-month experiment. Their team shipped a product with roughly a million lines of code, all written by Codex agents. About 1,500 pull requests were opened and merged, with a small team of three engineers driving Codex.

Interestingly, early progress was slower than expected. The reason was not a weak model. The environment lacked clear specs. Once the team gave agents better tools, docs, logs and feedback loops, things sped up.

9.3 Guides and Sensors for Your Own Projects

You do not need a research lab to apply this. Böckeler’s article on martinfowler.com gives practical examples for coding agents:

  • Guides (before the agent acts): AGENTS.md with coding rules, skills, bootstrap scripts, OpenRewrite recipes.
  • Sensors (after the agent acts): Linters, type checks, ArchUnit tests for module boundaries, AI code review.

As Java developers, we already have many sensors. JUnit, ArchUnit, Checkstyle and SpotBugs all become part of your agent harness once the agent can run them.

10. Common Mistakes When Building an Agent Harness

I see the same mistakes again and again in agent demos. Here are the big ones.

  • No step budget. The agent loops on the same failing call and burns tokens.
  • Rules only in the prompt. Permissions and limits must live in code.
  • Dumping huge tool outputs into context. A 5 MB API response will drown the useful information.
  • Vague tool descriptions. Two tools named getPayment and getPaymentStatus will confuse the model.
  • Trusting the agent’s own “done.” Always check with tests or real validation.
  • No traces. Without step logs, you cannot debug a bad answer.
  • Swallowing tool errors. Send a clear error back so the model can try another path.
  • Letting the model pick the customer ID. Pass identity through server-side context, like Spring AI’s ToolContext.

Most of these are not AI problems at all. They are normal backend engineering problems. That is good news for us, because Java developers already know how to solve them.

11. FAQ’s on agent harness

Q: What is an agent harness in agentic AI?

A: An agent harness is all the code around the model that turns it into an agent. It includes the agent loop, tools, context management, memory, guardrails, verification and logs. LangChain sums it up as Agent = Model + Harness. The model suggests the next step, and the harness decides what actually runs.

Q: What is the difference between an agent harness and an agent framework?

A: A framework gives you building blocks, like model clients, tool APIs and memory classes. A harness is the finished setup that runs an agent with a loop, rules and checks. Claude Code is a harness. Spring AI and LangChain are frameworks you can use to build a harness.

Q: Which responsibilities belong to the harness and which belong to the model?

A: The model reads the context and proposes the next action or a final answer. The harness builds the context, runs tools, checks permissions, handles errors, trims large outputs, saves state and stops the run. In short, the model proposes and the harness decides.

Q: How do you stop an AI agent from running in an infinite loop?

A: Add a step budget, which is a maximum number of loop iterations. Also detect repeated tool calls with the same arguments. When the budget runs out, return a clear fallback message or hand the task to a human instead of silently failing.

Q: Where should business rules and permissions live in an agent system?

A: Describe the rules in the prompt so the model can plan well. But always enforce them in harness code, for example permission checks, approval steps and amount limits. A model can ignore or misread a prompt, while code checks run every single time.

Q: What is context rot and how does a harness handle it?

A: Context rot means model quality drops as the context window fills up. A harness handles it with compaction, which summarises old messages. It can also trim large tool outputs, use sub-agents with their own clean context, and load tools or docs only when needed.

Q: How do long-running agents keep progress across context windows?

A: They save state outside the context window. Anthropic’s long-running agent harness used a JSON feature list, a progress file, an init script and git commits. Each new session reads these files first, picks one unfinished feature, tests it and commits the work.

Q: How does Spring AI implement the agent loop for tool calling?

A: In Spring AI 2.x, ChatClient automatically registers a ToolCallingAdvisor. It sends tool definitions to the model, runs any requested tools through ToolCallingManager and sends the results back. The loop repeats until the model replies without tool calls.

Q: What is harness engineering?

A: Harness engineering is the work of designing the environment around an AI agent so it works reliably. It covers tools, docs, rules, tests and feedback loops. Mitchell Hashimoto described it as fixing the setup so the agent never repeats the same mistake.

12. Conclusion

Let us quickly recap what we covered.

  • An agent harness is everything around the model: the loop, tools, context, memory, guardrails, checks and traces.
  • Remember the simple formula: Agent = Model + Harness.
  • The model only suggests the next step. Your harness decides what really runs.
  • Business rules and permissions belong in harness code, not only in prompts.
  • Long-running agents need memory outside the context window, like progress files and git.
  • Public results from LangChain and OpenAI show that harness changes can matter as much as model changes.
  • In Java, Spring AI 2.x gives you a solid tool calling loop through ToolCallingAdvisor and ChatClient.

If you build agents for real users, spend as much time on the harness as on choosing the model. In my view, that is where most of the reliability comes from.

13. Further Reading

Leave a Comment