How the agent loop works - Claude Code Docs
Documentation Index Fetch the complete documentation index at: /docs/llms.txt Use this file to discover all available pages before exploring further. Skip to main content Assistant Responses are generated using AI and may contain mistakes. The Agent SDK lets you embed Claude Code’s autonomous agent loop in your own applications. The SDK is a standalone package that gives you programmatic control over tools, permissions, cost limits, and output.
Both the TypeScript and Python SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install. See the quickstart’s install note for the installs that do. When you start an agent, the SDK runs the same execution loop that powers Claude Code : Claude evaluates your prompt, calls tools to take action, receives the results, and repeats until the task is complete. This page explains what happens inside that loop so you can build, debug, and optimize your agents effectively.
The loop at a glance Every agent session follows the same cycle: Receive prompt. Claude receives your prompt, along with the system prompt, tool definitions, and conversation history. The SDK yields a SystemMessage with subtype "init" containing session metadata. Evaluate and respond. Claude evaluates the current state and determines how to proceed. It may respond with text, request one or more tool calls, or both. The SDK yields one or more AssistantMessage objects, one for each content block, such as a text block or a tool call request.
Execute tools. The SDK runs each requested tool and collects the results. Each set of tool results feeds back to Claude for the next decision. You can use hooks to intercept, modify, or block tool calls before they run. Repeat. Steps 2 and 3 repeat as a cycle. Claude continues calling tools and processing results until it produces a response with no tool calls. Return result. The SDK yields a final AssistantMessage with the text response (no tool calls), followed by a ResultMessage with the final text, token usage, cost, and session ID.
A quick question such as “what files are here?” might take two or three turns : one or two calling Glob , then one responding with the results. A complex task such as “refactor the auth module and update the tests” can chain dozens of tool calls across many turns as Claude adjusts after each result. Turns and messages A turn is one pass through the loop: Claude produces output, and if it includes tool calls, the SDK executes them and the results feed back to Claude automatically.
This happens without yielding control back to your code. Turns continue until Claude produces output with no tool calls, at which point the loop ends and the final result is delivered. Consider what a full session might look like for the prompt “Fix the failing tests in auth.ts”. First, the SDK sends your prompt to Claude and yields a SystemMessage with the session metadata. Then the loop begins: Turn 1: Claude calls Bash to run npm test .
The SDK yields an AssistantMessage with the tool call, executes the command, then yields a UserMessage with the output (three failures). Turn 2: Claude calls Read on auth.ts and auth.test.ts . The SDK yields an AssistantMessage for each call and returns the file contents. Turn 3: Claude calls Edit to fix auth.ts , then calls Bash to re-run npm test . All three tests pass. The SDK yields an AssistantMessage for each call.
Final turn: Claude produces a text-only response with no tool calls: “Fixed the auth bug, all three tests pass now.” The SDK yields a final AssistantMessage with this text, then a ResultMessage with the same text plus cost and usage. That was four turns: three with tool calls, one final text-only response. You can cap the loop with max_turns / maxTurns . Count each turn with tool calls, plus one for the final text-only response.
Without that extra turn, the run ends with a ResultMessage of subtype error_max_turns and no final response. For example, max_turns=2 in the loop above would have stopped before the edit step. You can also use max_budget_usd / maxBudgetUsd to cap turns based on a spend threshold. Without limits, the loop runs until Claude finishes on its own, which is fine for well-scoped tasks but can run long on open-ended prompts (“improve this codebase”).
Setting a budget is a good default for production agents. See Turns and budget below for the option reference. Message types As the loop runs, the SDK yields a stream of messages. Each message carries a type that tells you what stage of the loop it came from. The five core types are: SystemMessage : session lifecycle events. The subtype field distinguishes them: "init" : session metadata for the run. When a SessionStart or Setup hook runs during session startup, its hook lifecycle messages arrive before the init message "compact_boundary" : fires after compaction "informational" : plain-text status banners from the loop "worker_shutting_down" : the host is exiting or Remote Control disconnected In TypeScript, each subtype other than "init" is its own type in the SDKMessage union rather than a subtype of SDKSystemMessage .
AssistantMessage : emitted for each content block in Claude’s responses, including the final text-only one. Each carries a single content block, such as text or a tool call, and the messages from one response share a message ID. UserMessage : emitted after each tool execution with the tool result content sent back to Claude. Also emitted for any user inputs you stream mid-loop. StreamEvent : only emitted when partial messages are enabled.
Contains raw API streaming events (text deltas, tool input chunks). See Stream responses . ResultMessage : marks the end of the agent loop. Contains the final text result, token usage, cost, and session ID. Check the subtype field to determine whether the task succeeded or hit a limit. A small number of trailing system events, such as prompt_suggestion , can arrive after it, so iterate the stream to completion rather than breaking on the result.
See Handle the result . These five types cover the full agent loop lifecycle. Both SDKs also yield observability events such as rate-limit status and task notifications that are not required to drive the loop. See the Python message types reference and TypeScript message types reference for the complete lists. Handle messages Which messages you handle depends on what you’re building: Final results only: handle ResultMessage to get the output, cost, and whether the task succeeded or hit a limit.
Progress updates: handle AssistantMessage to see what Claude is doing each turn, including which tools it called. Live streaming: enable partial messages ( include_partial_messages in Python, includePartialMessages in TypeScript) to get StreamEvent messages in real time. See Stream responses in real-time . How you check message types depends on the SDK: Python: check message types with isinstance() against classes imported from claude_agent_sdk (for example, isinstance(message, ResultMessage) ).
TypeScript: check the type string field (for example, message.type === "result" ). AssistantMessage and UserMessage wrap the raw API message in a .message field, so content blocks are at message.message.content , not message.content . Example: Check message types and handle results import asyncio from claude_agent_sdk import query, AssistantMessage, ResultMessage, TextBlock, ToolUseBlock async def main (): try : async for message in query( prompt = "Summarize this project" ): if isinstance (message, AssistantMessage): # Each AssistantMessage carries one content block for block in message.content: if isinstance (block, TextBlock): print ( f "Claude: { block.text } " ) elif isinstance (block, ToolUseBlock): print ( f "Tool call: { block.name } " ) if isinstance (message, ResultMessage): if message.subtype == "success" : print (message.result) else : print ( f "Stopped: { message.subtype } " ) except Exception as error: # A single-shot query() raises afte
The rest of this page is on the live site.