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.
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.
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])
@toolgives 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_errortrue, so Claude knows the lookup failed. create_sdk_mcp_serverbundles 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_promptis 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_serverswith the namesupport. So each tool is calledmcp__support__plus the tool name. allowed_toolslists what runs without asking.max_turnsis 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:
- An
AssistantMessagewith aToolUseBlock: Claude wantslookup_order. - A
UserMessagewith aToolResultBlock: what our tool returned. - Another
AssistantMessage, this time with a text block: the answer. - 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
| Option | What it decides |
|---|---|
tools | Which built-in tools exist at all. Empty means none. |
allowed_tools | Which tools run without asking. It approves; it does not hide anything. |
max_turns | When 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:
| Python | TypeScript |
|---|---|
claude_agent_sdk | @anthropic-ai/claude-agent-sdk |
async for | for await |
ClaudeAgentOptions(...) class | plain options object |
allowed_tools, max_turns | allowedTools, 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.
queryalready runs it. If you want to own the loop, use the Messages API instead (see the agentic loop article). - Treating
allowed_toolsas 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
| Piece | Job |
|---|---|
query(prompt, options) | Starts the run and streams typed messages back |
ClaudeAgentOptions | The agent as data: prompt, tools, MCP servers, approvals, turn cap, hooks |
@tool + create_sdk_mcp_server | Your own functions, served to Claude in process |
ResultMessage | Ends 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.
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.