Skip to content
← Blog Tutorials · Field note

Claude Agent SDK: Build Agents on Claude Code's Agent Loop (Python Tutorial)

Run Claude Code's full agent loop — tool execution, hook-driven permissions, in-process MCP servers, and subagents — from Python. Complete working code, no hand-waving.

TURION.AI · · 5 min read
3D wireframe cube in Claude orange dissolving into Python code on a dark terminal, with an agent-loop diagram and tool icons in the foreground

The Claude Agent SDK is not another thin wrapper around an API. It gives you the same agent loop that powers Claude Code — tool execution, context management, permission gating, subagent spawning, and MCP server wiring — but driven programmatically from Python instead of an interactive terminal.

Anthropic’s own framing is blunt: “Claude Code as a library.” That means you inherit the same battle-tested Read/Write/Bash/Grep/Glob tools that developers use inside Claude Code every day, plus a hook system that lets you intercept and override every decision the agent makes.

Here’s what we’ll build in this tutorial: a repo-health agent that scans a directory, identifies issues, and writes a structured report — all with custom tools, permission hooks, and in-process MCP servers.

Installation

pip install claude-agent-sdk

Requirements: Python 3.10+. The Claude Code CLI is bundled with the package — no separate installation needed. If you prefer a system-wide install:

curl -fsSL https://claude.ai/install.sh | bash
# then use: ClaudeAgentOptions(cli_path="/path/to/claude")

Auth: Set ANTHROPIC_API_KEY in your environment. The SDK reads it automatically.

Quick Start: query() for One-Shot Prompts

query() is the simplest entry point: send a prompt, iterate the response stream.

import anyio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock

async def main():
    options = ClaudeAgentOptions(
        cwd="./my-project",
        max_turns=5,
        allowed_tools=["Read", "Grep", "Glob"],
        permission_mode="acceptEdits",
    )

    async for message in query(
        prompt="Scan this repo for security issues. List the top 5.",
        options=options,
    ):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, TextBlock):
                    print(block.text)

anyio.run(main)

Key options worth knowing:

  • allowed_tools — Whitelist. Tools listed here are auto-approved; anything unlisted falls through to permission_mode and hooks. It does not remove tools from Claude’s toolset.
  • disallowed_tools — Blacklist specific tools even if they’d otherwise be available.
  • permission_mode — Controls how Claude handles file edits: "default" (prompt), "acceptEdits" (auto-approve), "bypassPermissions" (everything auto-approved — use with care).
  • max_turns — Caps the number of agent loop iterations. Prevents runaway loops.
  • cwd — Working directory. Claude’s file operations are scoped here.

ClaudeSDKClient: Bidirectional Conversations with Custom Tools

query() is fire-and-forget. For anything production-grade — custom tools, hooks, subagents — you need ClaudeSDKClient. It opens a persistent session you can send multiple prompts to and receive responses from.

Custom Tools via In-Process MCP Servers

The SDK’s standout feature: define tools as Python functions using the @tool decorator, then bundle them into an in-process MCP server. No subprocess, no IPC overhead, no separate deployment.

import anyio
from claude_agent_sdk import (
    tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient,
    AssistantMessage, TextBlock
)

# ── Step 1: Define custom tools ─────────────────────────────

@tool("scan_git_remote", "Check if a git remote URL is reachable", {"url": str})
async def scan_git_remote(args):
    import subprocess
    result = subprocess.run(
        ["git", "ls-remote", args["url"], "--heads"],
        capture_output=True, text=True, timeout=10
    )
    if result.returncode == 0:
        branches = result.stdout.strip().count("\n") + 1 if result.stdout.strip() else 0
        return {
            "content": [{"type": "text", "text": f"Reachable. {branches} branches found."}]
        }
    return {
        "content": [{"type": "text", "text": f"Unreachable: {result.stderr.strip()}"}]
    }

@tool("count_todos", "Count TODO/FIXME/HACK comments in a directory", {"path": str})
async def count_todos(args):
    import subprocess
    import pathlib
    target = pathlib.Path(args["path"])
    if not target.exists():
        return {"content": [{"type": "text", "text": f"Path not found: {args['path']}"}]}
    result = subprocess.run(
        ["grep", "-r", "-E", "(TODO|FIXME|HACK)", str(target), "--include=*.py"],
        capture_output=True, text=True
    )
    count = len(result.stdout.strip().split("\n")) if result.stdout.strip() else 0
    return {
        "content": [{"type": "text", "text": f"Found {count} TODO/FIXME/HACK markers in Python files."}]
    }

# ── Step 2: Bundle tools into an SDK MCP server ─────────────

repo_tools = create_sdk_mcp_server(
    name="repo-tools",
    version="1.0.0",
    tools=[scan_git_remote, count_todos],
)

# ── Step 3: Configure and run ───────────────────────────────

async def main():
    options = ClaudeAgentOptions(
        cwd=".",
        mcp_servers={"repo": repo_tools},
        allowed_tools=["Read", "Grep", "Glob", "mcp__repo__scan_git_remote", "mcp__repo__count_todos"],
        permission_mode="acceptEdits",
        max_turns=8,
    )

    async with ClaudeSDKClient(options=options) as client:
        await client.query(
            "Scan this repository. Count TODOs, check if git remotes in "
            "pyproject.toml point to reachable URLs, and write a short "
            "health report to REPO_HEALTH.md."
        )

        async for msg in client.receive_response():
            if isinstance(msg, AssistantMessage):
                for block in msg.content:
                    if isinstance(block, TextBlock):
                        print(block.text, end="", flush=True)

anyio.run(main)

Tool naming convention: SDK MCP tools are referenced as mcp__<server-name>__<tool-name>. The allowed_tools list uses this format to auto-approve specific tools.

Why In-Process MCP Servers Beat External Ones

ConcernExternal MCP ServerIn-Process SDK Server
Process managementSeparate subprocess per serverRuns in your Python process
LatencyIPC overhead on every tool callDirect function call
DebuggingCross-process, harderSingle process, standard debugger
DeploymentN+1 processes to manageOne Python process
Type safetyJSON serialization boundaryNative Python types

You can still mix both — pass external MCP servers alongside SDK servers in mcp_servers:

options = ClaudeAgentOptions(
    mcp_servers={
        "internal": sdk_server,
        "external": {
            "type": "stdio",
            "command": "python", "args": ["-m", "my_external_server"],
        },
    }
)

Hooks: Intercepting the Agent Loop

Hooks are Python callbacks that fire at specific points in Claude’s agent loop. They run outside Claude’s context — which means they’re deterministic, fast, and can override permission decisions before Claude even sees them.

The most useful hook point is PreToolUse: it fires before any tool execution, giving you a chance to block dangerous commands, inject context, or log every action.

from claude_agent_sdk import HookMatcher

async def validate_bash(input_data, tool_use_id, context):
    """Block destructive Bash commands before execution."""
    if input_data["tool_name"] != "Bash":
        return {}

    command = input_data.get("tool_input", {}).get("command", "")

    dangerous = ["rm -rf /", "sudo", "chmod 777", "> /dev/"]
    for pattern in dangerous:
        if pattern in command:
            return {
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": f"Blocked dangerous command pattern: '{pattern}'",
                }
            }

    return {}

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Write", "Bash"],
    hooks={
        "PreToolUse": [
            HookMatcher(matcher="Bash", hooks=[validate_bash]),
            HookMatcher(matcher="Write", hooks=[log_writes]),  # another hook
        ],
    },
)

HookMatcher takes a matcher (tool name or regex) and a list of hook functions. Each hook returns either {} (pass) or a structured decision object (allow/deny with a reason). The permission evaluation order is documented by Anthropic: disallowed_tools → hook decisions → allowed_tools → permission_mode → interactive prompt.

Available hook events: PreToolUse, PostToolUse, PostToolUseFailure, Notification, Stop, SubagentStop, SessionStart.

Subagents: Spawning Specialized Workers

Subagents are lightweight Claude sessions with their own system prompt and toolset. You spawn them from inside your main agent via the SDK’s task tool.

options = ClaudeAgentOptions(
    system_prompt=(
        "You are a lead developer. Delegate file analysis to subagents. "
        "Use the Task tool to spawn a subagent with instructions like: "
        "'Analyze src/auth.py for security issues. Return a bullet list.' "
        "Aggregate their output into a single report."
    ),
    allowed_tools=["Read", "Write", "Task", "Grep", "Glob"],
    permission_mode="acceptEdits",
)

The Task tool is available when included in allowed_tools. Each subagent gets its own context window, isolated from the parent — but results flow back through the agent loop.

For more on subagent patterns, see our Claude Code Subagents guide.

Error Handling

The SDK surfaces structured error types. Don’t just catch Exception:

from claude_agent_sdk import (
    ClaudeSDKError, CLINotFoundError, CLIConnectionError,
    ProcessError, ResultError, CLIJSONDecodeError,
)

try:
    async with ClaudeSDKClient(options=options) as client:
        await client.query("Analyze this repo")
        async for msg in client.receive_response():
            print(msg)
except CLINotFoundError:
    print("Claude Code CLI not found. Run: curl -fsSL https://claude.ai/install.sh | bash")
except ResultError as e:
    # The agent finished with a terminal error (also yielded as final ResultMessage)
    print(f"Agent failed: subtype={e.subtype}, status={e.api_error_status}")
    print(e.result or e.errors)
except ProcessError as e:
    print(f"CLI process exited with code {e.exit_code}")
except CLIJSONDecodeError as e:
    print(f"Failed to parse Claude's response: {e}")

ResultError is a subclass of ProcessError for runs that exit with a terminal error. It carries structured fields (.subtype, .api_error_status, .result, .errors) you can log or alert on.

When to Use the Claude Agent SDK (vs. Alternatives)

The Claude Agent SDK makes the most sense when:

  • You’re already using Claude Code and want to automate its workflows programmatically.
  • You need MCP-native tooling — the in-process server model is cleaner than anything in the OpenAI or Google SDKs.
  • You want hook-driven guardrails — PreToolUse/PostToolUse hooks give you deterministic control the other SDKs don’t match.
  • You’re building developer tools — Read/Write/Bash/Grep/Glob as built-in tools are purpose-built for code.

It makes less sense when:

  • You need multi-model routing — this is Claude-only.
  • You want declarative graph-based orchestration — use LangGraph instead.
  • You’re building a cross-platform agent that spans OpenAI + Anthropic — use the OpenAI Agents SDK or an abstraction layer.

For a head-to-head comparison of the Claude Agent SDK against the OpenAI Agents SDK, see our three-way comparison with Google ADK.

What We Shipped

The repo-health agent we built in this tutorial:

  1. Uses ClaudeSDKClient for persistent, bidirectional sessions
  2. Exposes two custom tools (scan_git_remote, count_todos) via an in-process MCP server
  3. Validates Bash commands with a PreToolUse hook that blocks dangerous patterns
  4. Spawns subagents via the Task tool for parallel file analysis
  5. Handles errors structurally with ResultError and ProcessError

All of this runs inside a single Python process. No Docker, no sidecars, no YAML config — just pip install claude-agent-sdk and an API key.

The SDK is still young (renamed from Claude Code SDK in June 2026), but the fact that it bundles Claude Code’s full agent harness means it inherits thousands of hours of production battle-testing. For Python developers building code-aware agents, it’s the most direct path from idea to working prototype we’ve seen this year.