◉CLAUDE LABJP
●2.1.301 — Adds the vim % motion, LaTeX math rendering in the VS Code panel, and a retry-watchdog limit for usage-limit waits (10/15)●2.1.299 — Conversations over 200K tokens left idle about 54 minutes get compacted; MCP allow rules now match only the server they name●SONNET 4.5 — Retires on the Claude API on 11/30, 45 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST MODE — Opus 5.5 fast mode is out of research preview and no longer needs the beta header (10/15)●NEW — I Put a Ten-Line Promise File at the To…●2.1.301 — Adds the vim % motion, LaTeX math rendering in the VS Code panel, and a retry-watchdog limit for usage-limit waits (10/15)●2.1.299 — Conversations over 200K tokens left idle about 54 minutes get compacted; MCP allow rules now match only the server they name●SONNET 4.5 — Retires on the Claude API on 11/30, 45 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST MODE — Opus 5.5 fast mode is out of research preview and no longer needs the beta header (10/15)●NEW — I Put a Ten-Line Promise File at the To…
Articles/Claude Code
⟐ Claude Code/2026-04-17Advanced

Building a Custom Autonomous Agent Loop with Claude Code SDK — Beyond the CLI

Understand the internals of the Claude Code SDK and build custom autonomous agent loops in Python and TypeScript. Covers tool permissions, error recovery, and streaming, plus the cost instrumentation and monthly model audits I rely on in real operation.

claude-code132SDK4agent14autonomous-agentPython22TypeScript24MCP54automation109

✦ Premium Article

There comes a point when using Claude Code where you hit a wall. You want finer control. You want to intercept at a specific moment. You want to run headless batch jobs without interactive prompts. When those needs arise, the official CLI options alone won't cut it.

What many developers don't realize is that Claude Code has an SDK underneath the CLI — accessible from Python or TypeScript. With the SDK, you can handle tool execution yourself, process streaming events at a granular level, and orchestrate multiple agents programmatically. Things that simply aren't possible through the CLI.

I run loops like this every day. As an indie developer, I keep several technical blogs updated through SDK-based autonomous agents that format articles and check bilingual consistency overnight, with nobody watching. The measurement and recovery patterns in this article come straight out of that operation.

What the SDK Gives You (and How It Differs from the CLI)

Let's start by clarifying what the Claude Code SDK actually is.

The Claude Code CLI (claude command) is designed for interactive human use. It receives a prompt, asks for permission, and walks through file operations and command execution interactively. This is great for human collaboration, but it's a poor fit for automated pipelines.

The SDK removes those constraints. You call Claude programmatically, apply your own logic to decide whether tools should run, and receive results as structured data. Concretely:

  • Automated tool permissions: Pass an allowed_tools list and tools run without individual confirmation prompts
  • Programmable event handling: Handle tool_use, text, result, and other events one at a time
  • Session management: Carry session IDs forward to maintain conversation context
  • Parallel execution: Spin up multiple Claude instances simultaneously and coordinate them

For automation, CI/CD pipelines, code generation at scale, and batch processing of routine tasks, the SDK is the right tool.

Python SDK Setup and Basic Structure

Let's start with the setup.

# Install the SDK
pip install claude-code-sdk
 
# Claude Code CLI is also required (the SDK uses it under the hood)
npm install -g @anthropic-ai/claude-code
 
# Verify auth
claude --version

Here's the most basic agent you can write:

import asyncio
from claude_code_sdk import query, ClaudeCodeOptions
 
async def run_simple_agent():
    """The simplest possible agent execution."""
    
    options = ClaudeCodeOptions(
        max_turns=5,           # Critical: prevents infinite loops
        allowed_tools=["Read", "Write", "Bash"],
    )
    
    # query() returns an async generator of messages
    async for message in query(
        prompt="Read src/app.py and suggest 3 improvements",
        options=options
    ):
        if message.type == "assistant":
            for block in message.content:
                if block.type == "text":
                    print(f"Claude: {block.text}")
        
        elif message.type == "result":
            print(f"\nDone — total cost: ${message.cost_usd:.4f}")
            print(f"Turns used: {message.num_turns}")
            break
 
asyncio.run(run_simple_agent())

max_turns=5 is critical. Without it, you can occasionally end up with an agent that never reaches end_turn — especially on ambiguous tasks.

✦

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
✦A cost-logging layer that records per-run spend from ResultMessage, with the measured distribution from real operation ($0.04-0.12 average per run)
✦A five-point monthly model-audit checklist that keeps autonomous loops alive through default-model switches and fast-mode retirements
✦A practical decision framework for choosing between a custom SDK loop, the CLI, and Managed Agents, based on how the landscape shifted in early 2026
Secure payment via Stripe · Cancel anytime
✦

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

Related Articles

⟐ Claude Code2026-07-27
Whose Environment Expands That Variable? Fingerprinting Your Effective Managed MCP Policy
Variable references in the Managed MCP allowlist and denylist now resolve from the startup environment and the managed-settings env block. I rebuilt both resolution orders locally to see where verdicts diverge, then wrote a preflight check that reduces the effective policy to a comparable fingerprint.
⟐ Claude Code2026-04-30
Composing Claude Code Skills — Building Automation a Single Skill Can't Reach
A practical guide to going beyond one-skill-at-a-time and composing multiple Claude Code Skills into real workflows. Pipeline, branching, and meta-skill patterns with full implementation examples and the failure modes you should design against.
⟐ Claude Code2026-03-28
Running Claude Code × Playwright E2E Tests in Production — Pitfalls and Decision Criteria
Implementation patterns for running E2E tests with Claude Code and Playwright in production, plus how to measure whether the investment pays back. Includes the Cloudflare Workers and Pages preview deployment pitfalls, and a decision framework that indie developers can use to judge whether E2E tests are worth the investment.