الانتقال إلى المحتوى
Claude وأدوات الـ AI للبرمجةClaude API و Tool Use· 8 دقائق للقراءة

Messages API, Tool Runner, Agent SDK or Managed Agents: Picking the Right Layer

Four ways to build a Claude agent, from owning every line of the loop to letting Anthropic host it. Two questions tell you which one fits.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • Claude API
محتويات المقال

The platform team wanted a "CI doctor": an agent that reads a failing build's log, searches the repository, and proposes a fix. Two engineers spent three weeks on it, almost none of it on the doctor itself. They wrote the tool loop, JSON schemas for read_file, grep and edit_file, path checks so the agent couldn't touch files outside the repo, a cap on iterations, and a fix for the day a long log blew up the context. In review, someone asked why they hadn't used the Agent SDK, which ships those tools, permission rules and context management already.

The common misconception

"Building a Claude agent always means hand-writing the tool loop on the raw Messages API." Experienced engineers believe it for good reasons:

  • Every tool-use tutorial starts with the manual loop, because that's how the protocol works.
  • An really is a loop: call the model, run the tools it asks for, repeat until it's done.
  • Agent frameworks have burned people before, with hidden prompts, opaque retries and painful debugging.
  • Owning the loop feels like the only way to keep control of approvals, logging and cost.

The half-truth: you should understand the loop, and sometimes you should own it. But the loop is the small part. The work is in the tools, the permissions, the context that keeps growing and the machine the code runs on, and Anthropic already ships layers that own some or all of that.

What actually happens

Two questions pick the layer

Every option is a different answer to two questions: who runs the loop, and where do the tools come from and run? Everything else in the , from retries to context management, follows from those answers.

Messages API: you own everything

With the raw API you send a request, read stop_reason, run each tool_use block, send back tool_result blocks, and repeat. You decide every detail, which is exactly why the tool runner's own docs send you here "When you need human-in-the-loop approval, custom logging, or conditional execution". You also own every edge case: results for in one message, max_tokens and pause_turn endings, thinking blocks that must go back unchanged, and a history that grows with every turn.

Tool Runner: the SDK runs the loop over your tools

The tool runner is a beta helper in all seven client SDKs. In the docs' words, it "handles the agentic loop, error wrapping, and type safety so you don't have to". In Python, @beta_tool derives each tool's JSON schema from the function's type hints and docstring. When a tool raises, the runner sends the error back to Claude as a tool result with is_error: true. You can still iterate over every message, cap the run with max_iterations, inspect or modify tool results before they're sent, or take over the history for a turn. What it doesn't have is tools of its own: every tool is a function you wrote, running in your process.

Agent SDK: Claude Code's harness in your process

The Agent SDK, for Python and TypeScript, gives you "the same tools, agent loop, and context management that power Claude Code". It's a library that runs the Claude Code binary in a process you operate. Built-in tools read, edit and write files, search with Glob and Grep, run Bash and use the web. Around them you get permission rules, hooks, subagents, MCP servers, sessions you can resume, and limits such as max_turns and max_budget_usd. If your agent works on files and commands, most of the CI doctor's three weeks is already in the box.

Managed Agents: Anthropic runs the harness and the sandbox

Managed Agents, in beta, is a "pre-built, configurable agent harness that runs in managed infrastructure". You create an agent (model, system prompt, tools, MCP servers, skills) once, then start sessions in an environment: an Anthropic-managed cloud sandbox or a self-hosted one. Claude runs bash, file and web tools there and streams events back to you. The docs pitch it for tasks "that run for minutes or hours", stateful sessions, and scheduled runs.

The same agent on two layers

For an agent whose tools are your own functions, compare the hand-written loop with the tool runner:

Python ci_doctor.py
import anthropicclient = anthropic.Anthropic()messages = [{"role": "user", "content": "Why did build 812 fail?"}]while True:  # loop, schemas, dispatch and error wrapping: all ours    reply = client.messages.create(        model="claude-opus-5-5", max_tokens=4096,        tools=TOOL_SCHEMAS, messages=messages,  # JSON schemas by hand    )    messages.append({"role": "assistant", "content": reply.content})    if reply.stop_reason != "tool_use":  # max_tokens? pause_turn? ours too        break    results = []    for call in [b for b in reply.content if b.type == "tool_use"]:        try:            output, failed = HANDLERS[call.name](**call.input), False        except Exception as err:            output, failed = str(err), True        results.append({"type": "tool_result", "tool_use_id": call.id,                        "content": output, "is_error": failed})    messages.append({"role": "user", "content": results})print(next(b.text for b in reply.content if b.type == "text"))

When the agent needs to read and edit a repository, the Agent SDK brings the tools as well as the loop:

Python ci_doctor_sdk.py
import asynciofrom claude_agent_sdk import ClaudeAgentOptions, ResultMessage, queryasync def main():    async for message in query(        prompt="Build 812 failed. Find the cause in this repo and fix it.",        options=ClaudeAgentOptions(            allowed_tools=["Read", "Glob", "Grep", "Edit"],  # built in            permission_mode="acceptEdits",            max_turns=30, max_budget_usd=5.0,        ),    ):        if isinstance(message, ResultMessage):            print(message.subtype)  # success, error_max_turns, ...asyncio.run(main())
LayerWho runs the loopTools and where they runPick it when
Messages APIYour codeYour functions, your processYou need a control flow no helper fits
Tool Runner (beta)The client SDKYour functions, your processCustom tools, standard loop
Agent SDKClaude Code, as a libraryBuilt-in file, shell and web tools, plus yoursAgents that work on files and commands
Managed Agents (beta)AnthropicA managed or self-hosted sandboxLong, stateful or scheduled runs you don't want to host

How to apply it in your project

  1. Write down what the agent needsList its tools, whether it touches files or a shell, how long a run lasts, and who should operate the machine.
  2. Answer the two questionsDecide who should run the loop and where the tools run. The table above maps the answers to a layer.
  3. Shrink hand-written loops over custom toolsIf your loop only dispatches your own functions, try the tool runner and keep custom code for the turns that need it.
  4. Don't rebuild Claude Code's toolsBefore writing file, search or shell tools, try the Agent SDK with allowed_tools and a permission_mode.
  5. Set limits and read how runs endUse max_iterations, or max_turns and max_budget_usd, and check the final stop_reason or ResultMessage subtype instead of assuming success.

Key takeaways

  • An agent is a loop, but the loop is the smallest part of the work.
  • Choose the layer by who runs the loop and where the tools run.
  • The tool runner handles the loop for your own tools and still lets you step into any turn.
  • The Agent SDK gives you Claude Code's tools, permissions and context management in a process you run.
  • Managed Agents hosts the harness and the sandbox; check its data-retention terms before you rely on it.

📚 المصادر

  1. Agent SDK overview — Claude Code Docs
  2. How the agent loop works — Claude Code Docs
  3. Tool runner — Claude API Docs
  4. Claude Managed Agents overview — Claude API Docs

التعليقات (0)