Claude Agent SDK Setup: Sonnet 5.5 in 13 Steps [2026]

Anthropic shipped two new SDK releases in the same week of October 2026, and both point at the same shift: building an AI agent with Claude is no longer about stitching together raw API calls. The Claude Agent SDK now handles tool orchestration, permission checks, session state, and multi-agent coordination out of the box, and pairing it with Claude Sonnet 5.5 gives you a model with a 1-million-token context window at a fraction of the cost of the flagship Opus tier. This tutorial walks through every step needed to go from zero to a working agent, including the exact commands, the environment setup, and a full project you can copy, run, and extend.

By the end you will have a Python (or TypeScript) project that calls Claude Sonnet 5.5 through the Claude Agent SDK, uses custom tools, connects to an MCP server, runs subagents for parallel work, and caches prompts to cut your token bill. Thirteen steps, five code-heavy sections, and one complete project. Grab an Anthropic API key and open a terminal.

Google · Preferred Sources

Don't miss new tech stories on Google

Add Tech Insider once in the Google app and our stories appear in your news suggestions.

Add Now

What Is the Claude Agent SDK, and Why Pair It With Claude Sonnet 5.5?

The Claude Agent SDK is Anthropic’s official framework for building autonomous and semi-autonomous agents on top of Claude models. It grew out of the internal harness that powers Claude Code, and Anthropic opened it up as a standalone SDK so developers could build the same kind of tool-using, multi-step agent for their own products: a code reviewer, a research assistant, a customer support bot that reads tickets and writes replies. Instead of writing your own loop to call the model, parse its tool requests, execute them, and feed results back, the SDK does that loop for you and exposes hooks at every stage.

Claude Sonnet 5.5 is the model most developers will reach for first. It sits in the middle of Anthropic’s current lineup, below Claude Opus 5.5 on raw capability and price but well ahead of Claude Haiku 5.5 on reasoning depth. According to Anthropic’s own model documentation, Claude Sonnet 5.5 ships with a 1-million-token context window and a 128,000-token maximum output, which matters once your agent starts reading entire repositories or long customer histories in a single pass.

Developers are already building on this stack. Stack Overflow’s 2025 Developer Survey found that “84% of developers use or plan to use AI tools in their development process”, and a growing slice of that work is agentic rather than autocomplete-style. The same survey reported that “69% of developers who have used AI agents at work agree that the agents increased their productivity.” That is the gap the Claude Agent SDK is built to close: turning a capable model into something that can actually finish a multi-step task without a human babysitting every tool call.

How the Claude Agent SDK Differs From Calling the Anthropic API Directly

You can call Claude Sonnet 5.5 with nothing more than a single HTTP request to the Messages API, and for a lot of tasks that is still the right choice. A one-shot summarizer or a classification endpoint does not need an agent framework wrapped around it. The Claude Agent SDK earns its keep once a task needs more than one round trip to finish: read a file, decide what to change, write the change, check the result, maybe ask a different subagent to weigh in. Writing that loop by hand means handling partial tool results, retries, permission checks, and context management yourself, and most teams end up rebuilding a worse version of what the SDK already ships.

The practical dividing line is simple. If your use case is “send text in, get text out,” stick with the plain Anthropic API and skip everything below. If your use case is “let the model figure out which actions to take, in what order, using which tools, while staying inside guardrails you define,” the Claude Agent SDK is built for exactly that, and the rest of this tutorial assumes that is the problem you are solving.

Prerequisites: Versions and Accounts You Need First

Before you touch any code, gather the following. None of this is optional, and skipping the version check is the single most common reason this tutorial fails for readers halfway through.

RequirementMinimum VersionWhy You Need It
Python3.10 or laterRuns the claude-agent-sdk package and its async query loop
Node.js18 or laterRequired by the Claude Agent SDK CLI layer and the TypeScript SDK
claude-agent-sdk (Python, PyPI)0.2.168 (Oct 15, 2026 release)Latest Python package, bundles Claude CLI 2.1.301
@anthropic-ai/claude-agent-sdk (npm)0.3.302 (Oct 16, 2026 release)Latest TypeScript SDK release
Anthropic Console accountActive, billing enabledNeeded to generate an Anthropic API key
Terminal / shell accessbash, zsh, or PowerShellFor environment variables and running the agent

You do not need a Claude Pro or Claude Max subscription for this tutorial. Everything here runs through the Anthropic API on a pay-as-you-go basis, billed separately from the consumer chat subscriptions. You will need a credit card on file in the Anthropic Console before your API key can make live calls.

Step 1: Create an Anthropic Console Account and Generate an API Key

Every call the Claude Agent SDK makes to Claude Sonnet 5.5 is authenticated with an Anthropic API key, so this is the step everything else depends on. Sign up or log in at the Anthropic Console, open the API Keys section, and click Create Key. Name it something you will recognize later, such as “agent-sdk-tutorial”, since you will likely create several keys over time for different projects and want to be able to revoke one without breaking the others.

Copy the key immediately. Anthropic shows the full key string exactly once, and if you navigate away before copying it you will have to delete that key and generate a new one. Store it as an environment variable rather than pasting it directly into your code, since hardcoded keys are the top cause of leaked credentials in public repositories.

# macOS / Linux
export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"

# Windows PowerShell
$env:ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"

# Or add it to a local .env file and load it with python-dotenv
echo "ANTHROPIC_API_KEY=sk-ant-api03-your-key-here" >> .env

If you plan to deploy this agent somewhere other than your laptop, set the same environment variable in your hosting provider’s secrets manager rather than committing a .env file. Add .env to your .gitignore right now, before you forget.

Step 2: Install the Claude Agent SDK for Python or TypeScript

Pick a language and stick with it for this tutorial. The concepts map directly between the Python and TypeScript SDKs, so switching later is mostly a syntax exercise. Python is the faster path if you are prototyping, while TypeScript fits better if your agent will live inside an existing Node.js backend.

# Python
python3 -m venv venv
source venv/bin/activate
pip install claude-agent-sdk

# TypeScript / Node.js
mkdir claude-agent-project && cd claude-agent-project
npm init -y
npm install @anthropic-ai/claude-agent-sdk

Anthropic ships the Claude Agent SDK packages frequently. The Python package hit v0.2.168 on October 15, 2026, and the TypeScript package reached v0.3.302 on October 16, 2026, according to the release history on GitHub. Pin a version once your agent is stable, since the SDK’s permission and hook APIs have changed shape between minor versions in the past, and an unpinned auto-upgrade can silently change how your agent behaves.

# Pin to a known-good version once you are happy with it
pip install claude-agent-sdk==0.2.168

Step 3: Set Up Environment Variables and Project Structure

Keep the project simple at first. You need a main entry file, a tools file for anything custom you build later, and a place to store your MCP server configuration once you reach Step 8.

claude-agent-project/
  .env
  .gitignore
  main.py
  tools.py
  .mcp.json
  agents/
    reviewer.py
  logs/

Install python-dotenv so main.py can load the API key without you exporting it in every new terminal session.

pip install python-dotenv

Step 4: Write Your First query() Call With Claude Sonnet 5.5

The simplest way to talk to the Claude Agent SDK is the query() function. It takes a prompt and a set of options, streams back messages as the agent thinks and acts, and exits when the turn is done. This is the building block everything else in this tutorial sits on top of.

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        model="claude-sonnet-5-5",
        permission_mode="default",
        max_turns=5,
    )

    async for message in query(
        prompt="List three ways to reduce cold-start latency in a serverless Python function.",
        options=options,
    ):
        print(message)

asyncio.run(main())

Run this file and you should see a stream of message objects, ending with a result message that includes the final text and token usage. If this is your first time calling the Anthropic API from this machine, check the models overview documentation for the exact dated model identifier Anthropic currently serves behind the claude-sonnet-5-5 alias, since Anthropic periodically rotates the underlying snapshot while keeping the alias stable.

Step 5: Configure Permission Modes So Your Agent Doesn’t Run Wild

An agent that can read files, write files, and run shell commands is powerful and dangerous in equal measure. The Claude Agent SDK exposes permission_mode as the main safety valve. In default mode, the agent asks before anything destructive. In acceptEdits mode, it applies file edits automatically but still asks before running commands. In bypassPermissions mode, it does everything without asking, which you should only use inside a sandbox or container you are comfortable losing.

options = ClaudeAgentOptions(
    model="claude-sonnet-5-5",
    permission_mode="acceptEdits",
    allowed_tools=["Read", "Grep", "Glob", "Edit"],
    disallowed_tools=["Bash"],
)

Start every new agent in default mode, watch what it tries to do, and only loosen permissions once you understand its behavior. The disallowed_tools list is your emergency brake. If you are not ready to let an agent execute shell commands on its own machine, block the Bash tool outright rather than trusting the permission prompt alone.

Step 6: Give Your Agent Custom Tools

Built-in tools cover file access and shell commands, but most real agents need to call your own functions: hit an internal API, query a database, check inventory. The SDK’s tool decorator turns an ordinary async function into something Claude can call mid-conversation.

# tools.py
from claude_agent_sdk import tool

@tool("get_open_prs", "Fetch open pull requests for a GitHub repo", {"repo": str})
async def get_open_prs(args):
    repo = args["repo"]
    # Replace this with a real GitHub API call in production
    prs = [{"number": 412, "title": "Fix retry logic in webhook handler"}]
    return {
        "content": [
            {"type": "text", "text": f"Open PRs for {repo}: {prs}"}
        ]
    }

Register the tool by passing it into the SDK’s MCP server helper, then reference it in allowed_tools so the agent knows it exists. Claude Sonnet 5.5 decides on its own when a tool call is the right move based on the conversation, so you do not need to manually route requests to it.

from claude_agent_sdk import create_sdk_mcp_server
from tools import get_open_prs

internal_tools = create_sdk_mcp_server(
    name="internal-tools",
    version="1.0.0",
    tools=[get_open_prs],
)

options = ClaudeAgentOptions(
    model="claude-sonnet-5-5",
    mcp_servers={"internal": internal_tools},
    allowed_tools=["mcp__internal__get_open_prs"],
)

Step 7: Add Hooks to Intercept and Control Agent Behavior

Hooks let you run your own code before or after the agent calls a tool, without modifying the tool itself. This is where production teams add logging, rate limiting, or a hard block on specific commands regardless of what permission_mode allows.

from claude_agent_sdk import HookMatcher

async def block_destructive_bash(input_data, tool_use_id, context):
    command = input_data.get("tool_input", {}).get("command", "")
    if "rm -rf" in command:
        return {"decision": "block", "reason": "Destructive command blocked by hook"}
    return {}

options = ClaudeAgentOptions(
    model="claude-sonnet-5-5",
    hooks={
        "PreToolUse": [
            HookMatcher(matcher="Bash", hooks=[block_destructive_bash])
        ]
    },
)

Treat hooks as your last line of defense, not your first. Permission modes and the allowed_tools list should already keep the agent inside reasonable bounds. Hooks exist for the rare case where you need a hard-coded rule that no prompt change can override, which matters once non-technical teammates start editing the system prompt.

Step 8: Connect an MCP Server for External Data and Tools

The Model Context Protocol lets your agent reach tools and data sources that live outside your own codebase: a Postgres database, Slack, a ticketing system. Anthropic’s own documentation confirms that the Claude Agent SDK supports MCP servers running locally, over HTTP, or embedded directly inside your application, and you can configure them either in the query() call or through a .mcp.json file loaded with settingSources.

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
    }
  }
}

Save that as .mcp.json in your project root, then load it with settingSources so the agent can see the server without you wiring it into every ClaudeAgentOptions call by hand. This separation matters once a project has more than one entry point, since a shared config file keeps your MCP servers consistent across scripts.

options = ClaudeAgentOptions(
    model="claude-sonnet-5-5",
    setting_sources=["project"],
    allowed_tools=["mcp__postgres__query"],
)

Step 9: Break Big Jobs Into Subagents

A single Claude Sonnet 5.5 agent can get lost once a task has too many independent pieces, the same way a human loses track of context switching between five unrelated bugs. Subagents solve this by giving each piece of the job its own isolated context window and its own tool set, coordinated by a parent agent.

from claude_agent_sdk import AgentDefinition

options = ClaudeAgentOptions(
    model="claude-sonnet-5-5",
    agents={
        "security-reviewer": AgentDefinition(
            description="Reviews code changes for security issues only",
            prompt="You check diffs for injection risks, secrets, and unsafe deserialization. Nothing else.",
            tools=["Read", "Grep"],
            model="sonnet",
        ),
        "style-reviewer": AgentDefinition(
            description="Reviews code changes for style and naming only",
            prompt="You check diffs against the project style guide. Ignore security concerns entirely.",
            tools=["Read", "Grep"],
            model="haiku",
        ),
    },
)

Notice the two subagents use different models. Routing the cheaper style check to Claude Haiku 5.5 while reserving Claude Sonnet 5.5 for the security review is a practical way to cut costs without losing quality where it counts. The parent agent decides which subagent to invoke based on the task description you give it.

Step 10: Turn On Prompt Caching to Cut Token Costs

Prompt caching is the single biggest cost lever available to anyone running an agent that reuses the same system prompt, tool definitions, or reference documents across many calls. Anthropic’s documentation states that prompt caching can cut latency by up to 80% and cost by up to 90% on cached portions of a request. For Claude Sonnet 5.5 specifically, Anthropic lowered the cache-read price from $0.20 to $0.10 per million tokens in its October 2026 release notes, putting cached reads at roughly a twentieth of the standard input price.

# Automatic caching: one field at the top level of the request
response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": long_system_prompt,
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[{"role": "user", "content": user_message}],
)

You can also place explicit cache breakpoints on individual content blocks for finer control, which is useful when only part of a long document changes between calls and you do not want to re-cache the whole thing every time. Any agent that reloads the same large tool schema or reference file on every turn should have caching turned on before it ever reaches production.

Step 11: Manage Multi-Turn Sessions

Most real agents are not one-shot. A user asks a follow-up question, or the agent needs to remember what it found three tool calls ago. The ClaudeSDKClient class keeps a session alive across multiple query() calls instead of starting a fresh context every time.

from claude_agent_sdk import ClaudeSDKClient

async def run_session():
    async with ClaudeSDKClient(options=options) as client:
        await client.query("Summarize open PR 412.")
        async for message in client.receive_response():
            print(message)

        await client.query("Now check if it has any failing tests.")
        async for message in client.receive_response():
            print(message)

Each call inside the same client session stays in context, so the second question about failing tests does not need to re-explain which PR you mean. If your agent needs to survive a process restart, save the session identifier and resume it later rather than rebuilding the whole conversation from a transcript.

Step 12: Add Extended Thinking for Harder Reasoning Tasks

Some tasks need the model to reason through several possibilities before committing to an answer: debugging a race condition, planning a multi-file refactor, weighing tradeoffs in an architecture decision. Extended thinking gives Claude Sonnet 5.5 a dedicated space to work through that reasoning before producing its final response, separate from the answer itself.

options = ClaudeAgentOptions(
    model="claude-sonnet-5-5",
    extra_args={"thinking": {"type": "enabled", "budget_tokens": 4000}},
)

Turn this on selectively. Extended thinking adds tokens and latency to every call, so flipping it on for a simple lookup task wastes money for no benefit. Reserve it for the subset of requests in your agent where getting the wrong answer quickly is worse than getting the right answer a few seconds later.

Step 13: Test, Log, and Deploy Your Agent

Before anything touches production, run your agent against a batch of realistic prompts and log every tool call, every permission prompt, and every token count. Agents fail in ways unit tests do not catch: a tool returns an unexpected shape of data, the model picks a reasonable-looking but wrong tool, a hook silently swallows an error. Logging catches these the first week, not three months later when a user complains.

import json, logging

logging.basicConfig(filename="logs/agent.log", level=logging.INFO)

async for message in query(prompt=task_prompt, options=options):
    logging.info(json.dumps(message, default=str))
    if message.get("type") == "result":
        print("Final result:", message.get("result"))

For deployment, wrap the agent behind a queue or an HTTP endpoint rather than letting it run attended in a terminal. Set a hard max_turns limit so a confused agent cannot loop indefinitely and burn through your token budget, and alert on any run that hits that ceiling since it almost always means something upstream changed.

Complete Working Project: A Pull-Request Review Agent

Here is everything from this tutorial combined into one working script: a custom tool, permission limits, a security subagent on Claude Sonnet 5.5, a style subagent on Claude Haiku 5.5, prompt caching for the shared system prompt, and logging. Save this as main.py, set ANTHROPIC_API_KEY in your environment, and run python3 main.py.

import asyncio
import json
import logging
from dotenv import load_dotenv
from claude_agent_sdk import (
    query,
    ClaudeAgentOptions,
    AgentDefinition,
    tool,
    create_sdk_mcp_server,
)

load_dotenv()
logging.basicConfig(filename="logs/agent.log", level=logging.INFO)

SYSTEM_PROMPT = """You are a pull-request review coordinator. Delegate security
concerns to the security-reviewer subagent and style concerns to the
style-reviewer subagent. Summarize both reports in a single response."""

@tool("get_diff", "Fetch the diff for a pull request number", {"pr_number": int})
async def get_diff(args):
    pr_number = args["pr_number"]
    # Replace with a real git/GitHub API call
    fake_diff = "+ user_input = request.GET['q']\\n+ cursor.execute(f'SELECT * FROM t WHERE x={user_input}')"
    return {"content": [{"type": "text", "text": f"Diff for PR #{pr_number}:\\n{fake_diff}"}]}

internal_tools = create_sdk_mcp_server(name="repo-tools", version="1.0.0", tools=[get_diff])

options = ClaudeAgentOptions(
    model="claude-sonnet-5-5",
    system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}],
    permission_mode="default",
    allowed_tools=["mcp__repo-tools__get_diff"],
    mcp_servers={"repo-tools": internal_tools},
    agents={
        "security-reviewer": AgentDefinition(
            description="Reviews diffs for security issues",
            prompt="Flag SQL injection, XSS, hardcoded secrets, and unsafe deserialization.",
            tools=["mcp__repo-tools__get_diff"],
            model="sonnet",
        ),
        "style-reviewer": AgentDefinition(
            description="Reviews diffs for style and naming",
            prompt="Flag naming inconsistencies and missing docstrings only.",
            tools=["mcp__repo-tools__get_diff"],
            model="haiku",
        ),
    },
    max_turns=8,
)

async def main():
    async for message in query(prompt="Review pull request 412.", options=options):
        logging.info(json.dumps(message, default=str))
        if message.get("type") == "result":
            print(message.get("result"))

asyncio.run(main())

A typical run against the fake diff above should produce output similar to this, since the sample diff contains a textbook SQL injection pattern:

Security review (PR #412): HIGH severity - raw user input is interpolated
directly into a SQL query string via an f-string, allowing SQL injection.
Replace with a parameterized query, e.g. cursor.execute(
  "SELECT * FROM t WHERE x=%s", (user_input,)
).

Style review (PR #412): variable name "x" in the SQL query is non-descriptive.
No docstring issues found.

Summary: 1 high-severity security issue, 1 minor style note. Do not merge
until the SQL injection is fixed.

Swap get_diff for a real call to your Git hosting provider’s API and this script is close to something you could point at an actual repository. Add a webhook that triggers it on every pull request and you have replaced a slice of manual code review with an agent that never gets tired on a Friday afternoon.

Claude Sonnet 5.5 vs Opus 5.5 vs Haiku 5.5: Picking the Right Model

The Claude Agent SDK works with any model in Anthropic’s current lineup, and picking the right one per subagent is one of the fastest ways to control cost without hurting output quality. Claude Opus 5.5 launched August 31, 2026, Claude Sonnet 5.5 followed on September 27, 2026, and Claude Haiku 5.5 arrived October 7, 2026, rounding out the current 5.5 generation.

ModelRelease DateContext WindowMax OutputInput / Output Price (per million tokens)Best Use in an Agent
Claude Opus 5.5Aug 31, 20261M tokens128K tokens$4 / $20Hardest reasoning, final-answer verification, architecture decisions
Claude Sonnet 5.5Sep 27, 20261M tokens128K tokens$2 / $10Main agent loop, coding tasks, most subagents
Claude Haiku 5.5Oct 7, 2026Not published at time of writingNot published at time of writingNot published at time of writingHigh-volume, low-stakes subagents like style checks and simple lookups

A common pattern in production agents built on the Claude Agent SDK is a Sonnet-led parent agent that delegates narrow, high-volume subtasks to Haiku while reserving Opus for a final review pass on anything flagged as high-risk. That three-tier structure keeps the bulk of your token spend on the cheapest model that can still do the job correctly.

Anthropic’s own Sonnet 5.5 announcement notes that the model lands only two points below Opus 5.5 on GDPval-AA, an internal benchmark covering real-world occupational tasks, without specifying the absolute score either model achieved. That gap is small enough that most teams building agents on the Claude Agent SDK default to Sonnet 5.5 everywhere and only route specific subagents to Opus 5.5 once they have evidence a task actually needs the extra capability, rather than assuming the most expensive model is always the safest choice.

Common Pitfalls When Building With the Claude Agent SDK

Most of the problems developers hit with the Claude Agent SDK trace back to a handful of repeatable mistakes.

  • Running with bypassPermissions on a local machine. This mode exists for sandboxed environments. Running it directly on your laptop means an agent can edit or delete files with zero confirmation, and a bad prompt or a confused tool call becomes a real incident.
  • Forgetting to set max_turns. An agent stuck in a loop, repeatedly trying and failing the same tool call, will burn through your API budget fast if nothing caps the number of turns per task.
  • Skipping cache_control on large system prompts. Teams that build a detailed system prompt and tool schema, then call the API without caching, pay full input price on every single request for content that never changes.
  • Giving every subagent the same tool list. Subagents are meant to be narrow. A security-reviewer subagent that also has write access to the filesystem defeats the purpose of separating concerns in the first place.
  • Not pinning the SDK version before deploying. The Claude Agent SDK ships new releases frequently, and an unpinned dependency can change hook or permission behavior under you without warning.
  • Treating hooks as optional. Developers who skip hooks and rely only on prompt instructions to prevent destructive actions learn the hard way that a model can be talked out of a soft rule. Hooks enforce a hard rule instead.

Troubleshooting Guide: Issues and Fixes

Here are the issues readers hit most often when setting up the Claude Agent SDK with Claude Sonnet 5.5, along with the fix for each one. Most of these show up in the first hour of setup, usually on the very first query() call or the first custom tool registration, so check this table before assuming the SDK itself is broken.

SymptomLikely CauseFix
Authentication error on first runANTHROPIC_API_KEY not exported in the current shell sessionRe-export the key or load it from .env with python-dotenv before calling query()
Agent never calls your custom toolTool name missing from allowed_tools, or the MCP server was not passed into ClaudeAgentOptionsCheck the mcp__servername__toolname format matches exactly and the server is registered in mcp_servers
Agent asks for permission on every single tool callpermission_mode left at defaultSwitch to acceptEdits for file edits, keeping Bash excluded until you trust the behavior
Import error for ClaudeAgentOptions or AgentDefinitionInstalled an outdated claude-agent-sdk versionRun pip install –upgrade claude-agent-sdk and confirm the version with pip show
Subagent never gets invokedThe subagent’s description is too vague for the parent agent to match it to the taskWrite a specific description field, since the parent model picks a subagent based on that text
MCP server fails to startThe command in .mcp.json points to a package that is not installed or not on PATHRun the MCP server’s command manually first to confirm it starts before letting the SDK launch it
Token costs higher than expectedcache_control missing from a large, repeated system prompt or tool schemaAdd an ephemeral cache_control block to the system prompt and re-check usage in the response metadata
Agent loops without finishingNo max_turns limit set, or the model keeps retrying a failing tool callSet max_turns explicitly and add a hook that blocks a tool after repeated failures
Hook function never firesHookMatcher’s matcher string does not match the tool name exactlyLog every tool_use event temporarily to confirm the exact tool name before writing the matcher
Extended thinking adds latency with no visible benefitEnabled globally instead of only for the tasks that need deep reasoningGate the thinking option behind a check on task complexity rather than always-on

Advanced Tips for Running Agents in Production

Once the basic agent works, a few practices separate a demo from something you can trust unattended. These are the habits teams running the Claude Agent SDK in production tend to pick up only after a real incident, so building them in from the start saves you that lesson.

  • Version your system prompts like code. Keep them in the repository, review changes in pull requests, and tag which prompt version produced which logged run so a regression is traceable.
  • Set per-task token budgets, not just max_turns. A task that technically finishes in three turns but burns 200,000 tokens getting there is still a cost problem worth catching.
  • Run a shadow deployment before cutting over fully. Let the new agent process real tasks in parallel with your existing process, compare outputs, and only switch traffic once the agent’s error rate is acceptable.
  • Rotate Anthropic API keys per environment. Use separate keys for development, staging, and production so a leaked development key cannot touch production spend or data.
  • Build a kill switch independent of the agent itself. If the agent’s own logic decides whether it should stop, a bug in that logic can disable your only safety mechanism. Put the stop condition outside the agent’s control.
  • Test subagent routing with adversarial prompts. Try to get the parent agent to send a security-sensitive task to the wrong subagent, and tighten the description fields until it stops happening.

Stack Overflow’s 2025 Developer Survey also found a split worth planning around: 31% of developers currently use AI agents, 17% plan to, and 38% do not plan to adopt them at all. If you are rolling an agent out to a team, expect that split inside your own organization too, and budget time for the rollout, not just the build.

Frequently Asked Questions

What is the Claude Agent SDK used for?
It is Anthropic’s framework for building agents that use tools, manage permissions, and coordinate subagents on top of Claude models, instead of you writing a custom tool-calling loop from scratch. Common uses include code review bots, research assistants that browse and summarize documents, and support agents that read tickets and draft replies.

Do I need a Claude Pro or Max subscription to use the Claude Agent SDK?
No. The SDK calls the Anthropic API, which is billed separately from the consumer chat subscriptions, on a pay-as-you-go basis tied to your Anthropic Console account.

Is Claude Sonnet 5.5 or Claude Opus 5.5 better for a coding agent?
Claude Sonnet 5.5 is the practical default for most coding agents, since it handles the bulk of coding and tool-use tasks at half the input price and a quarter of the output price of Claude Opus 5.5. Reserve Opus 5.5 for a final verification pass on the highest-stakes changes.

Can I use the Claude Agent SDK with TypeScript instead of Python?
Yes. Anthropic maintains both a Python package (claude-agent-sdk) and a TypeScript package (@anthropic-ai/claude-agent-sdk) with equivalent capabilities, including subagents, hooks, and MCP support.

Does the Claude Agent SDK support MCP servers?
Yes. MCP servers can run locally, over HTTP, or be embedded directly in your application, and you can configure them through the query() call or a shared .mcp.json file loaded with settingSources.

How much does prompt caching actually save?
Anthropic states that caching can cut latency by up to 80% and cost by up to 90% on cached content. For Claude Sonnet 5.5, cache reads are priced at $0.10 per million tokens, about a twentieth of the standard input price.

What is the difference between the Claude Agent SDK and the older Claude Code SDK?
The Claude Agent SDK is the current, actively updated framework, with Anthropic shipping new releases on both the Python and TypeScript packages multiple times a month as of October 2026. If you find references to an older SDK name in a tutorial, treat the Claude Agent SDK documentation as the current source of truth.

Can I run multiple subagents at the same time?
Yes. Define multiple entries in the agents parameter of ClaudeAgentOptions, each with its own description, prompt, tool list, and model, and the parent agent routes tasks to the subagent whose description best matches the job. Each subagent keeps its own context window, so a long-running security review does not eat into the token budget of an unrelated style check.

The fastest way to internalize all thirteen steps is to run the full pull-request review project above against a real repository, watch the logs it produces, and adjust one option at a time: tighten allowed_tools, add a hook, split off a third subagent for test coverage. The Claude Agent SDK rewards that kind of iteration far more than trying to design the perfect agent before running it once, and since both the Python and TypeScript packages update on a near-weekly cadence, checking the release notes before a production deploy is worth the two minutes it takes.

Nadia Dubois

Nadia Dubois

AI & Innovation Editor

Nadia Dubois is the AI & Innovation Editor at Tech Insider, where she tracks the rapid evolution of artificial intelligence, from foundation models to real-world enterprise deployment. She previously covered AI and startups for La Tribune and contributed to MIT Technology Review's European coverage. Nadia specializes in generative AI, AI regulation, and the intersection of technology and European industrial policy. She holds a dual degree in Computational Linguistics and Journalism from Sciences Po Paris.

View all articles