Build Your First Agent with the Claude Agent SDK
The Claude Agent SDK packages the agent loop used by Claude Code as a library. Unlike most frameworks, it ships with ready-made tools for reading and writing files, searching code, running shell commands and fetching web pages. You describe the task, choose which tools are allowed, and the SDK runs the loop. This post builds a first agent that reads files in a folder and summarizes them.
Install
pip install claude-agent-sdk
The Python package is claude-agent-sdk and you import claude_agent_sdk. A TypeScript version exists as @anthropic-ai/claude-agent-sdk. The SDK uses the Claude Code runtime underneath, so follow the official installation notes if the first run reports that the Claude Code CLI is missing. Authentication uses ANTHROPIC_API_KEY.
Run a query
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock
async def main():
options = ClaudeAgentOptions(
system_prompt="You are a careful code reader. Be concise.",
allowed_tools=["Read", "Glob", "Grep"],
max_turns=6,
)
async for message in query(
prompt="List the Python files in this folder and say what each one does.",
options=options,
):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, TextBlock):
print(block.text)
asyncio.run(main())
query is an async generator that yields messages as the agent works. The agent might use Glob to list files, Read to open them and then write a summary. Only the text blocks are printed here; other message types describe tool calls and the final result.
Understand the options
allowed_tools: tools the agent may use without asking. Listing only read-only tools such as Read, Glob and Grep keeps the run safe.system_prompt: your instructions for the agent.max_turns: an upper bound on loop iterations, which limits cost and runaway behavior.cwd: the working directory the tools operate in.permission_mode: how permission prompts are handled. Modes includedefault,acceptEdits,planandbypassPermissions. Start with the strictest one that works.
Read the final result
The last message in the stream is a ResultMessage with the outcome and usage details. Capture it if you need cost or the final text:
from claude_agent_sdk import ResultMessage
async def run(prompt: str):
async for message in query(prompt=prompt, options=ClaudeAgentOptions(max_turns=3)):
if isinstance(message, ResultMessage):
print("finished:", message.subtype)
print("turns:", message.num_turns)
print("cost (USD):", message.total_cost_usd)
Logging the result message for every run is cheap and gives you a record of cost and length over time.
How it differs from other frameworks
Most frameworks give you an empty loop and ask you to supply tools. This SDK starts from the opposite end: the tools for working with files and a shell are built in, along with context management and a permission system. That makes it a natural choice for agents that operate on a codebase or a folder of documents. It is less natural for a pure chat bot that only calls your own web APIs, though custom tools are supported and covered later.
Safety first
An agent with shell access can change your machine. Follow these habits from the first day:
- Allow only the tools the task needs; leave out
BashandWritefor read-only jobs. - Run in a scratch directory or a container when experimenting.
- Keep
bypassPermissionsfor sandboxed environments only. - Set
max_turnsso a confused agent cannot run indefinitely.
Later posts add custom tools, multi-turn clients, subagents and hooks that can block dangerous calls.
A realistic first project
A good beginner project is a documentation checker. Point the agent at a folder of Markdown files, allow only Read, Glob and Grep, and ask it to list every file that mentions a deprecated function name, with the line it appears on. The agent will search with Grep, open the matching files and report the results. Because the tools are read-only, the worst outcome of a confused run is wasted tokens, not a damaged repository. Once that works, widen the permissions one tool at a time and watch what changes.
Working directory and context
The agent resolves relative paths from its working directory, set with the cwd option. Keep it narrow. An agent started in your home directory can see much more than one started in a project folder, and a larger view means more noise in its searches. The SDK also manages the context window for you, summarizing and trimming as a long run grows, so you rarely need to count tokens yourself. If you want the agent to follow project rules, put them in a CLAUDE.md file in the working directory; the Claude Code runtime reads it as guidance when you enable the matching setting sources.
Comments
No comments yet. Have a question or a tip? Be the first to share it.