Architecture·9 min read·29 July 2026

Claude Agent SDK Guide: Production Patterns That Work

A practical claude agent sdk guide covering the Messages API agentic loop, tool design, multi-agent orchestration, error recovery, and context architecture for production

By Solomon Udoh · AI Architect & Certification Lead

Claude Agent SDK Guide: Production Patterns That Work

This claude agent sdk guide is for engineers who have already read the hello-world tutorials and are now asking harder questions: when does an agent actually beat a deterministic script, how do you keep the agentic loop from going off the rails, and what does a production-grade tool schema look like? We answer those questions with concrete patterns, not aspirational diagrams.

Do you actually need an agent?

The most important question in any agent project is whether you need one at all. An agent is the right choice when the task requires dynamic decision-making across an unpredictable sequence of steps, when the set of tools to invoke cannot be determined in advance, or when the system must recover from partial failures mid-task. If you can enumerate every step at design time, a fixed sequential pipeline (prompt chaining) is cheaper, faster, and easier to test.

A useful heuristic: if you can write the workflow as a flowchart with no "unknown" branches, you probably want a pipeline, not an agent. The CCAR-F exam rewards this kind of proportionate thinking. Domain 1 (Agentic Architecture and Orchestration) carries 27% of the exam weight, the largest single domain, precisely because the decision of when to use an agent is as important as how to build one.

ScenarioRecommended approach
Fixed steps, predictable inputsFixed sequential pipeline (prompt chaining)
Dynamic steps, tool selection unknown at design timeSingle agent with tool use
Parallel independent subtasksMulti-agent with coordinator
High-stakes irreversible actionsHuman-in-the-loop gate before execution
Simple classification or extractionDirect API call, no loop

How does the Claude agentic loop actually work?

Claude does not have a built-in "agent runtime" in the way some frameworks do. The agentic loop is a pattern you implement on top of the Messages API request-response cycle. Each turn, you send a messages array to the API. Claude either returns a final text response or a tool_use content block. You inspect the stop_reason field: if it is tool_use, you execute the tool, append the result as a tool_result block, and call the API again. If it is end_turn, the loop is complete.

python
import anthropic
client = anthropic.Anthropic()
def run_agent(system: str, tools: list, initial_message: str) -> str:
messages = [{"role": "user", "content": initial_message}]
while True:
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
system=system,
tools=tools,
messages=messages,
)
# Append assistant turn
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "end_turn":
# Extract final text
for block in response.content:
if block.type == "text":
return block.text
return ""
if response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = dispatch_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result,
})
# Append tool results as user turn
messages.append({"role": "user", "content": tool_results})

Three things to notice in this pattern. First, the full conversation history is always sent back; Claude has no server-side memory between API calls. Second, tool results are appended as a user role turn, not an assistant turn. Third, dispatch_tool is your code, not Anthropic's. The SDK gives you the structured call; you own the execution.

Every tool call is a round trip through your infrastructure. Latency, rate limits, and failure modes all compound across turns.

Anthropic , Claude Documentation (Tool Use Overview)

What are the most common agentic loop anti-patterns?

Understanding failure modes early saves significant debugging time. The agentic loop anti-patterns that appear most often in production are:

Premature termination. Claude returns end_turn before the task is complete because the system prompt framed the goal ambiguously. Fix: use goal-based prompts rather than step-based prompts. Tell Claude what a complete result looks like, not which steps to follow.

Infinite loops. The agent keeps calling the same tool because the tool result does not change the model's belief about what to do next. Fix: add a maximum-turn guard in your loop controller and surface the iteration count in the system prompt so Claude can reason about it.

Attention dilution. As the messages array grows across many tool calls, earlier context loses influence. This is the attention dilution problem: the model's effective attention is spread across a longer sequence, and critical instructions from the system prompt can be crowded out. Fix: keep tool results concise, trim verbose API responses before appending them, and consider a summary injection for fresh sessions when context grows large.

Silent suppression. A tool fails but returns an empty string rather than a structured error. Claude interprets the empty result as a valid (if unhelpful) answer and continues on a wrong path. Fix: use the MCP isError flag pattern and always return structured error metadata.

How should you design tools and schemas?

Tool design is where most production agents break down. Claude selects tools based on their descriptions, not their names. A vague description like "searches data" will cause misrouting; a precise description like "searches the product catalogue by SKU or partial name; returns up to 20 matching records with price and stock level" will not.

The schema quality rules that matter most in practice:

  1. Write descriptions as if explaining the tool to a competent colleague who has never seen your codebase.
  2. Document every parameter: its type, its valid range, and what happens when it is omitted.
  3. Split tools that do two things into two tools. A tool that both reads and writes is harder for Claude to reason about than two separate tools.
  4. Avoid overlapping tool descriptions. If two tools could plausibly handle the same input, Claude will pick inconsistently.
json
{
"name": "search_product_catalogue",
"description": "Search the product catalogue by SKU (exact match) or product name (partial, case-insensitive). Returns up to 20 results ordered by relevance. Use this tool when the user asks about product availability, pricing, or specifications. Do NOT use for order history or customer records.",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "SKU (e.g. 'SKU-4821') or partial product name (e.g. 'wireless headset')"
},
"max_results": {
"type": "integer",
"description": "Maximum number of results to return. Defaults to 10. Maximum 20.",
"default": 10,
"minimum": 1,
"maximum": 20
}
},
"required": ["query"]
}
}

When you have many tools, the tool overload problem becomes real: Claude's selection accuracy degrades as the tool list grows. Mitigate this by scoping tools to the agent that needs them rather than giving every agent the full catalogue. The tool distribution strategy for multi-agent systems should follow the principle of least privilege: each subagent receives only the tools its task requires.

When should you use multi-agent architecture?

Single-agent systems are simpler to debug and cheaper to run. Move to multi-agent when one or more of these conditions holds:

  • The task has genuinely parallel subtasks that do not depend on each other's results.
  • The context window would overflow if a single agent held all intermediate state.
  • Different subtasks require different tool sets or different system prompts (different personas or permission levels).
  • You want independent verification: a second agent reviewing the first agent's output catches errors that self-review misses.

The hub-and-spoke architecture is the most common multi-agent pattern: a coordinator agent receives the user request, decomposes it, delegates to specialised subagents, and synthesises their results. The coordinator does not execute tools directly; it routes work.

python
# Coordinator delegates to subagents via a task tool
# Each subagent runs its own agentic loop in isolation
coordinator_tools = [
{
"name": "delegate_to_research_agent",
"description": "Delegates a research subtask to the research subagent. Use when the task requires web search or document retrieval. Returns a structured findings object.",
"input_schema": {
"type": "object",
"properties": {
"task": {"type": "string", "description": "The research question or retrieval task."},
"context": {"type": "string", "description": "Relevant background the subagent needs."}
},
"required": ["task"]
}
}
]

Subagent context isolation is critical: each subagent should receive only the context it needs for its subtask, not the full coordinator conversation. This keeps token costs predictable and prevents the subagent from being confused by irrelevant history.

Effective multi-agent systems require careful design of how context is passed between agents. Each agent should receive precisely the information it needs, no more and no less.

Anthropic , Claude Documentation (Multi-Agent Systems)

How do you handle errors and recovery in production?

Production agents fail. The question is whether they fail gracefully or silently. A robust error-handling strategy has three layers.

Tool-level errors. Every tool should return a structured error object when it fails, not an empty string or a Python exception that bubbles up unhandled. Include an error category (network, permission, not-found, validation), a human-readable message, and any retry guidance.

json
{
"isError": true,
"error": {
"category": "not_found",
"message": "Product SKU-9999 does not exist in the catalogue.",
"retry_guidance": "Verify the SKU and try again, or use search_product_catalogue to find the correct SKU."
}
}

Loop-level errors. Your loop controller should track turn count, detect repeated tool calls with identical inputs (a sign of a stuck loop), and enforce a maximum-turn ceiling. When the ceiling is hit, surface a structured handoff rather than silently returning an empty result.

System-level errors. Network failures, rate limit responses (HTTP 429), and server errors (HTTP 529) should trigger exponential backoff with jitter, not immediate retry. The Anthropic Python SDK provides a max_retries parameter on the client; set it to a value appropriate for your latency budget.

python
client = anthropic.Anthropic(
max_retries=3, # SDK handles exponential backoff automatically
)

For long-running tasks, consider checkpointing intermediate results to durable storage so a crash does not require restarting from the beginning. The session management options concept covers when to resume a session versus fork it versus start fresh.

How do you manage context across a long agent session?

Context is the agent's working memory. Everything the agent knows about the task, the tools it has called, and the results it has received lives in the messages array. As that array grows, three problems emerge: token costs increase linearly, latency increases, and the attention dilution problem worsens.

Practical mitigations:

  • Trim tool results. If a tool returns a 50-field JSON object but the agent only needs three fields, extract those fields before appending the result.
  • Summarise periodically. After every N turns, inject a compact summary of progress so far and optionally start a fresh session with that summary as context. See summary injection for fresh sessions.
  • Use structured context passing. When delegating to subagents, pass a structured context object rather than a raw slice of the conversation. This forces you to be explicit about what the subagent actually needs.
  • Fork for exploration. When the agent needs to try two divergent approaches, fork the session rather than running both branches in the same context. This keeps each branch's context clean and makes it easier to compare results.

The context management domain accounts for 15% of the CCAR-F exam weight, and the exam consistently rewards solutions that address the root cause of context bloat rather than simply increasing max_tokens.

What does a minimal production-ready agent look like end to end?

Pulling the patterns together, a minimal production agent has these components:

ComponentResponsibility
System promptGoal definition, constraints, output format
Tool registryTyped, documented tool schemas
Loop controllerTurn limit, stuck-loop detection, backoff
Tool dispatcherExecutes tools, returns structured results or errors
Context managerTrims results, injects summaries, manages session lifecycle
Observability layerLogs each turn: tool called, result received, token count

The observability layer is the one most teams skip in early development and regret in production. Without per-turn logging, diagnosing why an agent took a wrong path is nearly impossible. Log the full messages array at each turn (redacting any PII), the stop_reason, and the wall-clock time per turn. This data is also what you need to build evals: a corpus of (input, trajectory, output) triples that you can score against a rubric.

For teams preparing for the CCAR-F exam, our concept library at /concepts maps 174 atomic concepts to the five exam domains and 30 task statements, including the agentic architecture patterns covered in this guide. The adaptive engine uses Bayesian Knowledge Tracing with a 0.90 mastery threshold, so you spend time on the concepts you actually need rather than reviewing what you already know.

AI Skill Certs is an independent prep platform; we are not affiliated with or endorsed by Anthropic.

Frequently asked questions

Does Anthropic provide a dedicated agent SDK or runtime?
Anthropic does not ship a separate agent SDK. The agentic loop is a pattern you implement on top of the standard Messages API using the official Python or TypeScript SDK. You control the loop, tool dispatch, and error handling. Anthropic's SDK handles authentication, retries, and response parsing.
What is the maximum number of turns an agent should run before stopping?
Anthropic does not publish a recommended maximum. In practice, most production teams set a ceiling between 20 and 50 turns depending on task complexity. The ceiling should be enforced in your loop controller, not left open-ended. When the ceiling is hit, return a structured partial result rather than an empty response.
How do I pass tool results back to Claude correctly?
Tool results must be appended as a message with role 'user' and content type 'tool_result', referencing the 'tool_use_id' from Claude's response. A common mistake is appending results as an 'assistant' turn or as plain text, which breaks the conversation structure and causes Claude to misinterpret the result.
What model should I use for agent tasks?
For complex multi-step reasoning and tool selection, claude-opus-4-5 or claude-sonnet-4-5 are appropriate. For high-volume, lower-complexity subtasks within a multi-agent system, a lighter model reduces cost without sacrificing quality. Always benchmark your specific task before committing to a model tier.
How do I prevent Claude from calling the same tool repeatedly in a loop?
Track tool calls within the loop controller. If the same tool is called with identical inputs on consecutive turns, inject a message informing Claude that the tool has already been called with those parameters and the result has not changed. Also review whether the tool's error response gives Claude enough information to change its approach.
Can I use Claude agents with MCP servers in production?
Yes. MCP servers expose tools to Claude via a standardised protocol. In production, scope each MCP server's tools to the agents that need them, use environment variable expansion for credentials rather than hardcoding them, and always handle the MCP isError flag in your tool dispatcher to avoid silent failures propagating through the agent.

People also ask

What is the Claude agent SDK and how does it work?
Claude does not have a standalone agent SDK. Agents are built on the Messages API: Claude returns a tool_use block, your code executes the tool, appends the result, and calls the API again. This loop continues until Claude returns stop_reason 'end_turn'. The official Python and TypeScript SDKs handle the HTTP layer.
How do I build a multi-agent system with Claude?
Use a hub-and-spoke pattern: a coordinator agent decomposes the task and delegates subtasks to specialised subagents via task tools. Each subagent runs its own agentic loop in isolation, receiving only the context it needs. The coordinator synthesises subagent results into a final response. Subagent context isolation keeps token costs predictable.
How do I handle tool errors in a Claude agent?
Return structured error objects from every tool, including an error category, human-readable message, and retry guidance. Use the MCP isError flag when working with MCP servers. Never return an empty string on failure. Structured errors give Claude enough information to change its approach rather than continuing on a wrong path.
How do I stop a Claude agent from running forever?
Enforce a maximum-turn ceiling in your loop controller, not in the system prompt alone. Track consecutive identical tool calls as a stuck-loop signal. When the ceiling is reached, return a structured partial result. The Anthropic SDK's max_retries parameter handles transient network errors separately from your loop-termination logic.
What Claude exam covers agentic architecture and tool design?
The Claude Certified Architect, Foundations exam (CCAR-F) covers agentic architecture and orchestration (27% weight) and tool design and MCP integration (18% weight) as its two largest domains. The exam costs $125, runs 60 items in 120 minutes, and requires a scaled score of 720 out of 1000 to pass.

About the author

Solomon Udoh

AI Architect & Certification Lead

Solomon Udoh is an AI Architect who designs and ships production agent systems on the Claude API and Claude Code. He built AI Skill Certs' adaptive engine and authored its 174-concept knowledge graph, mapping every Claude Certified Architect - Foundations objective to hands-on, exam-aligned practice.

  • Designs production multi-agent systems on the Claude API and Agent SDK
  • Author of the AI Skill Certs knowledge graph (174 mapped exam concepts)
  • Builds with MCP, Claude Code, structured outputs, and agentic loops daily
  • Reviews every concept page against the official Anthropic exam guide

You might also like

Ready to put it into practice?

Study every exam concept with an adaptive tutor.

Start studying