# How to Create AI Agents using Claude Agent SDK (A Step by Step Guide)

Bildad Oyugi

## Introduction
Artificial intelligence agents are transforming how we automate complex workflows, perform multi-step tasks, and interact with data and external services.

Among the leading tools empowering developers to build such AI agents is the **Claude Agent SDK** from Anthropic. This powerful SDK enables you to create reliable, production-ready AI agents that leverage the state-of-the-art **Anthropic AI Claude** models, including **Claude Code** and **Claude Opus**, to perform sophisticated code execution, file operations, semantic search, and more. The Claude Agent SDK provides all the building blocks needed to build production-ready agents.

In this guide, we’ll walk you through everything you need to know about the **Claude Agent SDK**—from installation and setup to building specialized agents with custom tools and managing context effectively.

## What is the Claude Agent SDK, and How Does it Work?
The **Claude Agent SDK** is a developer toolkit designed to build interactive AI agents powered by Anthropic’s **aligned frontier models,** such as **Claude Code** and **Claude Opus**.

These AI agents can autonomously perform tasks by **gathering context**, executing code, interacting with external APIs, managing filesystems, and more—all while following a structured loop of reasoning and action.

The key design principle behind the Claude Agent SDK is to give agents access to a computer. Agents run in a sandboxed container to enhance security and isolate processes, preventing prompt injection and other risks. The SDK supports subagents by default, enabling parallelization of tasks.

### Core Features
- **Define an agent’s role** and behavior through **system prompts** and configuration.
- Use built-in or **custom tools** to extend your agent’s capabilities.
- Manage **context** efficiently with automatic prompt caching and session management.
- Execute **multi-step tasks** with streaming interaction and built-in error handling.
- Safely operate with permission modes that block **dangerous commands** and require human approvals.
- Utilize checkpoints that automatically save an agent's progress, allowing for instant rollback during development.

The SDK works by connecting your code to Anthropic’s **Claude API** via your **Claude API key**, allowing you to build **production-ready agents** that can be embedded in Python or TypeScript applications.

## How to Create an AI Agent with Claude Agent SDK
Creating an AI agent using the **Claude Agent SDK** involves several key steps, from setup to deployment. They include:

### Step #1. Set up prerequisites
- **Choose a language**: The SDK is available for TypeScript (Node.js/web) and Python. Pick whichever fits your stack.
- **Install system dependencies**: Ensure you have:
  - Python ≥ 3.10 and Node ≥ 18 (for the CLI tools).
  - An Anthropic API key from the Claude Console. Set it in the environment as ANTHROPIC_API_KEY. If you use Bedrock or Vertex AI, set the appropriate environment variables (CLAUDE_CODE_USE_BEDROCK or CLAUDE_CODE_USE_VERTEX).
- **Install the CLI and SDK**:
  - Install the Claude Code/Agent CLI globally: `npm install -g @anthropic-ai/claude-code` or run the installer script (`curl -fsSL https://claude.ai/install.sh | bash`).
  - Install the Agent SDK library: `pip install claude-code-sdk` (Python) or `npm install @anthropic-ai/claude-agent-sdk` (TypeScript).
- **Verify installation**: Run `claude doctor` to ensure the CLI works, and test a simple streaming query to confirm your SDK install (e.g., query "What is 2+2?").

### Step #2. Understand the agent loop
The Claude Agent SDK follows a structured loop of **gathering context → taking action → verifying work → repeating**. Agents use tools to fetch context (files, APIs), perform actions (running code, calling APIs), then check the results and decide whether to continue.

### Gathering context
- The SDK can perform **agentic search** on a file system using typical developer commands (grep, find, glob) to pull relevant files into context.
- Subagents can run in parallel to collect specific information and send back only relevant snippets.

### Taking action
- Tools are the primary way your agent acts. Built-in tools include file operations (Read/Write/Grep/Glob), Bash for shell commands, web fetch for API calls, and multi-language code execution.
- You design **custom tools** to extend the agent. Tools must have descriptive names, a schema for arguments, and a function that returns results.

### Verification and repetition
- After each action, the agent can verify the output (e.g., run tests or linting, check file contents, or present results to a human for approval).

### Step #3. Define the agent’s role and operational options
Use the SDK’s options object to set the agent’s role, working directory, allowed tools, and permission strategy. A typical configuration looks like this (Python example):
```python
from claude_code_sdk import ClaudeCodeOptions

# Step 1: Define the agent's role
options = ClaudeCodeOptions(
    system_prompt="You are a Python code reviewer focused on security",
    cwd="/path/to/project"
)

# Step 2: Set operational parameters
options.allowed_tools = ["Read", "Grep"]       # Tools the agent can use
options.permission_mode = "manual"             # or "acceptEdits", "acceptAll"
options.max_turns = 5                          # Limit number of iterations
```

### Step #4. Run the agent via the high-level interface
Start interacting with your agent by calling the high-level query function or by creating a persistent client:
```python
import anyio
from claude_code_sdk import query, ClaudeSDKClient

# Option A: One-off query (streaming):
async def run_query():
    async for msg in query("Review main.py for security issues", options=options):
        for block in msg.content:
            if block.type == "text":
                print(block.text)
            elif block.type == "tool_use":
                print(f"Using tool: {block.tool_name}")

# Option B: Persistent client for multi-turn interactions:
async def run_client():
    async with ClaudeSDKClient(options=options) as client:
        await client.query("Find all SQL queries in the codebase")
        async for response in client.receive_response():
            pass

anyio.run(run_query)
```

### Step #5. Add custom tools and subagents
1. **Create custom tools** using the `@tool` decorator. Each tool should describe its purpose and argument schema, then implement the logic.
```python
from claude_code_sdk import tool, create_sdk_mcp_server

@tool("security_scan", "Scan code for vulnerabilities", args_schema={"file": str})
async def security_scanner(args):
    file_path = args["file"]
    return {"content": [{"type": "text", "text": f"Scanned {file_path}"}]}

server = create_sdk_mcp_server(
    name="security-tools",
    version="1.0.0",
    tools=[security_scanner]
)
options.mcp_servers = {"security": server}
options.allowed_tools.append("mcp__security__security_scan")
```

1. **Define subagents** by creating Markdown files in `.claude/agents/` with YAML front-matter specifying their role, allowed tools, and model.

### Step #6. Manage context and memory
- **Automatic context compaction** ensures long-running agents stay within the model’s context window.
- The CLI and SDK look for [CLAUDE.md](http://claude.md/) or `.claude/` [CLAUDE.md](http://claude.md/) files to maintain persistent context across sessions.

### Step #7. Apply best practices
- **Start small**. Build simple agents first, such as one-shot tasks or single-tool automation, before composing complex workflows.
- **Use least-privilege permissions**. Grant only the tools your agent truly needs.

By following these steps, you can create robust AI agents that operate autonomously yet safely using Anthropic’s Claude Agent SDK.
