The Claude Agent SDK hit version 0.1.21 in January 2026, and it’s solving a problem every developer with AI access has faced: you have the world’s most capable language model at your fingertips, but you still need to write hundreds of lines of glue code to make it do anything useful. The Claude Agent SDK changes that fundamentally. Anthropic’s philosophy is simple: “Give your agents a computer”—and they mean it literally. This isn’t just another wrapper around an API. It’s a complete framework that ships with 8 native tools, 200K token context management, and permission modes that let you sleep at night when your agent runs unsupervised. In the next 30 minutes, you’ll build an agent that researches topics autonomously, fetches web content, and synthesizes findings—no infrastructure required.
What You’ll Build: A Research Agent
Let’s set concrete expectations. By the end of this tutorial, you’ll have a working AI agent that takes a research query, searches the web autonomously, reads full articles, and summarizes findings with proper citations. The workflow is straightforward: user asks “What’s new in agentic AI?”, the agent uses WebSearch to find recent articles, fetches full content from those URLs, and outputs a structured research summary with sources. You’ll have a functional prototype in approximately 30 minutes, assuming basic Python comfort.
Your agent will be able to:
- Search the web automatically using integrated WebSearch tool
- Fetch and read web content with WebFetch—no manual scraping
- Execute shell commands with Bash for data processing
- Read, write, and edit files on disk
- Track context across the full 200K token window
Now let’s make sure you have everything you need before we start building.
Prerequisites and Setup
What You Need
You’ll need Python 3.10 or later. Grab an API key from Anthropic—they offer free trials for testing. You should be comfortable with Python’s async/await syntax since the SDK uses asynchronous operations throughout via the anyio library. Basic terminal competence is required since we’ll be running scripts and verifying installations.
Install the SDK
Installation takes one command. The package is claude-agent-sdk on PyPI:
# Install the SDK
pip install claude-agent-sdk
# Set your API key
export ANTHROPIC_API_KEY="your-key-here"
# Verify installation
python -c "from claude_agent_sdk import query; print('SDK installed successfully')"
The SDK reads your Anthropic API key automatically from the ANTHROPIC_API_KEY environment variable. On Windows, use set ANTHROPIC_API_KEY=your-key-here instead. This approach keeps credentials out of your codebase.
The Agent Toolkit: What Your Agent Can Do
The Claude Agent SDK ships with 8 built-in tools that extend what your agent can do beyond simple text generation. Each tool integrates seamlessly—your agent doesn’t need 10 different libraries with conflicting dependencies. As the official documentation explains, these tools give agents genuine computational capabilities.
Core Tools
| Tool | What It Does | Use Case |
|---|---|---|
| Read | Access file contents | Load config files, read existing code |
| Write | Create new files | Generate reports, save results |
| Edit | Modify existing files | Update code, fix bugs |
| Bash | Execute shell commands | Run tests, manage Git, install packages |
| Glob | Find files by pattern | Locate all .py files, search directories |
| Grep | Search file contents | Find specific text in codebase |
| WebSearch | Search the internet | Find trending topics, verify facts |
| WebFetch | Read web pages | Get article content, fetch documentation |
You’re not limited to these 8 tools. The SDK supports Model Context Protocol (MCP) for extending with custom tools specific to your domain. Permission modes let agents request approval before executing sensitive actions—helpful when you’re debugging or running untrusted agent logic.
Building Your Research Agent: Step-by-Step
Step 1: The Simplest Agent (5 Lines)
Let’s start with the absolute minimum—a working agent in 5 lines. The SDK provides a query() function that handles all the complexity for you:
import anyio
from claude_agent_sdk import query
async def main():
async for message in query(prompt="What are the latest trends in AI agents?"):
print(message)
anyio.run(main)
That’s it. The query() function is an async generator that yields responses from Claude as they arrive. The agent will use its available tools to research your question, search the web if needed, and stream the response back. The anyio library handles the async runtime—it works with both asyncio and trio.
Step 2: Configure Your Agent with Options
For more control, use ClaudeAgentOptions to configure the agent’s behavior—system prompt, allowed tools, and permission handling:
import anyio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
# Configure agent behavior
options = ClaudeAgentOptions(
system_prompt="""You are a research assistant specializing in AI and technology.
Your job is to research topics thoroughly, find reliable sources,
and summarize findings with proper citations.""",
allowed_tools=["WebSearch", "WebFetch", "Read", "Write"],
max_turns=10 # Limit agent iterations
)
prompt = "Research the latest developments in agentic AI (January 2026). Provide 3-5 key findings with sources."
async for message in query(prompt=prompt, options=options):
print(message)
anyio.run(main)
The allowed_tools array specifies which of the 8 built-in tools the agent can use—restricting this list improves security and reduces unnecessary tool calls. Tool names are case-sensitive and must match exactly: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch. The max_turns parameter prevents infinite loops by capping the number of agent iterations.
Step 3: Interactive Sessions with ClaudeSDKClient
For multi-turn conversations or bidirectional communication, use the ClaudeSDKClient. This gives you full control over the agent session:
import anyio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
async def research_session():
options = ClaudeAgentOptions(
system_prompt="You are a market research analyst. Provide data-driven insights.",
allowed_tools=["WebSearch", "WebFetch"],
permission_mode="acceptEdits" # Auto-approve read-only operations
)
async with ClaudeSDKClient(options=options) as client:
# First query
await client.query("Find recent funding news about Anthropic")
async for msg in client.receive_response():
print(msg)
# Follow-up query (maintains context)
await client.query("Now compare that to OpenAI's recent funding")
async for msg in client.receive_response():
print(msg)
anyio.run(research_session)
The ClaudeSDKClient uses an async context manager pattern. Within the async with block, you can send multiple queries and the agent maintains full conversation context. The permission_mode option controls how the agent handles tool approvals—"acceptEdits" auto-approves file modifications while still prompting for destructive actions.
Step 4: Permission Control with Hooks
For fine-grained control over what your agent can do, use hooks. These let you intercept tool calls before and after execution:
import anyio
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
# Hook that blocks dangerous bash commands
def block_dangerous_commands(event):
"""Intercept Bash tool calls and block destructive commands."""
if event.tool_name == "Bash":
command = event.tool_input.get("command", "")
dangerous_patterns = ["rm -rf", "sudo", "chmod 777", "mkfs"]
for pattern in dangerous_patterns:
if pattern in command:
print(f"BLOCKED: Dangerous command detected: {command}")
return {"decision": "block", "reason": f"Command contains '{pattern}'"}
print(f"APPROVED: {command}")
return {"decision": "approve"}
async def safe_agent():
options = ClaudeAgentOptions(
allowed_tools=["Bash", "Read", "Write"],
hooks={
HookMatcher(event_type="PreToolUse"): block_dangerous_commands
}
)
async for msg in query(prompt="List files in the current directory", options=options):
print(msg)
anyio.run(safe_agent)
Hooks are particularly useful during development when you’re debugging agent behavior or running untrusted logic. As the ongoing trust challenges in AI automation demonstrate, having guardrails matters. The HookMatcher class supports PreToolUse and PostToolUse events, letting you approve, modify, or block tool calls.

Real-World Use Case: Market Research Agent
Let’s move beyond tutorials to something with real business value. Here’s a complete market research agent that finds recent news about a company, reads the full articles, and synthesizes a structured report:
import anyio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
async def market_research(company: str):
"""Research a company and generate a structured report."""
options = ClaudeAgentOptions(
system_prompt="""You are an institutional equity research analyst.
When researching a company:
1. Search for recent news (last 30 days)
2. Read full articles, not just snippets
3. Cross-reference facts across multiple sources
4. Output a structured report with:
- Executive Summary (2-3 sentences)
- Key Developments (bulleted list)
- Sources (URLs with publication dates)
- Confidence Level (High/Medium/Low based on source quality)""",
allowed_tools=["WebSearch", "WebFetch"],
max_turns=15
)
prompt = f"Research {company}'s latest news, funding, partnerships, and product announcements from January 2026."
report = []
async with ClaudeSDKClient(options=options) as client:
await client.query(prompt)
async for message in client.receive_response():
report.append(message)
print(message, end="", flush=True)
return "".join(report)
# Run the research
if __name__ == "__main__":
result = anyio.run(market_research, "Anthropic")
# Save to file
with open("anthropic_research.md", "w") as f:
f.write(result)
This 47-line script does what would take a human analyst hours. The 200K token context window is the game-changer—your agent can read multiple 5,000-word articles, extract key facts, and cross-reference information across sources without losing coherence. At January 2026 pricing, a typical research task costs approximately $0.30-0.50 using Claude Sonnet 4.5.
Adding Custom Tools with MCP
The 8 built-in tools cover most use cases, but you can extend your agent with custom tools using the Model Context Protocol (MCP). Here’s how to create and register a custom tool:
import anyio
from claude_agent_sdk import query, ClaudeAgentOptions, tool, create_sdk_mcp_server
# Define a custom tool using the @tool decorator
@tool(
name="get_stock_price",
description="Get the current stock price for a given ticker symbol",
parameters={"ticker": str}
)
async def get_stock_price(args):
"""Fetch stock price from an API (simplified example)."""
ticker = args["ticker"].upper()
# In production, you'd call a real API here
mock_prices = {"AAPL": 198.50, "GOOGL": 175.25, "MSFT": 415.80}
price = mock_prices.get(ticker, 0.0)
return {
"content": [
{"type": "text", "text": f"{ticker}: ${price:.2f}"}
]
}
# Create an MCP server with your custom tools
custom_server = create_sdk_mcp_server(
name="finance-tools",
version="1.0.0",
tools=[get_stock_price]
)
async def financial_agent():
options = ClaudeAgentOptions(
system_prompt="You are a financial analyst with access to real-time stock data.",
mcp_servers=[custom_server],
allowed_tools=["WebSearch", "get_stock_price"]
)
async for msg in query(
prompt="What's Apple's current stock price and recent news?",
options=options
):
print(msg)
anyio.run(financial_agent)
The @tool decorator defines the tool’s name, description, and parameters. The create_sdk_mcp_server() function wraps your tools into an in-process MCP server. Then you pass it to ClaudeAgentOptions via the mcp_servers parameter. Your agent can now use both built-in tools and your custom ones.
Common Pitfalls and How to Fix Them
Every framework has rough edges. Here are the mistakes you’ll make (because everyone does) and how to avoid them.
Pitfall 1: Tool Names Are Case-Sensitive
Problem: You get “Tool not found” errors. Cause: Tool names must match exactly—WebSearch not websearch. Solution: Always use the exact names: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch.
Pitfall 2: Forgetting async/await
Problem: Your code hangs or throws coroutine errors. Cause: The SDK is fully async—you can’t call query() synchronously. Solution: Always use async for with query() and run your code with anyio.run(). If you’re in a Jupyter notebook, use %autoawait or wrap in an async cell.
Pitfall 3: Agent Gets Stuck in Loops
Problem: Your agent keeps calling the same tool repeatedly without progress. Cause: Usually an unclear system prompt or missing termination condition. Solution: Set max_turns in your options to cap iterations. Improve your system prompt to define what “done” looks like.
Pitfall 4: WebFetch Returns HTML Junk
Problem: WebFetch brings back navigation menus, ads, and JavaScript rather than article content. Solution: Claude is smart about extracting content, but you can help by adding instructions to your system prompt: “When fetching web pages, extract only the main article content. Ignore navigation, ads, and boilerplate.” The model will filter intelligently.
Pitfall 5: Context Window Exhaustion
Problem: Agent hits the token limit mid-task. Cause: Reading many large files or fetching dozens of long articles. Solution: The SDK handles context compaction automatically, but you can help by instructing the agent to summarize findings as it goes rather than holding everything in memory. The GitHub repository has examples of context management strategies.
Complete Reference: ClaudeAgentOptions
Here’s the full set of options you can configure:
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher
options = ClaudeAgentOptions(
# System prompt defines agent personality and behavior
system_prompt="Your custom instructions here",
# Limit which tools the agent can use (case-sensitive!)
allowed_tools=["Read", "Write", "Edit", "Bash", "Glob", "Grep", "WebSearch", "WebFetch"],
# Maximum agent iterations before forced termination
max_turns=10,
# Permission handling: 'default', 'acceptEdits', 'bypassPermissions'
permission_mode="acceptEdits",
# Custom MCP servers for additional tools
mcp_servers=[],
# Hook functions for intercepting tool calls
hooks={
HookMatcher(event_type="PreToolUse"): your_pre_hook,
HookMatcher(event_type="PostToolUse"): your_post_hook,
}
)
What’s Next: Building More Complex Agents
You’ve built a functional research agent. Here’s how to level up.
Level Up Ideas
- Multi-agent systems: Spin up specialized agents that coordinate—one researches, another writes, a third fact-checks. Use the SDK’s MCP support to let agents communicate.
- Persistent memory: Store knowledge across sessions using a vector database or simple JSON files. Your agent can load context from previous research.
- Domain-specific tools: Build MCP tools that query your company’s APIs, internal databases, or proprietary data sources.
- Production deployment: Add comprehensive logging, error handling, and monitoring so you know when agents fail or behave unexpectedly.
Official Resources
Start with Anthropic’s engineering blog post on the Agent SDK for deeper architectural insights. The Python SDK repository on GitHub contains example code, API documentation, and issue tracking. Check the PyPI package page for version history and release notes.
Related PulseMark Articles
Explore Cursor vs Claude Code vs Windsurf to understand how the Claude Agent SDK fits into the broader AI development ecosystem. Read about the underlying philosophy of how Claude agents think in our deep dive on Anthropic’s 14,000-token constitution that shapes agent behavior.
The Agent Future Starts Now
The Claude Agent SDK turns vague ideas about AI automation into working agents in hours, not weeks. You’ve learned to “give your agent a computer”—and that’s not marketing hyperbole, it’s architectural reality. With version 0.1.21 and the 200K token context window, you have more capability than agent frameworks that cost 10x more in both money and complexity. Start with the research agent you built today. Run it on real queries. Extend it for your specific use case. The developers who win in 2026 won’t be the ones with the biggest budgets—they’ll be the ones who started building first.
Get the Daily Pulse
Sharp analysis on what's actually moving in AI. No hype, no filler, no weekly digest.



