All chapters
  1. Start hereAn agent is a model call in a loop
  2. Chapter 1One call: what a model is from the outside
  3. Chapter 2The loop: where a call becomes an agent
  4. Chapter 3The abstraction ladder: six rungs over one call
  5. Chapter 4The eight jobs of a harness
  6. Chapter 5Context: deciding what the model sees
  7. Chapter 6Tools: what the model may ask for, and where it runs
  8. Chapter 7MCP: one way to plug tools into any harness
  9. Chapter 8RAG: retrieval is context assembly
  10. Chapter 9Control flow and state: stopping, pausing and resuming
  11. Chapter 10Guardrails: identity, approval and the output contract
  12. Chapter 11Reliability and cost: retries, budgets and the failures that will happen
  13. Chapter 12Observability and evals: knowing what the agent did, and whether it was right
  14. Chapter 13Many agents: more loops, and what each one costs
  15. Adopt · 1SDKs: the same loop in Python, TypeScript and Java
  16. Adopt · 2Coding harnesses: a finished harness for software work
  17. Adopt · 3Frameworks and graph runtimes: the loop as a library
  18. Adopt · 4Managed platforms: someone else runs the loop
  19. Adopt · 5Build your own: a whole harness in one file
  20. DecideBuild or adopt: who runs each job?
  21. ReferenceGlossary
  22. AboutAbout this site
Adopt · 1

SDKs: the same loop in Python, TypeScript and Java

A provider SDK wraps the HTTP call; an agent SDK wraps the loop and several of the eight jobs. The same tool loop in three languages, then what the Claude Agent SDK takes over.

The quote agent works. It is about thirty lines of Python that speak raw HTTP, and for the Naples email it returns a decision: quote, high premium band, flood zone AE. Now it has to leave the laptop, and it has two places to go.

The service that will run it in production is written in Java. The broker portal, where a broker watches a quote being prepared, is written in TypeScript. Neither team wants to copy urllib calls by hand into another language. So the first proposal in the room is the obvious one: use the vendor's SDK.

Then a second engineer says something that sounds like the same proposal. "Use the Agent SDK. It has the loop, permissions and sessions built in." The lead of the Java service asks one question: is there one for Java? Nobody in the room knows, and nobody can say whether these are two names for one thing.

They are two different things, and the difference decides what each team still has to write.

A provider SDK translates one HTTP request into your language. An agent SDK brings a harness with it. The first leaves the loop and all eight jobs with you, in every language. The second takes several jobs over, in the languages it is published for, and asks for a process to live in.

1. Two libraries that share one word#

The ladder placed both on rungs. Rung 2 is the provider SDK: the model vendor's own client library, which wraps the call. Rung 3 is the agent SDK: a library that wraps the loop. Between them sits a small helper inside the provider SDK that runs the loop for you and nothing else. So there are three places to stand.

Diagram: Three places to stand · what each library takes over, and what stays with you

Read each column from top to bottom. The top box is what the library does for you. The box under it is what you still write or decide. The top row grows from left to right. The bottom row never becomes empty. Click any box.

  1. Provider SDK · rung 2
    1. Takes over the request: Builds the HTTP request, sends the authentication and version headers, retries failed requests twice by default, and returns typed objects. It also offers streaming helpers.
    2. Still yours: the loop, all jobs: The loop, the history, and every one of the eight jobs. The library works only between the call and its reply.
  2. Tool runner · between
    1. Takes over the loop: A beta helper inside the provider SDK. It derives the tool schema from your function, calls the model, runs the functions the model asks for and sends the results back until the model stops asking.
    2. Still yours: approval, state: It runs every tool the model asks for, with no approval step. A turn limit applies only if you set one. Nothing is saved for a later run.
  3. Agent SDK · rung 3
    1. Takes over several jobs: A finished harness started from your code: the loop, built-in tools, MCP, permissions, hooks, subagents, sessions and automatic context compaction.
    2. Still yours: the policy, the host: Which tools are allowed, which limits apply, where the long-lived process runs and how it is isolated. The mechanisms are built in; the decisions are not.

Read each column from top to bottom: what the library takes over, then what is still yours. The sections below take the columns in order, with the same quote step as the example in each.

2. Rung 2: what a provider SDK is, and which ones exist#

Start with what exists, because the Java question deserves a direct answer. Anthropic's documentation, read on 2026-11-16, lists official client SDKs for seven languages: Python, TypeScript, C#, Go, Java, PHP and Ruby. It describes them as "general-purpose Messages API clients". None of the seven is marked beta. The three this page uses install like this.

LanguageInstall line, as documentedRuntime the page requires
Pythonpip install anthropicPython 3.10 or later
TypeScriptnpm install @anthropic-ai/sdkTypeScript 5.0 or later; Node.js 20 or later, among other runtimes
Javaimplementation("com.anthropic:anthropic-java:3.9.0") in Gradle, or the same coordinates in MavenJava 8 or later

So both teams have a library. What does it do for them? Go back to call_model in agent_minimal.py. That function builds a JSON body, sets three headers, opens a connection with a time limit and parses the reply. If the API answers with status 429, which means "too many requests", it raises an exception and the run ends. The provider SDK takes over exactly this function.

What you wrote at rung 1What the provider SDK does instead, per its documentation
The URL, the JSON body, the content typeBuilds the request from typed parameters
The key and the version headerReads ANTHROPIC_API_KEY from the environment and "sends the authentication, version, and content-type headers automatically"
Nothing for a failed requestRetries twice by default, with a short exponential backoff: connection errors, 408, 409, 429 and 5xx
timeout=120A default time limit of 10 minutes per request, which you can change
response["stop_reason"], a string keyTyped objects: response.stop_reason, and content blocks you can tell apart by type
One except for everythingOne error class per status: a rate limit and a bad request are different types
Nothing for partial outputStreaming helpers, covered in section 5

Every row is plumbing. None of it knows anything about insurance, and every team that calls a model would otherwise write it again. That is the whole case for rung 2.

3. The same loop in three languages#

The tabs below show the loop from agent_minimal.py, rewritten with the official SDK for each language: one tool, check_underwriting_rules, and a loop that continues until stop_reason is no longer tool_use. The code is meant to show which lines change between languages and which do not.

Each version was compiled or typechecked against the real package on 2026-11-16. That proves the class names, method names and types exist as written. It proves nothing about a model's answers: none was run against the API, and no API key was read. The miniature under examples/quote-email/ stays the only code on this site that is presented as run.

Python

Compiled against anthropic 2.9.0 today, imported, and its client constructed. Not run against the API.

import json

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY; retries twice by default

FLOOD_ZONES = {"18 gulf shore blvd, naples fl": "AE"}  # simulated data
TOOLS = [{
    "name": "check_underwriting_rules",
    "description": "Apply the underwriting rules to a property.",
    "input_schema": {
        "type": "object",
        "properties": {
            "address": {"type": "string"},
            "year_built": {"type": "integer"},
            "sqft": {"type": "integer"},
        },
        "required": ["address"],
    },
}]


def run_tool(name: str, args: dict) -> str:
    """The model asked; our code acts. Here there is only one tool."""
    zone = FLOOD_ZONES.get(args["address"].lower(), "X")
    return json.dumps({"outcome": "quote", "premium_band": "high" if zone == "AE" else "standard",
                       "reasons": [f"eligible; flood zone {zone}"]})


def agent(email: str) -> str:
    messages = [{"role": "user", "content": email}]
    while True:  # still no turn limit, no budget, no checkpoint
        response = client.messages.create(
            model="claude-opus-5-5", max_tokens=1024, tools=TOOLS, messages=messages)
        messages.append({"role": "assistant", "content": response.content})
        if response.stop_reason != "tool_use":
            return "".join(block.text for block in response.content if block.type == "text")
        results = [{"type": "tool_result", "tool_use_id": block.id,
                    "content": run_tool(block.name, block.input)}
                   for block in response.content if block.type == "tool_use"]
        messages.append({"role": "user", "content": results})

TypeScript

Typechecked in strict mode against @anthropic-ai/sdk 1.9.0 today. Not run against the API.

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic(); // reads ANTHROPIC_API_KEY; retries twice by default

const FLOOD_ZONES: Record<string, string> = { "18 gulf shore blvd, naples fl": "AE" }; // simulated data
const tools: Anthropic.Tool[] = [
  {
    name: "check_underwriting_rules",
    description: "Apply the underwriting rules to a property.",
    input_schema: {
      type: "object",
      properties: {
        address: { type: "string" },
        year_built: { type: "integer" },
        sqft: { type: "integer" }
      },
      required: ["address"]
    }
  }
];

/** The model asked; our code acts. Here there is only one tool. */
function runTool(name: string, input: unknown): string {
  const { address } = input as { address: string };
  const zone = FLOOD_ZONES[address.toLowerCase()] ?? "X";
  return JSON.stringify({
    outcome: "quote",
    premium_band: zone === "AE" ? "high" : "standard",
    reasons: [`eligible; flood zone ${zone}`]
  });
}

export async function agent(email: string): Promise<string> {
  const messages: Anthropic.MessageParam[] = [{ role: "user", content: email }];
  while (true) { // still no turn limit, no budget, no checkpoint
    const response = await client.messages.create({
      model: "claude-opus-5-5", max_tokens: 1024, tools, messages
    });
    messages.push({ role: "assistant", content: response.content });
    if (response.stop_reason !== "tool_use") {
      let text = "";
      for (const block of response.content) if (block.type === "text") text += block.text;
      return text;
    }
    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const block of response.content) {
      if (block.type === "tool_use") {
        results.push({ type: "tool_result", tool_use_id: block.id, content: runTool(block.name, block.input) });
      }
    }
    messages.push({ role: "user", content: results });
  }
}

Java

Compiled with JDK 23 against com.anthropic:anthropic-java 3.9.0 today. Not run against the API. The text block in runTool needs Java 15 or later; the SDK itself requires Java 8.

import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
import com.anthropic.models.messages.StopReason;
import com.anthropic.models.messages.TextBlock;
import com.anthropic.models.messages.Tool;
import com.anthropic.models.messages.Tool.InputSchema;
import com.anthropic.models.messages.ToolResultBlockParam;
import com.anthropic.models.messages.ToolUseBlock;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public final class QuoteAgent {
    // Reads ANTHROPIC_API_KEY; retries twice by default.
    static final AnthropicClient client = AnthropicOkHttpClient.fromEnv();

    static final Map<String, String> FLOOD_ZONES = Map.of("18 gulf shore blvd, naples fl", "AE"); // simulated data
    static final Tool RULES_TOOL = Tool.builder()
        .name("check_underwriting_rules")
        .description("Apply the underwriting rules to a property.")
        .inputSchema(InputSchema.builder()
            .properties(JsonValue.from(Map.of(
                "address", Map.of("type", "string"),
                "year_built", Map.of("type", "integer"),
                "sqft", Map.of("type", "integer"))))
            .required(List.of("address"))
            .build())
        .build();

    /** The model asked; our code acts. Here there is only one tool. */
    static String runTool(ToolUseBlock request) {
        Map<String, Object> args = request._input().convert(new TypeReference<Map<String, Object>>() {});
        String zone = FLOOD_ZONES.getOrDefault(String.valueOf(args.get("address")).toLowerCase(), "X");
        String band = zone.equals("AE") ? "high" : "standard";
        return """
            {"outcome": "quote", "premium_band": "%s", "reasons": ["eligible; flood zone %s"]}"""
            .formatted(band, zone);
    }

    static String agent(String email) {
        // The builder holds the history: every turn adds to it and sends all of it again.
        MessageCreateParams.Builder request = MessageCreateParams.builder()
            .model(Model.CLAUDE_OPUS_5_5)
            .maxTokens(1024L)
            .addTool(RULES_TOOL)
            .addUserMessage(email);
        while (true) { // still no turn limit, no budget, no checkpoint
            Message response = client.messages().create(request.build());
            request.addMessage(response);
            if (!response.stopReason().equals(Optional.of(StopReason.TOOL_USE))) {
                return response.content().stream()
                    .flatMap(block -> block.text().stream())
                    .map(TextBlock::text)
                    .collect(Collectors.joining());
            }
            List<ContentBlockParam> results = response.content().stream()
                .flatMap(block -> block.toolUse().stream())
                .map(toolUse -> ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()
                    .toolUseId(toolUse.id())
                    .content(runTool(toolUse))
                    .build()))
                .collect(Collectors.toList());
            request.addUserMessageOfContentBlockParams(results);
        }
    }
}

Switch between the tabs and compare the function agent. It makes the same four moves in every language: send the whole history, append the reply, check the stop reason, run the tools and append their results. Python and TypeScript keep the history in a list called messages. Java keeps it in the request builder, where addMessage(response) appends the model's reply and the next build() sends everything again. The tool definition is the same JSON Schema three times, written as a dictionary, an object literal and a builder.

Now compare any tab with the raw HTTP version. The headers are gone. The 429 that ended a run at rung 1 is retried by the library. A typing mistake in stop_reason is caught by an editor or a compiler before the code runs.

One line did not change at all, in any language. It is the comment on the loop.

Exactly what was checked, and howReal packages, a compiler, and a local stand-in for the API

The files were written in a scratch folder, outside this repository. Python: a virtual environment with anthropic 2.9.0; the file was compiled and imported, which constructs the client. TypeScript: tsc 7.0.2 in strict mode. Java: the jar resolved with Maven, then javac from JDK 23, which reports one unchecked-conversion warning on properties(JsonValue.from(...)), the form the documentation's own example uses.

Each loop was also pointed at a small program on the same machine that answers POST /v1/messages with two scripted replies: a tool request, then a final text. All three sent the same two request bodies, one message in the first and three in the second, and returned the same text. This exercises the loop's shape. It is not a run of the agent: no model was called, no request left the machine, and the key in the environment was a placeholder.

The tabs use max_tokens 1024, as the SDK documentation's examples do. agent_minimal.py uses 16000.

4. What rung 2 leaves with you#

The comment says: no turn limit, no budget, no checkpoint. A provider SDK does not answer it, and the reason is in what the library is. It wraps one request. Everything it does happens between the moment you call create and the moment the reply comes back. The loop is outside that window, and so is every decision the loop makes.

Ask the three questions from The ladder again. Where does the history live? In a list or a builder in your process; stop the process and the run is gone. Who decides that a tool may run? Your run_tool, which today runs whatever the model asks for. The documentation says it directly: client tools "run in your application". What stops the spending? The SDK retries one request twice. It does not count turns, and the pages read describe no spend limit for a conversation. The response carries a usage object with token counts, and adding them up is your code.

So the provider SDK removes the request plumbing in each language, and leaves the loop and all eight jobs exactly where they were. That is not a weakness to fix. The full build of the running example stands here on purpose: it calls the model through the provider SDK and writes its loops by hand, because those loops carry rules the team wants to read in its own code.

5. Streaming: the same reply, in pieces#

The portal team has a problem that the Java service does not. A broker is looking at a screen, and until now the code waits for the complete reply before it shows anything.

The API can send the reply as it is produced: the server keeps the connection open and sends a series of small events, each carrying the next piece. This is called streaming. The documented order of events is fixed: message_start, then for each content block a content_block_start, any number of content_block_delta events and a content_block_stop, then one or more message_delta events, then message_stop.

For a chat window that is enough: show each text piece as it arrives. For a harness, three things change, and each follows from the event order.

Diagram: One streamed reply that asks for a tool · the order of events

Time runs down the page. The harness sends one request and receives many small events on the same connection. Watch two things: the tool arguments arrive as pieces of text, and the stop reason arrives near the end. The harness runs the tool only after both.

  1. Harness (your loop) to Model API: One request, streaming on. The same body as before: model, tools, the whole message history. Only the way the reply travels changes.
  2. Model API to Harness (your loop): message_start. A message object with empty content. Nothing to act on yet.
  3. Model API to Harness (your loop): content_block_start: tool_use. The block's id and the tool name are known. Its input is still an empty object.
  4. Model API to Harness (your loop): content_block_delta: input_json_delta, many times. Each delta carries a fragment of the arguments as a partial JSON string. A fragment is not a complete instruction.
  5. Model API to Harness (your loop): content_block_stop. The block is complete. Only now can the fragments be joined and parsed into the arguments object.
  6. Model API to Harness (your loop): message_delta: stop_reason tool_use. The stop reason arrives here, near the end of the stream, together with the token counts.
  7. Model API to Harness (your loop): message_stop. The reply is over. The SDK helper now returns the assembled message.
  8. Harness (your loop) to Tool: run_tool(name, input). The harness decides and calls, exactly as without streaming, using the complete arguments.
  9. Tool to Harness (your loop): the tool result. The result goes into the next request, and the loop continues.

First, a tool request also arrives in pieces. Its arguments come as fragments of JSON text, in deltas of type input_json_delta. The documentation is exact about it: the deltas are "partial JSON strings, whereas the final tool_use.input is always an object". Half a JSON object is not an instruction. A harness must not run a tool until that block's content_block_stop has arrived.

Second, the stop reason comes late. It is in the message_delta event near the end of the stream, not at the start. The loop's central check, whether stop_reason is tool_use, can only run when the stream is nearly over.

Third, a stream can fail after it has started. The HTTP status was already 200 when the first event arrived, so an error such as overloaded_error can arrive as an event in the middle. Text that was already shown to the broker then belongs to a reply that never completed.

The SDK's streaming helpers handle the first two. They pass on partial text as it arrives and hand you the assembled message at the end, so the loop reads complete blocks as before. The tabs show the one call that replaces create in each loop above; nothing else in agent changes.

Python

Compiled against anthropic 2.9.0 today; adapted from the official SDK documentation. Not run.

with client.messages.stream(
        model="claude-opus-5-5", max_tokens=1024, tools=TOOLS, messages=messages) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)    # partial text, as it arrives
    response = stream.get_final_message()  # complete blocks: now the tool requests can be read

TypeScript

Typechecked against @anthropic-ai/sdk 1.9.0 today; adapted from the official SDK documentation. Not run.

const stream = client.messages
  .stream({ model: "claude-opus-5-5", max_tokens: 1024, tools, messages })
  .on("text", (text) => process.stdout.write(text)); // partial text, as it arrives
const response = await stream.finalMessage();        // complete blocks: now the tool requests can be read

Java

Compiled against anthropic-java 3.9.0 today; adapted from the official SDK documentation. Not run. It needs three more imports: com.anthropic.core.http.StreamResponse, com.anthropic.helpers.MessageAccumulator and com.anthropic.models.messages.RawMessageStreamEvent.

MessageAccumulator accumulator = MessageAccumulator.create();
try (StreamResponse<RawMessageStreamEvent> events = client.messages().createStreaming(request.build())) {
    events.stream()
        .peek(accumulator::accumulate)
        .flatMap(event -> event.contentBlockDelta().stream())
        .flatMap(deltaEvent -> deltaEvent.delta().text().stream())
        .forEach(textDelta -> System.out.print(textDelta.text())); // partial text, as it arrives
}
Message response = accumulator.message(); // complete blocks: now the tool requests can be read

There is a second reason to stream that has nothing to do with a screen. The documentation recommends the same helpers for "requests with large max_tokens values, where the SDK requires streaming to avoid HTTP timeouts". So the Java service may stream too, with nobody watching.

Streaming changes how a reply travels. It does not change what the reply is or who runs the tool.

6. The step between: the tool runner#

The three loops in section 3 are the same block, and the next project will contain that block again. That repetition is the cause the next step removes.

The provider SDK contains a helper that runs the loop. You give it your tools as ordinary functions and a first message. It calls the model, runs the functions the model asks for, sends the results back and repeats. Anthropic calls it the tool runner. The ladder counts it as the smallest form of rung 3; it gets its own section here because it takes the loop and nothing else. The documentation read today says it "handles the agentic loop, error wrapping, and type safety", that it is "in beta on every model", and that it exists in all seven SDK languages. So this step is open to the Java team.

The tabs show the quote step with it. There is no while in any of them, and the tool's schema is derived from the function or class instead of written by hand.

Python

Compiled against anthropic 2.9.0 today. Not run against the API. Beta.

import json

from anthropic import Anthropic, beta_tool

client = Anthropic()
FLOOD_ZONES = {"18 gulf shore blvd, naples fl": "AE"}  # simulated data


@beta_tool
def check_underwriting_rules(address: str, year_built: int = 0, sqft: int = 0) -> str:
    """Apply the underwriting rules to a property.

    Args:
        address: Street, city and state
        year_built: Year the house was built
        sqft: Living area in square feet
    """
    zone = FLOOD_ZONES.get(address.lower(), "X")
    return json.dumps({"outcome": "quote", "premium_band": "high" if zone == "AE" else "standard",
                       "reasons": [f"eligible; flood zone {zone}"]})


def agent(email: str) -> str:
    runner = client.beta.messages.tool_runner(
        model="claude-opus-5-5",
        max_tokens=1024,
        max_iterations=8,  # a turn limit, because you set one
        tools=[check_underwriting_rules],
        messages=[{"role": "user", "content": email}],
    )
    final = runner.until_done()  # call, run the tools, send the results, repeat
    return "".join(block.text for block in final.content if block.type == "text")

TypeScript

Typechecked against @anthropic-ai/sdk 1.9.0 and zod 4.6.7 today. Not run against the API. Beta.

import Anthropic from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";

const client = new Anthropic();
const FLOOD_ZONES: Record<string, string> = { "18 gulf shore blvd, naples fl": "AE" }; // simulated data

const checkUnderwritingRules = betaZodTool({
  name: "check_underwriting_rules",
  description: "Apply the underwriting rules to a property.",
  inputSchema: z.object({
    address: z.string().describe("Street, city and state"),
    year_built: z.number().int().optional().describe("Year the house was built"),
    sqft: z.number().int().optional().describe("Living area in square feet")
  }),
  run: async (input) => {
    const zone = FLOOD_ZONES[input.address.toLowerCase()] ?? "X";
    return JSON.stringify({
      outcome: "quote",
      premium_band: zone === "AE" ? "high" : "standard",
      reasons: [`eligible; flood zone ${zone}`]
    });
  }
});

export async function agent(email: string): Promise<string> {
  const finalMessage = await client.beta.messages.toolRunner({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    max_iterations: 8, // a turn limit, because you set one
    tools: [checkUnderwritingRules],
    messages: [{ role: "user", content: email }]
  });
  let text = "";
  for (const block of finalMessage.content) if (block.type === "text") text += block.text;
  return text;
}

Java

Compiled with JDK 23 against anthropic-java 3.9.0 today. Not run against the API. Beta. The addBeta line is copied from the documentation's Java example.

import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.helpers.BetaRunnableTool;
import com.anthropic.helpers.BetaToolRunner;
import com.anthropic.models.beta.messages.BetaMessage;
import com.anthropic.models.beta.messages.BetaTextBlock;
import com.anthropic.models.beta.messages.BetaToolResultBlockParam;
import com.anthropic.models.beta.messages.MessageCreateParams;
import com.anthropic.models.beta.messages.ToolRunnerCreateParams;
import com.anthropic.models.messages.Model;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.Map;
import java.util.stream.Collectors;

public final class QuoteRunner {
    static final AnthropicClient client = AnthropicOkHttpClient.fromEnv();
    static final Map<String, String> FLOOD_ZONES = Map.of("18 gulf shore blvd, naples fl", "AE"); // simulated data

    // The SDK derives the tool name (snake-cased class name) and the JSON Schema from this class.
    @JsonClassDescription("Apply the underwriting rules to a property.")
    static class CheckUnderwritingRules {
        @JsonPropertyDescription("Street, city and state")
        public String address;

        @JsonProperty("year_built")
        @JsonPropertyDescription("Year the house was built")
        public Integer yearBuilt;

        @JsonPropertyDescription("Living area in square feet")
        public Integer sqft;
    }

    static String applyRules(CheckUnderwritingRules input) {
        String zone = FLOOD_ZONES.getOrDefault(input.address.toLowerCase(), "X");
        String band = zone.equals("AE") ? "high" : "standard";
        return """
            {"outcome": "quote", "premium_band": "%s", "reasons": ["eligible; flood zone %s"]}"""
            .formatted(band, zone);
    }

    static String agent(String email) {
        BetaRunnableTool rules = BetaRunnableTool.of(
            CheckUnderwritingRules.class,
            input -> BetaToolResultBlockParam.Content.ofString(applyRules(input)));

        BetaToolRunner runner = client.beta().messages().toolRunner(ToolRunnerCreateParams.builder()
            .initialMessageParams(MessageCreateParams.builder()
                .model(Model.CLAUDE_OPUS_5_5)
                .maxTokens(1024L)
                .addBeta("structured-outputs-2025-11-13")
                .addTool(rules)
                .addUserMessage(email)
                .build())
            .maxIterations(8) // a turn limit, because you set one
            .build());

        BetaMessage last = null;
        for (BetaMessage message : runner) { // each iteration: one model call, then the tools it asked for
            last = message;
        }
        return last.content().stream()
            .flatMap(block -> block.text().stream())
            .map(BetaTextBlock::text)
            .collect(Collectors.joining());
    }
}

The actors have not moved. The model still only asks. The runner now does the deciding and the calling that your loop did, and your function does the work. So read closely how the runner decides.

It runs every tool the model asks for. The tool runner page describes no approval step, and it says where to go if you need one: "When you need human-in-the-loop approval, custom logging, or conditional execution, use the manual loop instead." For the read-only rules check that is fine. For the tool that sends the reply email it is not, and that tool belongs behind the loop from section 3 or behind a check inside the function.

It stops when the model stops asking, "or until it reaches max_iterations ... if you set it". The parameter exists. The pages read give no default, so a limit applies only when you write one.

It turns a failure into a message. When a tool raises an exception, the runner "catches it and returns the error to Claude as a tool result with is_error: true". The model reads the error and decides what to ask next, so an exception in your function no longer stops the run.

An observation from the compile check: where the runner kept the historySeen in the requests, not stated on the tool runner page

The tool runner page says the runner "manages conversation state for you: after each tool-call turn, it appends the assistant message and any tool results to its own message history". It does not say where that history is kept.

In the local check described in section 3, the manual loops sent the whole history on the second request. The three tool runner versions did not. Their first request carried "thread": {"type": "create"} and a beta header message-threads-2026-08-12; their second carried only the new tool result and a reference to the previous reply. That is an observation of these package versions on one day, not documented behaviour of the runner.

The feature has its own documentation page, Message threads: a thread "keeps a conversation on the server for a short time", its contents are "deleted no more than 1 hour after the thread's last use", and the page marks it as not eligible for zero data retention. The Python runner has a thread parameter; the pages read do not describe it.

A helper that removes code can also change where data lives. Before adopting one, read the request it sends.

7. Rung 3: the agent SDK brings a harness#

The tool runner removed twelve lines. An agent SDK removes far more.

The Claude Agent SDK describes itself as "the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript". Claude Code is a coding harness, the subject of the next chapter. So this library is not a larger tool runner. It is a finished harness that you start from your own code. The documentation says how: it is "a library that runs the Claude Code binary", and when your code calls query(), "the SDK spawns a separate claude CLI process and talks to it over stdio".

That answers the Java lead's question. The install lines are pip install claude-agent-sdk and npm install @anthropic-ai/claude-agent-sdk, and those are the only two.

The tabs show the quote step once more. The tool is the same function, registered as a small in-process tool server, because the Agent SDK reaches custom tools through MCP. The options then state what the earlier versions could not: which tools may run, what happens to any other request, and where the run stops.

Python

Compiled against claude-agent-sdk 0.2.182 today, imported, and its options and tool server constructed. query was not called. Documented shape.

import json
from typing import Any

from claude_agent_sdk import (ClaudeAgentOptions, ResultMessage, create_sdk_mcp_server,
                              query, tool)

FLOOD_ZONES = {"18 gulf shore blvd, naples fl": "AE"}  # simulated data


@tool("check_underwriting_rules", "Apply the underwriting rules to a property.",
      {"address": str, "year_built": int, "sqft": int})
async def check_underwriting_rules(args: dict[str, Any]) -> dict[str, Any]:
    zone = FLOOD_ZONES.get(args["address"].lower(), "X")
    verdict = {"outcome": "quote", "premium_band": "high" if zone == "AE" else "standard",
               "reasons": [f"eligible; flood zone {zone}"]}
    return {"content": [{"type": "text", "text": json.dumps(verdict)}]}


rules = create_sdk_mcp_server(name="rules", version="1.0.0", tools=[check_underwriting_rules])

options = ClaudeAgentOptions(
    mcp_servers={"rules": rules},
    allowed_tools=["mcp__rules__check_underwriting_rules"],  # may run without asking
    permission_mode="dontAsk",   # a request that would need approval is denied instead
    setting_sources=[],          # load no settings or instruction files from disk
    max_turns=6,
    max_budget_usd=0.50,
)


async def agent(email: str) -> str:
    async for message in query(prompt=email, options=options):
        if isinstance(message, ResultMessage):
            if message.subtype == "success":
                return message.result
            return f"stopped: {message.subtype}"   # for example error_max_turns
    return "no result"

TypeScript

Typechecked against @anthropic-ai/claude-agent-sdk 0.3.325 today. Not run. Documented shape.

import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const FLOOD_ZONES: Record<string, string> = { "18 gulf shore blvd, naples fl": "AE" }; // simulated data

const checkUnderwritingRules = tool(
  "check_underwriting_rules",
  "Apply the underwriting rules to a property.",
  { address: z.string(), year_built: z.number().optional(), sqft: z.number().optional() },
  async (args) => {
    const zone = FLOOD_ZONES[args.address.toLowerCase()] ?? "X";
    const verdict = {
      outcome: "quote",
      premium_band: zone === "AE" ? "high" : "standard",
      reasons: [`eligible; flood zone ${zone}`]
    };
    return { content: [{ type: "text", text: JSON.stringify(verdict) }] };
  }
);

const rules = createSdkMcpServer({ name: "rules", version: "1.0.0", tools: [checkUnderwritingRules] });

export async function agent(email: string): Promise<string> {
  for await (const message of query({
    prompt: email,
    options: {
      mcpServers: { rules },
      allowedTools: ["mcp__rules__check_underwriting_rules"], // may run without asking
      permissionMode: "dontAsk", // a request that would need approval is denied instead
      settingSources: [],        // load no settings or instruction files from disk
      maxTurns: 6,
      maxBudgetUsd: 0.5
    }
  })) {
    if (message.type === "result") {
      return message.subtype === "success" ? message.result : `stopped: ${message.subtype}`;
    }
  }
  return "no result";
}

Java

There is no official Claude Agent SDK package for Java: the documentation read on 2026-11-16 publishes it for Python and TypeScript only and says that from any other language you "run the CLI as a subprocess", so a Java team either keeps the provider SDK with its own loop or the tool runner from the sections above, or runs the agent as a separate Python or TypeScript service that the Java service calls.

Three of those option lines would have been your code at rung 2. max_turns is the turn limit. max_budget_usd stops the run on a spend estimate. The pair allowed_tools and permission_mode is an allow-list with a default of "no". Each is one line here because someone else wrote the mechanism.

The list of what the library takes over is longer than those three. The table maps each piece to the job it belongs to, in the documentation's own words.

What the Agent SDK takes overIn the documentation's wordsJob
The loop"Turns continue until Claude produces output with no tool calls, at which point the loop ends and the final result is delivered."3 Control flow
Built-in tools"Read, write, edit files, run commands, and search the web"2 Tools
MCP"Connect external tools and data sources via the Model Context Protocol"2 Tools
Permissions"Control which tools run automatically, which need approval"5 Permissions, approval
Hooks"Run custom code at key points in the agent lifecycle"5 and 3
Subagents"Spawn specialized agents for focused subtasks"3 Control flow
Sessions"Maintain context across exchanges, resume or fork later"4 State
Context compaction"When the context window approaches its limit, the SDK automatically compacts the conversation"1 Context assembly

Each row is a chapter of this site that you would otherwise write yourself. That is the real size of the proposal.

It has a price, and the price follows from what the library is. It runs a separate program, so every running agent is "a long-lived process tied to local state": the hosting page says one session maps to one subprocess, and suggests "1 GiB RAM, 5 GiB disk, and 1 CPU per agent" as a starting point. Sessions are written to the local disk of that machine unless you add a session store. The built-in tools can read files and run commands, so the same page recommends running the SDK "inside a sandboxed container", and the example above closes every door except one. Two details are easy to miss: the cost behind max_budget_usd is a client-side estimate, and the hooks page lists more events for TypeScript than for Python.

For the quote step, with one read-only tool, this is a great deal of machinery. For a task that needs to read files, run commands and work for many turns, it is machinery you would otherwise build.

8. Who runs each job at each of the three places#

The table goes job by job, with the words this site uses everywhere: YOU BUILD, BUILT IN, and "the docs do not say" where the pages read on 2026-11-16 are silent. BUILT IN means a mechanism exists. The policy is still yours: which tools, which limit, which schema.

JobProvider SDKProvider SDK with the tool runner (beta)Claude Agent SDK
1 Context assemblyYOU BUILD. You send every message on every call.BUILT IN: keeps the message history of the run; optional compaction. What goes into the first message is yours.BUILT IN: automatic compaction; loads skills and memory files from .claude folders unless you switch that off.
2 Tools, and where they runYOU BUILD. You write the schema and run the function, in your process.BUILT IN: derives the schema and calls your function, in your process.BUILT IN: built-in tools, MCP servers, in-process custom tools. Isolation is your deployment; a sandbox option exists.
3 Control flowYOU BUILD. The loop and its stop are your code.BUILT IN: the loop. A turn limit only if you set max_iterations.BUILT IN: the loop, max_turns, subagents, hooks.
4 State, memory, durabilityYOU BUILD.YOU BUILD. The pages read describe nothing that saves a run for later.BUILT IN: sessions on local disk, resume and fork; an adapter for external storage.
5 Identity, permissions, approvalYOU BUILD.YOU BUILD. The docs point to the manual loop for approval.BUILT IN: permission modes, allow and deny rules, a callback, hooks. The end user's identity: the docs do not say.
6 Output contractBUILT IN: structured outputs with a JSON Schema, with helpers per language. Checking the meaning is yours.The docs do not say for the runner itself.BUILT IN: output_format with a JSON Schema.
7 Reliability and costBUILT IN for one request: two retries, a time limit, token counts in usage. A budget across turns: YOU BUILD.As the provider SDK, and a tool error becomes a tool result. A budget: YOU BUILD.BUILT IN: max_budget_usd on an estimate, a fallback_model option. Side effects that must happen once: the docs do not say.
8 Observability and evalsBUILT IN: logging by environment variable; the Python page describes one trace span per request. Evals: YOU BUILD.The docs do not say.BUILT IN: OpenTelemetry export when you switch it on. Evals: the docs do not say.

Read the table by columns and the three libraries look like a staircase: one request, one loop, most of a harness. Read it by rows and something more useful appears. In the rows that matter most for the quote, state and approval, the middle column says YOU BUILD just as the first does. The tool runner saves the loop and nothing around it.

9. Which one, under which conditions#

None of the three is better than the others. Each fits a set of conditions, and the conditions can be stated.

Stay on the provider SDK and write the loop when the loop itself carries rules you need to read, test and change: an approval before a tool, a checkpoint after each step, a budget per quote. It is also the only one of the three that exists in all seven languages and is not in beta. The Java service is in this position.

Add the tool runner when the tools are safe to run whenever the model asks, the run is short enough to live in memory, and a turn limit you set is all the control you need. It is in beta. A read-only lookup in the portal fits.

Adopt the Agent SDK when the task needs what it brings (file and command tools, permissions, sessions, compaction) and all of these hold: your code is Python or TypeScript, you can run one long-lived process per session in an isolated container, and you are content to configure a harness instead of writing one.

One system can stand in more than one place: the portal streams a single call through the provider SDK while the Java service runs a hand-written loop. The question for each step is the one from the table: who runs each job?

What comes next#

The team can now answer the Java lead. Yes, there is an SDK for Java, and it wraps the call. The library that wraps the loop and half the jobs exists for Python and TypeScript, and it is a different kind of thing: a harness that was built for another purpose and then opened up as a library.

That purpose is software work. The same loop, with file tools, permission modes, hooks and sessions around it, is a finished product that developers use from a terminal every day. Coding harnesses reads those products as what they are: the eight jobs, already built, with a configuration file for each.