Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript

Build a support agent with the Claude Agent SDK and no loop code: describe it with ClaudeAgentOptions, serve two @tool functions in process, read the stream of messages, then write the same agent in TypeScript.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Explain what the Claude Agent SDK runs for you and what you still write
  • Describe an agent as data with ClaudeAgentOptions: system prompt, tools, MCP servers, allowed_tools and max_turns
  • Write in-process tools with @tool and create_sdk_mcp_server, and read the stream of typed messages
  • Move the same agent from Python to TypeScript by renaming, not redesigning

Before you start

  • Claude tool use: tool_use and tool_result
  • Basic async Python

When you build an agent on the Messages API, you write the loop yourself: send the messages, read the stop reason, run the tool, append the result, go round, and stop at a cap. The Claude Agent SDK has that loop built in. It is the agent loop of Claude Code, packaged as a library. You describe the agent, and you read what it does.

In this article we build a small support agent that looks up orders, with no loop code at all. Three names carry the whole thing: the query function, the ClaudeAgentOptions object, and the @tool decorator.

Train them yourself, or hire one who knows the routine

Think of a new assistant at a shop. You could train them yourself: teach the routine, write the checklist, watch every step. That's the hand-written loop. Or you hire someone who already knows the routine. You hand over a job card (the options), a toolbox (your tools) and the question, and then you read their report.

The steps are the same either way. What changes is who writes them. You still choose the job and the tools. The SDK brings the routine.

Who does what in an Agent SDK run Your code runner.py: query() options.py tools.py (@tool) Agent SDK runs the loop calls your tools Claude Code decides the next step prompt tool call typed messages, one at a time
The loop turns between the SDK and Claude Code. Your code only sees the messages.

In the lecture project a stand-in plays the Claude Code process, so no API key is needed and every reply says test model reply. With an API key in the environment, the same code starts the real Claude Code process that the SDK installs.

agent/tools.py: your own code, served in process

"""Our two tools, as async functions the SDK serves to Claude."""
import json
import pathlib
from claude_agent_sdk import create_sdk_mcp_server, tool

DATA = pathlib.Path(__file__).resolve().parent.parent / "data"
ORDERS = json.loads((DATA / "orders.json").read_text())
POLICY = json.loads((DATA / "policy.json").read_text())


def reply(text, is_error=False):
    return {"content": [{"type": "text", "text": text}],
            "is_error": is_error}


@tool("lookup_order", "Find an order by its id.", {"order_id": str})
async def lookup_order(args):
    order = ORDERS.get(args["order_id"])
    if order is None:
        return reply(f"No order {args['order_id']}.", is_error=True)
    return reply(json.dumps(order))


@tool("check_return_policy", "Days to return.", {"order_id": str})
async def check_return_policy(args):
    return reply(json.dumps(POLICY))


support_server = create_sdk_mcp_server(
    name="support", version="1.0.0",
    tools=[lookup_order, check_return_policy])
  • @tool gives each tool a name, a description and its inputs.
  • The function is a plain async function. It runs in your own process and reads the data file.
  • If the order isn't there, it returns is_error true, so Claude knows the lookup failed.
  • create_sdk_mcp_server bundles the tools into an MCP server that lives inside your program.

agent/options.py: the agent, described as data

"""The agent, described as data."""
from claude_agent_sdk import ClaudeAgentOptions
from agent.tools import support_server

SYSTEM = ("You are a support agent for an online shop. "
          "Never guess.")

options = ClaudeAgentOptions(
    system_prompt=SYSTEM,
    tools=[],
    mcp_servers={"support": support_server},
    allowed_tools=[
        "mcp__support__lookup_order",
        "mcp__support__check_return_policy",
    ],
    max_turns=6,
)
  • system_prompt is the job card.
  • tools=[] turns off the built-in tools, so the agent only gets the two we wrote.
  • Our server goes in under mcp_servers with the name support. So each tool is called mcp__support__ plus the tool name.
  • allowed_tools lists what runs without asking.
  • max_turns is a safety net, so a stuck run still ends.

agent/runner.py: read the stream

"""Ask a question and read the stream of messages."""
from claude_agent_sdk import (AssistantMessage, ResultMessage,
                              ToolResultBlock, ToolUseBlock,
                              UserMessage, query)
from agent.options import options


async def ask(question, transport=None):
    answer = ""
    stream = query(prompt=question, options=options,
                   transport=transport)
    async for message in stream:
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, ToolUseBlock):
                    print(f"  tool_use -> {block.name}")
        elif isinstance(message, UserMessage):
            for block in message.content:
                if isinstance(block, ToolResultBlock):
                    kind = "error" if block.is_error else "ok"
                    print(f"  tool_result ({kind}): "
                          f"{block.content}")
        elif isinstance(message, ResultMessage):
            print(f"  result: {message.subtype}, "
                  f"{message.num_turns} turns")
            answer = message.result
    return answer

A run is a stream of typed messages, read with async for:

  1. An AssistantMessage with a ToolUseBlock: Claude wants lookup_order.
  2. A UserMessage with a ToolResultBlock: what our tool returned.
  3. Another AssistantMessage, this time with a text block: the answer.
  4. A ResultMessage: it holds the subtype, the number of turns and the final text, and it ends the run.

(The transport argument is only there so the lecture's stand-in can play Claude Code. In real use you leave it out.)

Three questions, no loop code

main.py asks three questions: one that needs one tool, one that needs two, and one for an order that doesn't exist.

agent sdk: one tool
  tool_use -> mcp__support__lookup_order
  tool_result (ok): {"item": "wireless headphones", "status": "shipped", "arrives": "Friday"}
  result: success, 2 turns
  answer: test model reply: your wireless headphones arrive Friday.
agent sdk: two tools
  tool_use -> mcp__support__lookup_order
  tool_result (ok): {"item": "wireless headphones", "status": "shipped", "arrives": "Friday"}
  tool_use -> mcp__support__check_return_policy
  tool_result (ok): {"return_window_days": 30, "counted_from": "delivery"}
  result: success, 3 turns
  answer: test model reply: arrives Friday, and returns are open for 30 days.
agent sdk: tool error
  tool_use -> mcp__support__lookup_order
  tool_result (error): No order 9999.
  result: success, 2 turns
  answer: test model reply: I could not find order 9999.

The replies come from the scripted stand-in. What to notice:

  • The first question used one tool and took two turns.
  • The second asked for the order, then for the return policy: three turns.
  • For order 9999 the tool reported an error, the error came back as a result, and the agent could say it couldn't find the order.

Three options that sound alike

OptionWhat it decides
toolsWhich built-in tools exist at all. Empty means none.
allowed_toolsWhich tools run without asking. It approves; it does not hide anything.
max_turnsWhen to stop trying. A safety net, not the plan.

allowed_tools is not a fence around the tools. To keep Claude away from a tool, leave it out (or block it with disallowed_tools); don't just leave it unapproved.

The same agent in TypeScript

The second lecture moves a ticket-triage agent to TypeScript. The agent reads one ticket with the built-in Read tool, and a PreToolUse hook refuses any path that ends in .env. (Hooks get their own article: hooks for deterministic actions.)

import { query } from "@anthropic-ai/claude-agent-sdk";
import type {
  HookCallback,
  PreToolUseHookInput,
} from "@anthropic-ai/claude-agent-sdk";

const guard: HookCallback = async (input) => {
  const pre = input as PreToolUseHookInput;
  const args = pre.tool_input as Record<string, string>;
  const path = args.file_path ?? "";
  if (path.endsWith(".env")) {
    console.log(`hook deny        Read ${path}`);
    return {
      hookSpecificOutput: {
        hookEventName: pre.hook_event_name,
        permissionDecision: "deny",
        permissionDecisionReason: "No .env files",
      },
    };
  }
  console.log(`hook allow       Read ${path}`);
  return {};
};

for await (const message of query({
  prompt: "Summarise tickets/T-201.txt in one line.",
  options: {
    systemPrompt: "You triage support tickets. Read files, never edit them.",
    allowedTools: ["Read", "Grep"],
    maxTurns: 4,
    hooks: { PreToolUse: [{ matcher: "Read", hooks: [guard] }] },
  },
})) {
  if (message.type === "system") {
    console.log("system init");
  } else if (message.type === "assistant") {
    for (const block of message.message.content) {
      if (block.type === "text") console.log(`assistant text   ${block.text}`);
      if (block.type === "tool_use") {
        console.log(`assistant tool   ${block.name} ${block.input.file_path}`);
      }
    }
  } else if (message.type === "result") {
    console.log(`result ${message.subtype}   ${message.num_turns} turns`);
  }
}

And the same agent in Python. This version uses ClaudeSDKClient and reads the answer with receive_response():

async def main():
    options = ClaudeAgentOptions(
        system_prompt="You triage support tickets. Read files, never edit them.",
        allowed_tools=["Read", "Grep"],
        max_turns=4,
        hooks={"PreToolUse": [HookMatcher(matcher="Read", hooks=[guard])]},
    )
    async with ClaudeSDKClient(options=options) as client:
        await client.query("Summarise tickets/T-201.txt in one line.")
        async for message in client.receive_response():
            if isinstance(message, SystemMessage):
                print("system init")
            elif isinstance(message, AssistantMessage):
                for block in message.content:
                    if isinstance(block, TextBlock):
                        print(f"assistant text   {block.text}")
                    if isinstance(block, ToolUseBlock):
                        path = block.input["file_path"]
                        print(f"assistant tool   {block.name} {path}")
            elif isinstance(message, ResultMessage):
                print(f"result {message.subtype}   {message.num_turns} turns")

Think of one recipe cooked in two kitchens. The steps are identical; only the tools on the bench change:

PythonTypeScript
claude_agent_sdk@anthropic-ai/claude-agent-sdk
async forfor await
ClaudeAgentOptions(...) classplain options object
allowed_tools, max_turnsallowedTools, maxTurns
HookMatcher(matcher=..., hooks=[...]){ matcher, hooks }
isinstance(message, ResultMessage)message.type === "result"

The hook's answer is the same JSON in both: hookSpecificOutput with a permissionDecision. The lecture's run_all.py runs both agents against a stand-in and compares the printouts:

$ python agent.py
system init
assistant text   test model reply: I will read the ticket first.
assistant tool   Read tickets/T-201.txt
hook allow       Read tickets/T-201.txt
assistant text   test model reply: Now the settings file.
assistant tool   Read .env
hook deny        Read .env
assistant text   test model reply: T-201 is a double charge. Refund once.
result success   3 turns
$ node --experimental-strip-types --import ./stand_in/register.mjs agent.ts
system init
assistant text   test model reply: I will read the ticket first.
assistant tool   Read tickets/T-201.txt
hook allow       Read tickets/T-201.txt
assistant text   test model reply: Now the settings file.
assistant tool   Read .env
hook deny        Read .env
assistant text   test model reply: T-201 is a double charge. Refund once.
result success   3 turns
same output: True

Line for line, the same. Notice that the deny blocked one tool call, not the run: the reason went back to the model, and the loop carried on to a successful result.

Common mistakes

  • Writing the tool loop yourself on top of the Agent SDK. query already runs it. If you want to own the loop, use the Messages API instead (see the agentic loop article).
  • Treating allowed_tools as a restriction. It auto-approves. Restrict with the tool lists, not the approval list.
  • Bare tool names for MCP tools. In-process tools are named mcp__<server>__<tool>.
  • Calling the Agent SDK a hosted service. It's a library that runs in your process. Anthropic-hosted agents are a different product: Managed Agents.
  • Rebuilding the agent per language. Python and TypeScript share the loop, the hooks and the message order. You rename; you don't redesign.

Quick recap

PieceJob
query(prompt, options)Starts the run and streams typed messages back
ClaudeAgentOptionsThe agent as data: prompt, tools, MCP servers, approvals, turn cap, hooks
@tool + create_sdk_mcp_serverYour own functions, served to Claude in process
ResultMessageEnds the run: subtype, turns and the final text

When an agent built this way misbehaves, the cause is usually one wrong line in the options. The Fix the Agent article walks through four of them.

Try it yourself

Add a third tool, cancel_order, to the support server, but leave it out of allowed_tools. Predict what happens when a customer asks to cancel, then decide whether the tool should be approved, gated by a hook, or not offered at all.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 28 of 66

Previous
The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
Next post
Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared

Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.

Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move

Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.

On this page

  • Train them yourself, or hire one who knows the routine
  • agent/tools.py: your own code, served in process
  • agent/options.py: the agent, described as data
  • agent/runner.py: read the stream
  • Three questions, no loop code
  • Three options that sound alike
  • The same agent in TypeScript
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.