Blog · Claude API

Building AI Agents with the Claude API & Agent SDK

An architecture-first guide to building AI agents on the Claude API and Agent SDK: agent loops, MCP tool integration, guardrails, model selection, and multi-agent orchestration patterns.

An agent is a model in a loop with tools and a goal. That definition sounds trivial until you try to ship one: suddenly you are designing permission boundaries, taming runaway loops, deciding what a model may do without a human watching, and debugging behaviour that emerges rather than executes. The Claude API gives you the primitives — tool use, streaming, structured outputs — and the Claude Agent SDK packages the loop, context management, and tool plumbing so you build behaviour instead of scaffolding.

This guide is written for architects deciding how much autonomy to grant, where MCP fits, which model runs which role, and how to keep an agent observable enough to trust in production.

Agents vs. Workflows: Choose the Cheapest Abstraction That Works

The most expensive mistake in agent engineering is building an agent where a workflow would do. A workflow is a fixed sequence of LLM calls your code orchestrates — classify, then extract, then draft. Deterministic, testable, cheap. An agent hands the model the steering wheel: given a goal and tools, Claude decides which steps to take and when it is done.

Reach for a true agent only when the path genuinely cannot be predetermined — debugging, open-ended research, multi-system investigations where the next action depends on what the last one revealed. A useful decision test:

  • Can you draw the flowchart in advance? Build a workflow.
  • Does the branching depend on intermediate results in ways you cannot enumerate? Build an agent.
  • Unsure? Start with a workflow and promote the genuinely dynamic segment to an agent later.

Autonomy is a cost — in tokens, latency, and verification burden — so spend it only where it buys capability.

The Core Agent Loop on the Messages API

Strip away frameworks and every agent is the same loop: send the conversation with tool definitions, execute whatever Claude requests, append results, repeat until the model stops calling tools or a budget runs out.

for turn in range(MAX_TURNS):
    resp = client.messages.create(model=MODEL, tools=tools,
                                  system=goal, messages=history,
                                  max_tokens=4096)
    if resp.stop_reason != "tool_use":
        return resp  # agent is done
    history += [assistant(resp.content),
                user(execute_all(resp.content))]
raise AgentBudgetExceeded(history)

The interesting engineering is in the budgets and the transcript. Cap turns, wall-clock time, and token spend explicitly — an agent without limits is an incident waiting for a pager. And treat the message history as your primary debugging artifact: persist it per run, because “why did it do that?” is answered by replaying the transcript, not by re-reading your prompt.

What the Claude Agent SDK Actually Buys You

You can hand-roll the loop above, and for a single-tool assistant you probably should. The Claude Agent SDK earns its place when agents get real: it provides the production agent loop with context management built in, so long-running sessions compact history instead of overflowing the window; a tool and hook system so you can intercept, permit, or deny actions before they execute; sub-agent spawning for parallel work; and session persistence for tasks that outlive one process.

The architectural shift is subtle but important — with the SDK you stop writing orchestration code and start writing policy: which tools exist, what requires approval, how much budget each task class gets, what gets logged. That policy layer is where enterprise requirements live, and it is far easier to audit than bespoke loop code scattered across services. Our Claude Code bootcamp covers the SDK hands-on, from first loop to multi-agent systems.

Connecting Tools and Data with MCP

Agents are only as capable as their tools, and tool sprawl is a genuine failure mode: every team hand-wiring bespoke integrations into every agent. The Model Context Protocol (MCP) is the standard answer — an open protocol for exposing tools and data sources through servers that any MCP-capable client, including the Agent SDK, can consume.

The enterprise payoff is separation of concerns. The team that owns your ticketing system publishes one MCP server with search, read, and comment tools; every agent in the organisation connects to it rather than reimplementing the integration. Security posture improves too, because the server is a single choke point for authentication, authorization, and audit logging.

  • Expose capabilities, not raw APIs — “find_customer_orders” beats a generic SQL tool.
  • Keep read and write tools separate so permissions can differ.
  • Version servers like any API contract; agents are consumers.

Guardrails, Permissions, and Human-in-the-Loop

An agent’s blast radius is defined by its tools, so guardrail design is mostly tool design. Apply least privilege ruthlessly: an agent that summarises tickets needs read access to tickets, not write access to anything. From there, layer controls by consequence:

  • Reversible, low-stakes actions (searches, reads, drafts) run autonomously.
  • Consequential actions (sending external email, modifying records) pause for human approval via SDK hooks or your own gate.
  • Irreversible or financial actions stay outside agent reach entirely, surfaced as recommendations for a human to execute.

Treat every tool result as untrusted input: a web page or document an agent reads can contain adversarial instructions, and prompt-injection resistance comes from constraining what tools can do, not from hoping the model ignores hostile text. Log every action with its justification — the transcript — so security review is a query, not an archaeology project.

Model Selection and Multi-Agent Patterns

Agents amplify model-choice consequences because every decision compounds across turns. The current 2026 lineup maps cleanly onto agent roles: Claude Haiku 4.5 for high-volume, narrow sub-tasks — classification, extraction, tool-result summarisation; Claude Sonnet 5 as the balanced default for most single-agent loops; Claude Opus 4.8 and Claude Fable 5 for orchestration and the hardest multi-step reasoning, where a wrong plan wastes every downstream call.

That mapping suggests the dominant multi-agent pattern: an orchestrator-worker design where a strong model decomposes the goal and cheaper sub-agents execute bounded pieces in parallel, each with only the tools its slice requires. Keep sub-agent contexts isolated and have them return structured summaries, not raw transcripts — context discipline is what keeps costs sane. Prompt caching on shared system prompts and tool definitions compounds the savings. For team-wide adoption strategy beyond the code, see our AI Champions Program.

Key takeaways

FAQ

Questions

The raw API is enough for simple loops, and building one by hand is the best way to learn the mechanics. The SDK becomes worthwhile when you need context compaction for long sessions, permission hooks before tool execution, sub-agents, or session persistence — infrastructure you would otherwise rebuild and maintain yourself.

Enforce hard limits outside the model: a maximum turn count, a wall-clock timeout, and a token budget per run, each terminating the loop with the transcript preserved. Combine that with progress checks — if consecutive turns repeat the same failing tool call, abort early and escalate to a human rather than retrying indefinitely.

Start with Claude Sonnet 5 as the default loop model; it balances reasoning quality against cost for most agentic work. Route high-volume narrow sub-tasks to Claude Haiku 4.5, and reserve Claude Opus 4.8 or Claude Fable 5 for planning and orchestration, where an early wrong decision is the most expensive failure. Measure on your own tasks before standardising.

Cait Hitesh Scaled

Your trainer

Meet Hitesh Motwani

Hitesh Motwani is a globally recognised corporate AI trainer and generative-AI expert. He has trained 2,00,000+ professionals across 16+ countries on Claude, ChatGPT and generative AI, and advised leadership teams at Tata, Flipkart, Hitachi, Siemens, Adani and Marks & Spencer. Connect on LinkedIn →

Trusted by

Teams we’ve trained

TataJSW PaintsMitsui & Co.BirlasoftXebiaPiramal FinanceHPEAction Construction EquipmentIndoramaPharmedM Square MediaFlipkartHitachiAdaniSonyMahindra

…and 200+ organisations, across 16+ countries.

What participants say

Real feedback from real sessions

Verified feedback collected from participants across corporate sessions — average rating 4.8/5.

★★★★★

“A very productive session for working professionals. A must-do.”

Sabyasachi DasGeneral Manager, Tata Teleservices
★★★★★

“The session was highly insightful and conducted in a very professional and interactive manner. Learnt about AI and excited to learn more!”

Rohan MankameDGM – Financial Planning, JSW Paints
★★★★★

“Highly recommended! Hands-on and directly useful — from making PPTs and strategic plans to building KRAs.”

Suneetha QureshiPresident, M Square Media
★★★★★

“Great work done by Mr Hitesh in the AI landscape — a true subject-matter expert. More power to him for spreading this knowledge.”

Vikram Sagar SaxenaAsst. Vice President, Pharmed Ltd
★★★★★

“I would recommend everyone to go through this session — it clarifies both what to expect from AI and where AI isn’t needed.”

Rahul AroraDeputy General Manager, Tata Tele Business Services
★★★★★

“Amazing session by Hitesh. The AI tools he shared are very helpful for day-to-day work.”

Varsha TaklikarDy. Manager, Mitsui & Co. India
★★★★★

“Mr Hitesh Motwani is a very informative trainer. The way he delivers training is awesome.”

Prem ChandDy. Manager – HR, Action Construction Equipment
★★★★★

“Mr Hitesh Motwani delivered a valuable, informative session and showed us exactly how to use AI tools to enhance our work. Thank you so much.”

Alisha KhanProgram Coordinator, Q Academy
★★★★★

“A nice interactive session with a lot of new insights and the power of AI. This will help me save time in routine activities.”

Ramnath BandiSenior Manager – Engineering, JSW Paints
★★★★★

“A very good training session. AI can do wonders — we’ll implement it to create efficiency and save time.”

Ruchit PanchalDeputy Manager, Mitsui & Co.
★★★★★

“Hitesh was very informative and knowledgeable about AI tools. It will let me use my time far more effectively.”

Dagmar NoronhaOperations Manager, Q Academy (Toronto)
★★★★★

“Your session helped me walk into the world of magic.”

Partha ChowdhuryDHM, JSW Paints

Work with us

Bring Claude AI training to your team

Tell us your team, tools and goals and we will send a fixed proposal — usually within one business day.