Tutorial
Claude Agent SDK Tutorial for Beginners
The Claude Agent SDK is Anthropic's library for building agents on the same agent loop that powers Claude Code. Instead of writing the tool-calling loop yourself, you call one function and the SDK runs it, with built-in tools for reading files, editing code and running commands. This tutorial shows the Python SDK from install to a custom tool, in code you can run.
By Abdul Rahman Azam, founder of AI Season · Updated
Key facts
| The Claude Agent SDK is | A Python and TypeScript library that runs Claude's agent loop, tools and context management for you |
|---|---|
| Made by | Anthropic. It was previously named the Claude Code SDK |
| Install | pip install claude-agent-sdk |
| Main entry point | query() for one-off tasks; ClaudeSDKClient for multi-turn conversations |
| Built-in tools | Read, Write, Edit, Glob, Grep, Bash, web search and fetch |
| Custom tools | Python functions with @tool, served through an in-process MCP server |
What is the Claude Agent SDK?
The Claude Agent SDK is a library from Anthropic that gives your program the same agent loop, built-in tools and context management that Claude Code uses, so you can build your own agents in Python or TypeScript. You describe the task and the permissions; the SDK handles the cycle of model call, tool execution and result until the task is finished.
This differs from calling the Claude API directly. With the raw API you write the tool calling loop and every tool yourself. With the Agent SDK the loop and a set of working tools come ready-made, which suits agents that act on files, code and a terminal.
Setup
pip install claude-agent-sdk
# macOS / Linux
export ANTHROPIC_API_KEY=your-api-key
# Windows PowerShell
$env:ANTHROPIC_API_KEY = "your-api-key"You need Python 3.10 or newer and an API key from the Anthropic Console. The SDK reads the key from the process environment; it does not load .env files on its own, so load them yourself with python-dotenv if you use one.
Your first agent with query()
query() is an async generator. You give it a prompt and options, and it yields messages as the agent works. The last one is a ResultMessage holding the final answer.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
options = ClaudeAgentOptions(
system_prompt="You are a careful Python reviewer. Be brief.",
allowed_tools=["Read", "Glob", "Grep"], # read-only tools, auto-approved
max_turns=10,
)
async for message in query(
prompt="Find the Python files in this folder and list any functions without docstrings.",
options=options,
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())Run it inside a project folder. The agent decides by itself to list files with Glob, open them with Read and report back. You did not write a loop or a single tool.
Tools and permissions
| Option | What it does |
|---|---|
allowed_tools | Tools that run without asking for approval. It does not hide other tools |
disallowed_tools | Tools the agent may never use |
permission_mode | How unlisted tools are handled, for example "acceptEdits" to auto-approve file edits |
system_prompt | Your instructions. Pass a string, or the claude_code preset to reuse Claude Code's prompt |
max_turns | A cap on agent steps |
mcp_servers | External or in-process MCP servers that add tools |
options = ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"],
permission_mode="acceptEdits",
system_prompt="You are a senior Python developer. Always follow PEP 8.",
)Give an agent the fewest tools that let it do the job. Leave out Bash and Write until you need them, and run agents that execute commands inside a container or a throwaway folder.
Add a custom tool
Custom tools are plain async Python functions decorated with @tool. You bundle them into an in-process MCP server and pass it in the options. Tool names follow the pattern mcp__<server>__<tool>.
import asyncio
from claude_agent_sdk import (
ClaudeAgentOptions, ResultMessage, create_sdk_mcp_server, query, tool,
)
FEES = {"early_bird": 100, "regular": 150} # demo data
@tool("get_fee", "Get the course fee for a plan: early_bird or regular", {"plan": str})
async def get_fee(args):
plan = args["plan"]
if plan not in FEES:
return {"content": [{"type": "text", "text": f"Unknown plan: {plan}"}]}
return {"content": [{"type": "text", "text": f"{plan}: {FEES[plan]}"}]}
course_server = create_sdk_mcp_server(name="course", version="1.0.0", tools=[get_fee])
async def main():
options = ClaudeAgentOptions(
mcp_servers={"course": course_server},
allowed_tools=["mcp__course__get_fee"],
)
async for message in query(
prompt="How much do I save with the early-bird plan?", options=options
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())The same mcp_servers option connects external MCP servers, for example a filesystem or database server started with a command. See the MCP guide for how MCP works.
Multi-turn conversations and subagents
query() starts a fresh session each call. For a chat where the agent must remember earlier turns, use ClaudeSDKClient, which keeps one session open, or resume a past session by passing its ID in resume.
For larger jobs the SDK supports subagents: specialised agents with their own prompt, tools and context that the main agent delegates to. Each returns only its result, which keeps the main context small. It also supports hooks, your own functions that run before or after tool calls to log, block or modify them. These are the same design patterns you would build by hand elsewhere.
Claude Agent SDK vs other frameworks
| Claude Agent SDK | OpenAI Agents SDK | LangGraph | Google ADK | |
|---|---|---|---|---|
| Core idea | Claude Code's loop with ready tools | Agents, handoffs, guardrails | Graphs with explicit state | Agents and sub-agents with a dev UI |
| Built-in file and shell tools | Yes | Some hosted tools | No, you add them | Some built-in tools |
| Model choice | Claude models | OpenAI first, others possible | Any | Gemini first, others possible |
| Control over flow | Loop is managed for you | Managed loop with handoffs | Full control | Workflow and LLM agents |
| Best for | Coding, file and research agents | Multi-agent apps on OpenAI | Custom stateful workflows | Agents on Google Cloud |
Tutorials for the others: OpenAI Agents SDK, LangGraph, Google ADK. For the wider picture see AI agent frameworks compared.
SDKs change quickly. Confirm option names against Anthropic's Agent SDK documentation before you build on them.
How AI Season teaches agent SDKs
Session 9 of the AI Season curriculum is MCP and Agent SDK. Students who have already written the raw loop and built graphs in LangGraph learn what an agent SDK does for them, build an MCP tool server, and connect it to an SDK-based agent. Cohort 02 starts 1st January 2027.
Frequently asked questions
What is the Claude Agent SDK?
It is Anthropic's library for building AI agents in Python or TypeScript using the same agent loop, tools and context management as Claude Code. You give it a task and options and it runs the tool-using loop for you.
How do I install the Claude Agent SDK?
Run pip install claude-agent-sdk for Python, then set the ANTHROPIC_API_KEY environment variable with a key from the Anthropic Console.
Is the Claude Agent SDK the same as the Claude Code SDK?
Yes, it is the renamed successor. The Python package changed from claude-code-sdk to claude-agent-sdk, and the options class is now ClaudeAgentOptions.
What is the difference between the Claude API and the Claude Agent SDK?
With the Claude API you send messages and implement the tool loop and tools yourself. The Agent SDK provides the loop, built-in tools such as file reading and command execution, permissions and session handling.
Is the Claude Agent SDK free?
The SDK is free to install. You pay for the Claude model usage it generates, billed through your Anthropic API key.
Can I use my own tools with the Claude Agent SDK?
Yes. Decorate a Python function with @tool, add it to an in-process MCP server with create_sdk_mcp_server, and pass that server in ClaudeAgentOptions. You can also connect external MCP servers.