
Messages API, Tool Runner, Agent SDK or Managed Agents: Picking the Right Layer
- كاتب موثّق
- Claude API
محتويات المقال
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
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.
What actually happens
Two questions pick the layer
Messages API: you own everything
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
@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
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
The same agent on two layers
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"))import anthropicfrom anthropic import beta_toolclient = anthropic.Anthropic()@beta_tooldef read_build_log(build_id: int) -> str: """Return the last 200 lines of a CI build log. Args: build_id: The CI build number. """ return fetch_log(build_id) # an exception becomes an is_error resultrunner = client.beta.messages.tool_runner( model="claude-opus-5-5", max_tokens=4096, max_iterations=10, tools=[read_build_log], messages=[{"role": "user", "content": "Why did build 812 fail?"}],)final = runner.until_done()print(next(b.text for b in final.content if b.type == "text"))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())How to apply it in your project
Write down what the agent needs List its tools, whether it touches files or a shell, how long a run lasts, and who should operate the machine. Answer the two questions Decide who should run the loop and where the tools run. The table above maps the answers to a layer. Shrink hand-written loops over custom tools If your loop only dispatches your own functions, try the tool runner and keep custom code for the turns that need it. Don't rebuild Claude Code's tools Before writing file, search or shell tools, try the Agent SDK with allowed_toolsand apermission_mode.Set limits and read how runs end Use max_iterations, ormax_turnsandmax_budget_usd, and check the finalstop_reasonorResultMessagesubtype 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.
التعليقات (0)