Agent Harness in Agentic AI: What It Is and How to Build One in Java
-
Last Updated:
-
By: javahandson
-
Series

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.
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:
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.
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. |
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:
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.
The word “harness” became popular in early 2026. Here is a short timeline from primary sources.
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.
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.

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:
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.
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.
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:
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.
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:
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.
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:
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.
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. |
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?”
Here is what happens inside the harness, one step at a time.
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.
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.
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.
The harness adds this result to the context. If the output were huge, it would trim it first. Then it calls the model again.
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.
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.
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:
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.
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]";
}
}Let us map the code back to the harness parts we discussed:
for loop is the agent loop, and maxSteps is the step budget.tools map works as the tool registry.isReadOnly check is a guardrail. A tool that changes data is blocked until a human approves it.try-catch, tool failures turn into messages. So the model can try another approach.shorten method protects the context window from huge outputs.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.
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. |
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.
| Test | Situation | What the harness must do |
|---|---|---|
| Answers after using the tool | The model calls the tool, then answers | Return the model’s answer |
| Blocks a tool that changes data | The model wants to run issueRefund | Block it with “needs human approval” and never run the refund |
| Stops when the step budget runs out | The model keeps calling tools and never finishes | Stop after 3 steps with “Sorry, I could not finish within 3 steps.” |
| Turns a tool error into a message | The 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.
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.
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:
ToolCallingManager finds and runs the matching tools.That is exactly the loop we wrote by hand, just cleaner and better tested.
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.
Spring AI covers several harness jobs out of the box:
spring.ai.tools.throw-exception-on-error=true.returnDirect = true, a tool result goes straight to the caller instead of back to the model.ToolCallingAdvisor and override methods like doBeforeCall and doAfterCall. The docs show an example that records every tool call intent for auditing.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.
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.
Even with compaction, their agent struggled on a large app-building task. Some failures stood out:
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:
passes field. Deleting or editing tests was off limits.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. |
So how much does the harness really matter? A few public results give us a good idea.
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.
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.
You do not need a research lab to apply this. Böckeler’s article on martinfowler.com gives practical examples for coding agents:
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.
I see the same mistakes again and again in agent demos. Here are the big ones.
getPayment and getPaymentStatus will confuse the model.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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Let us quickly recap what we covered.
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.