CLAUDE LABJP
FORK — Claude Code 2.1.212 changes what /fork does: it copies your conversation into a new background session with its own row in claude agents, so you can keep working. The old in-session subagent is now /subtaskLIMITS — WebSearch calls are now capped at 200 per session by default, and subagent spawns get the same 200 ceiling, so a runaway search or delegation loop stops on its ownMCPBG — MCP tool calls running past two minutes now move to the background automatically, keeping the session usable. Tune the threshold with CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSPLANFIX — Fixed plan mode auto-running file-modifying Bash commands such as touch and rm without a permission prompt or an SDK canUseTool callbackSONNET5 — Claude Sonnet 5 is running on introductory pricing of $2 per million input tokens and $10 per million output. After August 31 it moves to $3 and $15IPO — Bankers are reportedly lining up investor meetings for Anthropic ahead of a possible public listing as soon as OctoberFORK — Claude Code 2.1.212 changes what /fork does: it copies your conversation into a new background session with its own row in claude agents, so you can keep working. The old in-session subagent is now /subtaskLIMITS — WebSearch calls are now capped at 200 per session by default, and subagent spawns get the same 200 ceiling, so a runaway search or delegation loop stops on its ownMCPBG — MCP tool calls running past two minutes now move to the background automatically, keeping the session usable. Tune the threshold with CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSPLANFIX — Fixed plan mode auto-running file-modifying Bash commands such as touch and rm without a permission prompt or an SDK canUseTool callbackSONNET5 — Claude Sonnet 5 is running on introductory pricing of $2 per million input tokens and $10 per million output. After August 31 it moves to $3 and $15IPO — Bankers are reportedly lining up investor meetings for Anthropic ahead of a possible public listing as soon as October
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-code129SDK4agent13autonomous-agentPython17TypeScript24MCP45automation95

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-17
The Morning My Table Ended in "… 2,847 more rows" — Separating Render Caps from Token Cost in Tool Output
Claude Code 2.1.209 caps markdown tables at 200 rows plus a remainder count. Only the rendering is capped — the model still receives every row. Here is how to measure the gap and redesign tool output around aggregates.
Claude Code2026-07-15
Answering auto mode's confirmation prompts in headless runs — a deny-by-default permission-prompt-tool
auto mode's confirmation step is a friend when you're at the keyboard, but in an unattended midnight run it becomes the reason a job sits waiting until morning. Here is how I catch those prompts with permission-prompt-tool, decide deny-by-default, and log every ruling — with working code.
Claude Code2026-07-14
One Day My Push Had an Extra Destination — Guarding Against /commit-push-pr Pushing to Remotes Beyond origin
The July 14 update made /commit-push-pr push to configured push remotes in addition to origin. Convenient, but if you keep a mirror or backup as a second remote, unintended pushes quietly multiply. Here is how to inventory which remotes you can push to, block anything off the allowlist with a pre-push hook, and keep unattended runs safe — with working code.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →