CLAUDE LABJP
PRICING — September 1 was the scheduled date for the Sonnet 5 price increase, and it did not happen. The introductory $2/$10 per MTok now stands as the regular pricePARTNER — Salesforce and Anthropic announced Claudeforce, an expanded partnership. The Salesforce in Claude plugin ships with 37 prebuilt sales skills, from meeting prep to pipeline managementTRUST — Claudeforce serves Claude through Amazon Bedrock inside the Salesforce Trust Boundary, so data and inference never leave the security perimeter — an answer aimed squarely at regulated industriesBETA — Salesforce in Claude is with select pilot customers for now, with an open beta expected during SeptemberLIMITS — The 50% weekly-limit boost runs through September 13. From September 14 the permanent level is 25% above the pre-promotion baseline, roughly a 17% cut from todayRELEASE — Claude Code has shipped nothing since v2.1.251 on August 28. Against a pace of one release every 0.8 days, a four-day gap is among the longest yetPRICING — September 1 was the scheduled date for the Sonnet 5 price increase, and it did not happen. The introductory $2/$10 per MTok now stands as the regular pricePARTNER — Salesforce and Anthropic announced Claudeforce, an expanded partnership. The Salesforce in Claude plugin ships with 37 prebuilt sales skills, from meeting prep to pipeline managementTRUST — Claudeforce serves Claude through Amazon Bedrock inside the Salesforce Trust Boundary, so data and inference never leave the security perimeter — an answer aimed squarely at regulated industriesBETA — Salesforce in Claude is with select pilot customers for now, with an open beta expected during SeptemberLIMITS — The 50% weekly-limit boost runs through September 13. From September 14 the permanent level is 25% above the pre-promotion baseline, roughly a 17% cut from todayRELEASE — Claude Code has shipped nothing since v2.1.251 on August 28. Against a pace of one release every 0.8 days, a four-day gap is among the longest yet
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-code131SDK4agent13autonomous-agentPython17TypeScript24MCP52automation107

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 $15 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-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.
📚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 →