How to Build AI Agents with the Claude Agent SDK
The Claude Agent SDK is Anthropic's toolkit for building AI agents that can read files, run commands, search the web, and execute multi-step tasks using Claude models. Available in Python and TypeScript, it gives developers the same agent loop and tool execution that powers Claude Code, but as a programmable library. This guide walks through the SDK's core capabilities, shows how to connect external tools via MCP, and explains how to give your agents persistent file storage.
What Is the Claude Agent SDK?
The Claude Agent SDK (formerly the Claude Code SDK) is a library from Anthropic that lets you build AI agents with built-in tool execution. Unlike the standard Anthropic Client SDK, where you write the tool loop yourself, the Agent SDK handles tool calls autonomously. Your agent reads files, runs terminal commands, edits code, and searches the web without you implementing each tool handler. The SDK ships in two languages: Python (pip install claude-agent-sdk) and TypeScript (npm install @anthropic-ai/claude-agent-sdk). Both versions expose the same query() function that streams agent messages as the agent works through a task. Here is a minimal Python example:
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Find all TODO comments in this repo",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"])
):
print(message)
The agent receives the prompt, decides which tools to call, executes them, and returns results. You never write a while response.stop_reason == "tool_use" loop.
What to check before scaling claude agent sdk
The Agent SDK bundles nine built-in tools that cover most development and automation tasks:
- Read: Read any file from the working directory
- Write: Create new files
- Edit: Make targeted edits to existing files
- Bash: Run terminal commands, scripts, and git operations
- Glob: Find files by pattern (e.g.,
**/*.ts,src/**/*.py) - Grep: Search file contents with regex
- WebSearch: Search the web for current information
- WebFetch: Fetch and parse web page content
- AskUserQuestion: Ask the user clarifying questions with multiple-choice options
Beyond built-in tools, the SDK supports three extension mechanisms.
Subagents. Spawn specialized child agents that handle focused subtasks. A main agent can delegate a code review to a code-reviewer subagent while it continues working on other parts of the codebase. Each subagent gets its own instructions, tool permissions, and context.
Hooks. Run custom code at key points in the agent lifecycle. PreToolUse hooks can validate or block tool calls before execution. PostToolUse hooks can log actions, transform outputs, or trigger side effects. This is how you add audit logging, rate limiting, or custom validation.
Sessions. Maintain context across multiple exchanges. The SDK assigns each conversation a session ID that you can capture and resume later. Claude remembers files it read, analysis it performed, and the full conversation history.
Connecting External Tools with MCP
The Model Context Protocol (MCP) is an open standard for connecting AI agents to external services. The Agent SDK has native MCP support, so you can plug in any MCP server and your agent immediately gets access to its tools. Adding an MCP server takes one configuration block:
async for message in query(
prompt="Open example.com and take a screenshot",
options=ClaudeAgentOptions(
mcp_servers={
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
}
)
):
print(message)
This pattern works for any MCP server: databases, browser automation, file storage, APIs, and more. The MCP registry lists hundreds of available servers.
Why MCP Matters for Agent Builders
Without MCP, connecting an agent to a new service means writing custom tool definitions, handling authentication, and managing API calls yourself. MCP standardizes all of this. You declare a server, and your agent gets typed tools with built-in auth handling. For file storage specifically, this is where most agent builders hit a wall. Claude agents can read and write local files, but production agents need persistent, shareable storage that survives across sessions and works across machines.
Give Your AI Agents Persistent Storage
Fastio gives teams shared workspaces, MCP tools, and searchable file context to run claude agent sdk workflows with reliable agent and human handoffs.
Giving Agents Persistent File Storage
Local file operations work fine during development, but production agents need storage that persists, scales, and supports collaboration. An agent that generates reports, processes documents, or manages assets needs somewhere to put those files where humans (or other agents) can access them. Fastio provides an MCP server built specifically for this use case. With 251 MCP tools available via Streamable HTTP or SSE transport, agents can create workspaces, upload files, manage permissions, and query documents through natural language. Here is how you connect it:
async for message in query(
prompt="Create a workspace and upload the quarterly report",
options=ClaudeAgentOptions(
mcp_servers={
"fast-io": {
"type": "url",
"url": "/storage-for-agents/"
}
}
)
):
print(message)
What Agents Get with Fastio
- 50GB free storage with no credit card, no trial period, and no expiration
- Built-in RAG with Intelligence Mode. Toggle it on for a workspace and files are auto-indexed. The agent can ask questions about uploaded documents and get cited answers, no separate vector database needed
- Ownership transfer. An agent creates an org, builds workspaces with files, and transfers everything to a human client. The agent keeps admin access for ongoing maintenance
- File locks for concurrent multi-agent access, preventing conflicts when multiple agents work on the same files
- URL Import to pull files from Google Drive, OneDrive, Box, or Dropbox without downloading locally first
The free agent tier includes 5,000 monthly credits, 5 workspaces, and 50 shares. Agents sign up like human users at fast.io/storage-for-agents/.
Permission Modes and Security
Production agents need guardrails. The Agent SDK provides three permission modes that control how much autonomy an agent gets:
Manual mode (default). Every tool call requires explicit approval. Best for development and debugging, where you want to see each step before it executes.
AcceptEdits mode. File reads and edits are auto-approved, but shell commands still require approval. Good for code generation agents where file operations are safe but arbitrary command execution needs oversight.
BypassPermissions mode. All tools run without approval. Use this for fully autonomous agents in sandboxed environments, CI/CD pipelines, or trusted production workflows.
### Read-only agent: can analyze but not modify code
async for message in query(
prompt="Review this code for security issues",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep"],
permission_mode="bypassPermissions"
)
):
print(message)
You can also restrict which tools an agent can access using the allowed_tools parameter. A research agent might only get Read, Glob, Grep, and WebSearch. A code modification agent might get Read, Edit, and Write but not Bash.
Hooks for Fine-Grained Control
Permission modes set broad policies, but hooks give you per-action control. A PreToolUse hook can inspect tool arguments and block specific operations:
- Block file writes to sensitive directories
- Require approval for commands matching certain patterns
- Rate-limit API calls through external MCP servers
A PostToolUse hook can log every action to an audit trail. For agents handling sensitive data, this creates a complete record of what the agent did and why.
Building Multi-Agent Systems with Subagents
Complex tasks often break down into specialized subtasks. The Agent SDK supports this through subagents: child agents that handle focused work and report results back to a parent.
async for message in query(
prompt="Review the codebase for security and performance issues",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep", "Task"],
agents={
"security-reviewer": AgentDefinition(
description="Reviews code for security vulnerabilities",
prompt="Check for injection, auth issues, and data exposure",
tools=["Read", "Glob", "Grep"]
),
"perf-reviewer": AgentDefinition(
description="Reviews code for performance bottlenecks",
prompt="Identify N+1 queries, unnecessary allocations, and slow algorithms",
tools=["Read", "Glob", "Grep"]
)
}
)
):
print(message)
The parent agent spawns both reviewers, collects their findings, and synthesizes a single report. Each subagent runs with its own context and tool permissions.
When to Use Subagents
- Parallel analysis. Run multiple reviewers on different aspects of a codebase simultaneously
- Separation of concerns. Keep a research agent's context separate from a writing agent's context
- Tool isolation. Give a deployment agent access to
Bashwhile keeping a documentation agent limited toReadandWrite
For agents that produce files, pairing subagents with external storage makes the pattern more useful. A research subagent can upload findings to a shared Fastio workspace, and a writing subagent can read those findings without the parent needing to shuttle data between them.
Deploying Agents to Production
Moving from a local prototype to a production agent involves a few key decisions.
Authentication The SDK supports multiple authentication backends:
- Anthropic API key (set
ANTHROPIC_API_KEY): Direct access to Claude models - Amazon Bedrock (set
CLAUDE_CODE_USE_BEDROCK=1): Use your AWS credentials and billing - Google Vertex AI (set
CLAUDE_CODE_USE_VERTEX=1): Use your GCP credentials and billing - Microsoft Azure (set
CLAUDE_CODE_USE_FOUNDRY=1): Use your Azure credentials and billing
Pick the backend that matches your existing cloud infrastructure. All backends give you the same SDK capabilities.
Session Management
For agents that handle ongoing conversations, capture the session ID from the initial query and pass it to subsequent calls:
### First interaction
async for msg in query(prompt="Analyze the auth module"):
if hasattr(msg, 'subtype') and msg.subtype == 'init':
session_id = msg.session_id
### Resume later with full context
async for msg in query(
prompt="Now suggest improvements",
options=ClaudeAgentOptions(resume=session_id)
):
print(msg)
The agent remembers everything from the first interaction, including files it read, analysis it performed, and decisions it made.
CI/CD Integration The Agent SDK fits naturally into CI/CD pipelines. Common patterns include:
- Code review bots that analyze pull requests and post comments
- Documentation generators that update docs when code changes
- Test writers that generate tests for new functions
- Migration assistants that update code when dependencies change
For these workflows, run agents in bypassPermissions mode inside a sandboxed container with restricted filesystem access.
Frequently Asked Questions
What is the Claude Agent SDK?
The Claude Agent SDK is Anthropic's library for building AI agents that autonomously execute multi-step tasks. Available in Python and TypeScript, it provides the same agent loop, built-in tools, and context management that powers Claude Code. Unlike the standard Client SDK where you write the tool loop yourself, the Agent SDK handles tool execution automatically.
How do Claude agents use tools?
Claude agents call tools through the Agent SDK's built-in tool system. The SDK includes nine tools out of the box: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch, and AskUserQuestion. You specify which tools an agent can access via the allowed_tools parameter. Claude decides when and how to call each tool based on the task. You can extend the tool set by connecting MCP servers for database access, browser automation, file storage, and other capabilities.
Can Claude agents access files?
Yes. Claude agents can read, write, and edit local files using the SDK's built-in Read, Write, and Edit tools. For persistent cloud storage, agents can connect to MCP servers like Fastio, which provides 50GB of free storage with built-in RAG, file versioning, and sharing capabilities. This gives agents organized, searchable file storage that persists across sessions.
What is the difference between the Claude Agent SDK and the Anthropic Client SDK?
The Client SDK gives you direct API access where you implement the tool execution loop yourself. The Agent SDK includes built-in tool execution, so Claude autonomously calls tools without you writing loop logic. The Agent SDK also adds subagent support, session management, hooks, and MCP integration that would require significant custom code with the Client SDK.
Does the Claude Agent SDK support MCP?
Yes. The Agent SDK has native MCP (Model Context Protocol) support. You configure MCP servers in the options object, and the agent automatically gets access to all tools those servers expose. This works with any MCP-compatible server, including browser automation (Playwright), file storage (Fastio with 251 tools), databases, and hundreds of other integrations listed in the MCP registry.
What permission modes does the Claude Agent SDK have?
The SDK offers three permission modes. Manual mode (default) requires approval for every tool call. AcceptEdits mode auto-approves file operations but requires approval for shell commands. BypassPermissions mode runs all tools without approval, designed for sandboxed or CI/CD environments. You can also use hooks for per-action control, like blocking writes to specific directories.
Related Resources
Give Your AI Agents Persistent Storage
Fastio gives teams shared workspaces, MCP tools, and searchable file context to run claude agent sdk workflows with reliable agent and human handoffs.