In short.
How the agent loop works is a Claude Agent SDK documentation page explaining the agent loop for Python and TypeScript developers embedding Claude agents in their applications. Permission and spending controls require careful configuration. It explains how prompts become tool calls, how results return to the model, and how applications receive progress and termination messages. Its most consequential details are that allowedTools auto-approves tools without excluding others, budget caps can be exceeded, and a result message may be followed by additional events. Python and TypeScript examples illustrate integration, not demonstrated reliability or actual costs. Installation requirements, licensing and performance remain unknown from this page.
Researched and written by an AI model and checked by a second AI model. How it works
The scope is the complete selected documentation page at [https://code.claude.com/docs/en/agent-sdk/agent-loop.md], supplied as selected-page.txt. Its prose, examples, tables and notices about permissions, budget overshoot, version requirements, compaction, session storage and error handling are included. Linked pages, the documentation index, SDK package files and external image assets are excluded. No code was executed. Installation, authentication, runtime correctness, security containment, performance, actual costs and redistribution rights remain unverified.
The overview
Identity
The resource is the Claude Code documentation page titled How the agent loop works, available at [https://code.claude.com/docs/en/agent-sdk/agent-loop.md]. It explains the execution architecture of the Claude Agent SDK, which embeds Claude Code's autonomous agent loop in another application.
The resource itself is documentation. Its subject is the standalone SDK, with examples for Python and TypeScript and explanations of tools, permissions, messages, context and sessions.
Assessment
The guide is useful for moving from a simple agent query to an application that needs progress updates, controlled tool access and predictable error handling. It connects the model's decisions to what the SDK executes and what the host application receives.
Its strongest material concerns integration details that are easy to misunderstand: reserving a final turn for the answer, consuming events after the result, handling exceptions after error results, and distinguishing automatic approval from tool restriction. It provides no measured evidence of task accuracy, latency, reliability or deployment readiness.
Users
Python and TypeScript developers building coding agents, project assistants or other applications that let Claude use tools are the main audience. Developers adding a progress interface, approval callback, cost reporting or session resumption will find specific implementation guidance.
Beginners can use the prompt, tool and response cycle as an introduction, but the examples assume familiarity with asynchronous programming and SDK imports. Someone seeking their first installation should start with the linked quickstart; someone seeking a comparison of agent frameworks will need other material.
Capabilities
The page describes built-in tools for reading and editing files, searching code, running shell commands, fetching web content and coordinating subagents. It also introduces external services through MCP servers, custom tool handlers and reusable project skills.
Execution controls include tool approval and denial rules, permission modes, hooks, model choice, reasoning effort, turn limits and estimated spending limits. allowed_tools or allowedTools automatically approves listed tools; omitted tools remain available subject to other permission settings. The list therefore does not create an exclusive tool boundary.
Read-only tools can execute concurrently, while Edit, Write and Bash execute sequentially. Custom tools default to sequential execution and can enable concurrency through the readOnlyHint annotation. Hooks can inspect or block calls and run in the application process without consuming the agent's context window.
Using it
Requirements
The examples use the Python module claude_agent_sdk and the TypeScript package @anthropic-ai/claude-agent-sdk. Both SDKs bundle a native Claude Code binary, so most installations do not require a separate Claude Code installation. The page delegates installation exceptions to the quickstart.
Minimum Python and Node.js versions, supported operating systems, authentication steps and account requirements are not established here. Model support for effort settings also varies. The page states that the budget cap-enforcement behaviors (spawning another subagent failing with Budget limit reached once spend reaches the cap, and stopping background subagents still running) require Claude Code v2.1.217 or later.
Mechanism
Claude receives a prompt together with system instructions, tool definitions and conversation history. It produces text, tool requests or both. The SDK executes requested tools, sends their results back to Claude and repeats until a response contains no tool calls. A final assistant response is followed by a ResultMessage describing termination.
The message stream includes system lifecycle events, assistant content blocks, user messages containing tool results, optional partial streaming events and results. Startup hook events can arrive before the init message, and some system events can arrive after the result, so consumers should iterate the stream to completion.
In Python, examples identify messages with isinstance(). TypeScript checks the type field, and assistant content is nested at message.message.content. A single-shot query yields an error result and then raises or throws; a streaming-input session generally remains available after an error result, except after a session crash.
Setup
The page directs first-time users to the quickstart at [https://code.claude.com/docs/en/agent-sdk/quickstart.md]. Installation commands and authentication instructions are absent from the selected page, and the linked quickstart's contents are outside this resource's assessed scope.
The integration examples call query(), supply options and consume its asynchronous message stream. Project instructions, skills and filesystem hooks are loaded explicitly through setting_sources or settingSources. The combined example configures tool auto-approvals, a 30-turn limit and high effort, but does not configure a dollar budget.
Permission mode needs a deliberate choice. In default mode, calls needing approval reach canUseTool, and the absence of that callback means denial. dontAsk denies calls that would otherwise require prompting, subject to documented exceptions. Neither mode should be interpreted solely from its name.
Example
The page illustrates a four-turn authentication repair: run tests, read the implementation and test files, edit and rerun tests, then return a text answer. This explains turn counting; it is an illustrative scenario, not evidence of an actual repair or passing test run.
Its fuller Python and TypeScript examples auto-approve Read, Edit, Bash, Glob and Grep, load project settings, set 30 turns and high effort, capture a session ID, inspect result subtypes and print cost. The surrounding try block handles the exception that follows a single-shot error result.
A smaller example uses query() to summarize a project and prints text or requested tool names as messages arrive. None of these examples has execution evidence in the supplied material.
Assessment & evidence
Limitations
Turn limits count tool-calling turns and the final text-only response. A limit that leaves no final turn produces error_max_turns without final answer text. With streaming input, a queued message can begin a new turn count, while the spending total continues across messages.
Context accumulates across turns. Automatic compaction summarizes older history and can lose specific early instructions; the page recommends persistent project rules loaded through setting sources. Session storage can mirror transcripts to a backend, but the Claude Code subprocess still writes to local disk first.
The page advises reserving bypassPermissions for isolated environments. TypeScript additionally requires allowDangerouslySkipPermissions: true, and this mode cannot run as root on Unix. The page does not demonstrate sandbox containment, application security, production reliability or successful behavior on a particular project.
Reasoning
The effort option controls reasoning depth within each response. The page describes levels from low through max, with support depending on the model. Extended thinking output and its visibility are separate controls. No evidence establishes how a particular level changes correctness or latency for a given task.
A practical implication of the documented architecture is that model intent, host permission and task correctness require separate attention. A requested action may be denied, and a success result means the loop finished normally; it is not independent proof that generated code is correct. Likewise, a turn limit bounds loop iterations without fixing the cost of each response.
Alternatives
For a broader conceptual introduction, the page points to How Claude Code works at [https://code.claude.com/docs/en/how-claude-code-works.md]. For practical loop-design patterns, it points to Loop engineering: getting started with loops at [https://claude.com/blog/getting-started-with-loops].
These are suggested reading paths named by the source; their contents have not been assessed. The selected page supplies no comparison with other agent SDKs, orchestration frameworks or direct model API integrations, so relative capability, cost and complexity remain unknown.
Evidence
The evidence is the complete supplied capture of [https://code.claude.com/docs/en/agent-sdk/agent-loop.md], captured at 2026-11-12T21:06:21.634Z. It contains lifecycle explanations, API option tables, cautions and Python and TypeScript examples.
This is documentation of intended behavior, not an execution trace, benchmark or independent evaluation. Linked reference pages, package contents and external assets were not supplied as separate evidence. Installation success, observed outputs, performance and actual expenditure are not established.
Access & freshness
Costs
Actual operating cost is unknown. The page supplies no model price table or representative workload measurements. Its sample $0.0312 output is illustrative and does not establish an expected bill.
Turn and budget limits default to unlimited. max_budget_usd or maxBudgetUsd checks estimated spend after model responses arrive, so the response that reaches the cap still completes. Total spending can exceed the threshold by that response's cost plus spending incurred by running subagents before they stop.
Result messages expose cost and usage information, but Python cost fields can be absent and crash results can contain zeroed cost fields. The usage field covers the main loop; modelUsage or model_usage is needed for whole-tree accounting. With streaming input, spending accumulates across messages until /clear resets the budget. The page also describes prompt caching and lower effort as cost controls, without quantifying savings.
Rights
The supplied page contains no explicit documentation licence, SDK licence, commercial-use terms or redistribution grant. Rights to redistribute its text, examples or SDK files are unknown from this evidence.
The package names and documentation links identify the relevant software and references, but do not establish licensing terms. No redistributable package is established by the supplied rights evidence.
Freshness
The capture timestamp establishes when this page content was acquired, not when it was published or last updated. The supplied page does not identify an overall SDK release or pin the examples to a package version.
The explicit Claude Code v2.1.217 minimum applies to the described budget cap-enforcement behaviors: spawning another subagent fails with Budget limit reached once spend reaches the cap, and Claude Code stops background subagents still running. It does not establish a general minimum for every feature. Model-dependent effort support, permission-mode availability and differences between Python and TypeScript need confirmation against the versions in use; changes after the capture are unknown.
Actions
Use the quickstart for initial setup, then adapt the message-handling examples to a small, clearly defined task. Configure permission rules and any approval callback explicitly; do not treat allowedTools as an exclusive list. Set both a turn limit and a spending threshold, leaving room for the final response and documented budget overshoot.
Consume the entire message stream, inspect the result subtype before reading result text, and handle exceptions after single-shot error results. Preserve session IDs for resumption and distinguish main-loop usage from whole-tree accounting.
Before relying on generated changes, validate their behavior in an isolated project and confirm the installed SDK and bundled binary versions. Check licensing and authentication requirements in their own documentation. These are recommended next steps; no execution or validation outcome is established here.
