How to Use the Claude Code API and Agent SDK
The Claude Code Agent SDK gives developers the same tools, agent loop, and context management that power Claude Code, available as a Python or TypeScript library. This guide walks through installation, authentication across five providers, built-in tools, and advanced patterns like hooks, subagents, and MCP integration, so you can ship production agents without reimplementing tool execution from scratch.
What the Claude Code Agent SDK Actually Is
71% of developers who regularly use AI agents now reach for Claude Code as their primary tool, according to a Pragmatic Engineer survey of 15,000 developers in February 2026. But most tutorial content still teaches the raw Anthropic Messages API, a lower-level interface that forces you to write your own tool execution loop. The Claude Code Agent SDK sits a layer above, and the difference is not cosmetic.
With the Messages API (Anthropic's Client SDK), you send a prompt, get a response that might request a tool call, execute that tool yourself, feed the result back, and loop until the model stops. You own the entire orchestration. With the Agent SDK, Claude owns the loop. You call query() with a prompt and a set of allowed tools, and the SDK reads files, runs commands, edits code, and streams results back to you as structured messages. No tool handlers to write, no loop to manage.
Think of it this way: the Client SDK is the engine. The Agent SDK is the car. Most developers building agents want the car.
The SDK ships in two languages. The Python package (claude-agent-sdk) requires Python 3.10 or later. The TypeScript package (@anthropic-ai/claude-agent-sdk) bundles a native Claude Code binary for your platform, so you don't need Claude Code installed separately. Both expose the same core interface: a query() function that returns an async iterator of messages as Claude works through your task.
Claude Cowork patterns, where Claude agents collaborate alongside human teammates on shared files, are a natural fit for the SDK. Instead of one-shot API calls, agents built with the SDK maintain sessions, remember context across multiple exchanges, and produce artifacts that humans pick up and refine. Sessions persist as JSONL on your filesystem, so you can resume work hours or days later.
How to Install the SDK and Configure Authentication
Setup takes about two minutes. Pick your language and install the package.
Python:
pip install claude-agent-sdk
TypeScript:
npm install @anthropic-ai/claude-agent-sdk
If pip reports "No matching distribution found for claude-agent-sdk," your interpreter is older than 3.10. Check with python3 --version on macOS/Linux or py --version on Windows.
Next, set your API key. The simplest path is a direct Anthropic key from the Console:
export ANTHROPIC_API_KEY=your-api-key
The SDK also supports authentication through cloud providers. This is useful when your organization already routes AI workloads through AWS, Google Cloud, or Azure, since traffic stays inside existing billing and compliance boundaries.
Amazon Bedrock: Set CLAUDE_CODE_USE_BEDROCK=1 and configure your AWS credentials (IAM role, access key, or SSO profile).
Claude Platform on AWS: Set CLAUDE_CODE_USE_ANTHROPIC_AWS=1 and ANTHROPIC_AWS_WORKSPACE_ID, then configure AWS credentials. This routes through Anthropic's platform while keeping traffic on AWS infrastructure.
Google Vertex AI: Set CLAUDE_CODE_USE_VERTEX=1 and configure Google Cloud credentials (service account or application default credentials).
Microsoft Azure AI Foundry: Set CLAUDE_CODE_USE_FOUNDRY=1 and configure Azure credentials.
Each provider has its own pricing model and rate limits. The direct Anthropic API key is the fast path for prototyping. Enterprise teams typically prefer Bedrock, Vertex, or Foundry because the traffic stays inside their existing cloud governance. You can switch providers by changing environment variables without modifying your agent code.
Give your SDK agents a persistent workspace
Fast.io workspaces connect to the Claude Agent SDK through MCP. File versioning, semantic search, and human handoff are built in. Start with a 14-day free trial.
Built-in Tools and the Agent Loop
The SDK ships with 10 built-in tools. This is the single biggest practical difference from the Messages API: you don't write tool handlers for file operations, command execution, or code search. The SDK already knows how to do all of it.
Here is what's available out of the box:
- Read reads any file in the working directory
- Write creates new files
- Edit makes precise, targeted edits to existing files
- Bash runs terminal commands, scripts, and git operations
- Monitor watches a background process and reacts to each output line
- Glob finds files by pattern (like
**/*.tsorsrc/**/*.py) - Grep searches file contents with full regex support
- WebSearch searches the web for current information
- WebFetch fetches and parses web page content
- AskUserQuestion asks the user clarifying questions with multiple-choice options
You control which tools the agent can access through the allowed_tools parameter. A read-only analysis agent gets ["Read", "Glob", "Grep"]. A full-power coding agent gets all ten. A research agent might only need ["WebSearch", "WebFetch"]. This parameter doubles as a security boundary, since the agent cannot use tools you don't list.
The query() function is the entry point. Pass a prompt and options, and you get back an async iterator. Each yielded message tells you what Claude is doing: reading a file, running a command, thinking through a problem, or returning a final result.
Python:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find all TODO comments and summarize them",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep"]
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
TypeScript:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find all TODO comments and summarize them",
options: { allowedTools: ["Read", "Glob", "Grep"] }
})) {
if ("result" in message) console.log(message.result);
}
The agent handles the full loop internally. It reads files, follows import paths, searches for patterns, and continues working until it has a complete answer. You consume the stream and act on the results.
How to Write Your First Production Agent
A "hello world" that lists files is fine for testing connectivity. Here is something closer to a real use case: an agent that reviews code for security issues and writes a report.
Python:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt=(
"Review this codebase for common security issues: "
"SQL injection, XSS, hardcoded secrets, and insecure "
"dependencies. Write findings to security-report.md."
),
options=ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Glob", "Grep", "Bash"],
permission_mode="acceptEdits",
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
TypeScript:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: `Review this codebase for common security issues: SQL injection,
XSS, hardcoded secrets, and insecure dependencies.
Write findings to security-report.md.`,
options: {
allowedTools: ["Read", "Write", "Glob", "Grep", "Bash"],
permissionMode: "acceptEdits",
}
})) {
if ("result" in message) console.log(message.result);
}
The permissionMode parameter controls what the agent can do without human approval:
"default"prompts for everything"acceptEdits"allows file reads and writes, but prompts before destructive shell commands"bypassPermissions"runs everything without prompts (useful in CI/CD)"plan"requires approval before each step
For CI/CD pipelines, "bypassPermissions" is the standard choice since there's no human to approve actions. For local development, "acceptEdits" balances speed and safety.
Sessions maintain context across multiple queries. Capture the session ID from the first response, then pass it back:
from claude_agent_sdk import SystemMessage, ResultMessage
session_id = None
### First query: analyze the auth module
async for message in query(
prompt="Read the authentication module and explain how it works",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
):
if isinstance(message, SystemMessage) and message.subtype == "init":
session_id = message.data["session_id"]
### Second query: full context from the first exchange is available
async for message in query(
prompt="Now find all callers of that module and check for misuse",
options=ClaudeAgentOptions(resume=session_id),
):
if isinstance(message, ResultMessage):
print(message.result)
Sessions persist as JSONL files on disk. You can resume them across process restarts, which makes them practical for long-running pipelines where each stage builds on previous analysis.
Extending Agents with Hooks, Subagents, and MCP
The SDK's extension points turn a single-purpose script into a system of collaborating agents, each with its own tools, permissions, and responsibilities.
Hooks
Hooks run your custom code at specific points in the agent lifecycle. You can validate tool inputs before execution, log every action to an audit trail, block operations that violate a policy, or transform results before they reach your application.
Available hook points: PreToolUse, PostToolUse, Stop, SessionStart, SessionEnd, and UserPromptSubmit.
This example logs every file modification to an audit file:
from datetime import datetime
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
async def log_edit(input_data, tool_use_id, context):
path = input_data.get("tool_input", {}).get("file_path", "unknown")
with open("./audit.log", "a") as f:
f.write(f"{datetime.now()}: modified {path}
")
return {}
async for message in query(
prompt="Refactor utils.py for readability",
options=ClaudeAgentOptions(
permission_mode="acceptEdits",
hooks={
"PostToolUse": [
HookMatcher(matcher="Edit|Write", hooks=[log_edit])
]
},
),
):
pass
Hooks are especially valuable in production environments where you need audit trails, cost controls, or compliance checks that the built-in permission modes don't cover.
Subagents
Subagents let your main agent delegate focused subtasks to specialized child agents. Each subagent gets its own context window, tool set, and system prompt. The main agent orchestrates, and subagents report back.
from claude_agent_sdk import AgentDefinition
async for message in query(
prompt="Use the code-reviewer agent to review this codebase",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep", "Agent"],
agents={
"code-reviewer": AgentDefinition(
description="Expert code reviewer for quality and security.",
prompt="Analyze code quality and flag potential issues.",
tools=["Read", "Glob", "Grep"],
)
},
),
):
if hasattr(message, "result"):
print(message.result)
Include "Agent" in allowed_tools so the main agent can spawn subagents without a permission prompt. Messages from subagents include a parent_tool_use_id field, which lets you track which results come from which child.
Model Context Protocol (MCP)
MCP connects your agent to external systems: databases, browsers, APIs, and custom tooling. The SDK supports both local MCP servers (spawned as child processes) and remote servers (connected via Streamable HTTP or SSE).
async for message in query(
prompt="Open example.com and describe what you see",
options=ClaudeAgentOptions(
mcp_servers={
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
}
),
):
if hasattr(message, "result"):
print(message.result)
MCP turns the Agent SDK from a code-centric tool into a general-purpose agent platform. Any service that exposes an MCP endpoint becomes a tool your agent can call. The MCP server registry lists hundreds of community-maintained servers for databases, cloud services, productivity tools, and more.
Claude Cowork Workflows with Sessions and Subagents
The combination of sessions, subagents, and MCP creates what many teams call Claude Cowork: a pattern where multiple agents collaborate on shared files, then hand the results to a human for review.
A typical Claude Cowork pipeline looks like this: a research subagent gathers information using WebSearch and WebFetch, a writer subagent produces a draft using Read and Write, a reviewer subagent checks the output using Grep and Read, and finally the main agent uploads the deliverables to a shared workspace where a human teammate picks them up. Each subagent has access only to the tools it needs, and sessions preserve the full chain of reasoning across the pipeline.
This is not a hypothetical pattern. It's how production teams structure agent workflows that need human oversight before final delivery.
Connecting Agents to Persistent Storage
Agents built with the SDK produce artifacts: reports, code changes, extracted data, generated files. Those artifacts need to go somewhere durable, especially when an agent's work feeds into a human review step or a downstream pipeline.
Local filesystems work for prototyping. The SDK's Read, Write, and Edit tools operate on the working directory by default, so output lands wherever you run the script. For production, you need something with versioning, access controls, and discoverability.
Common options for agent artifact storage:
- S3 or GCS buckets suit batch pipelines where output is consumed by other automated systems. Use the Bash tool to run
aws s3 cporgsutil cpcommands. - Git repositories fit code-generation agents well. The Bash tool can stage, commit, and push changes directly.
- Workspace platforms like Fast.io are designed for the handoff between agents and humans. Upload files through the API or MCP server, organize them in shared workspaces with versioning and granular permissions, then transfer ownership when the work is ready for review.
Fast.io's MCP endpoint connects directly to the Agent SDK's MCP integration. Point your agent at the Streamable HTTP endpoint at mcp.fast.io, and it gets access to 19 workspace tools for uploading, organizing, searching, and sharing files. Intelligence Mode auto-indexes uploaded content for semantic search, so a second agent or a human can query the first agent's output by meaning rather than filename.
The ownership transfer pattern works well for client-facing agent pipelines. An agent creates a workspace, populates it with deliverables, and transfers the organization to a human client. The agent retains admin access for ongoing updates while the client gets full control over sharing and distribution.
For teams evaluating storage, the deciding factors are: Does the consumer need a UI to browse results? Does the output need versioning? Does a human need to review or modify it before it ships? When the answers point toward yes, a workspace with built-in collaboration beats raw object storage.
Frequently Asked Questions
How do I use the Claude Code API?
Install the Claude Agent SDK with pip install claude-agent-sdk (Python) or npm install @anthropic-ai/claude-agent-sdk (TypeScript). Set your ANTHROPIC_API_KEY environment variable, then call the query() function with a prompt and a list of allowed tools. The SDK runs the agent loop internally and streams results back as structured messages.
What is the Claude Agent SDK?
The Claude Agent SDK is a library that gives developers the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript. It includes 10 built-in tools for reading files, running commands, editing code, and searching the web. Unlike the Anthropic Messages API, the Agent SDK handles tool execution internally, so you write a prompt and consume results rather than implementing the tool loop yourself.
Can I use Claude Code programmatically?
Yes. The Claude Agent SDK exposes Claude Code's full capabilities as a library you embed in your own applications. Use it in CI/CD pipelines, scheduled tasks, custom developer tools, or any Python or TypeScript project. The SDK supports sessions for multi-turn context, hooks for customizing behavior, subagents for delegation, and MCP for connecting to external systems.
What tools does the Claude Code SDK include?
The SDK includes Read (file access), Write (file creation), Edit (targeted file changes), Bash (terminal commands), Monitor (background process observation), Glob (file pattern matching), Grep (regex content search), WebSearch (web queries), WebFetch (page content extraction), and AskUserQuestion (interactive clarification). You control which tools each agent can access through the allowed_tools parameter.
What is the difference between the Agent SDK and the Anthropic Messages API?
The Messages API gives you direct model access where you send prompts and implement tool execution yourself in a loop. The Agent SDK wraps that with a complete agent runtime: 10 built-in tools, automatic tool execution, session persistence, lifecycle hooks, subagent delegation, and MCP integration. The Messages API is for custom LLM applications. The Agent SDK is for building agents that work with files, code, and external systems.
Which authentication providers does the Agent SDK support?
The SDK supports five authentication paths: direct Anthropic API key, Amazon Bedrock, Claude Platform on AWS, Google Vertex AI, and Microsoft Azure AI Foundry. Switch between them by setting environment variables. No code changes required. Enterprise teams typically use Bedrock, Vertex, or Foundry to keep agent traffic inside their existing cloud governance and billing.
Related Resources
Give your SDK agents a persistent workspace
Fast.io workspaces connect to the Claude Agent SDK through MCP. File versioning, semantic search, and human handoff are built in. Start with a 14-day free trial.