Claude Agent SDK Overview for Developers
AI generated
Claude
>_
Claude AI · Agent SDK · Tool Calling · Development
Claude Agent SDK Overview for Developers
From the agent loop to a production agent

The Claude Agent SDK exposes the same agent loop that Claude Code uses internally: tool call, execution, context update and a new model request, all in one controlled cycle. Anyone building custom automation, internal developer tools or customer products on top of Claude can use this loop directly instead of implementing it from scratch.

19 min read Agent Loop · Tools · Permissions · Subagents Python · TypeScript · Claude Code

1. What the Claude Agent SDK actually is

The Claude Agent SDK is not just another chat library, it is the productized version of the agent loop that runs internally inside Claude Code. Instead of deciding, project by project, how a language model calls tools, processes their results and determines when a task is complete, the SDK handles this loop end to end. Developers get the same foundation the official command line tool is built on, packaged as an embeddable library for custom applications in Python and TypeScript.

The practical difference to a plain API call matters here. A raw call to the Claude API returns a single response to a single request. An agent built on the Claude Agent SDK, by contrast, plans multiple steps, calls tools along the way, reads their results, adjusts its plan and repeats this cycle until the goal is reached or a limit kicks in. For tasks like automated debugging, multi step data processing or complex code migrations, this loop is exactly the building block that would otherwise need to be reimplemented for every project using raw API access.

2. Architecture: agent loop, tools and permissions

The architecture of the Claude Agent SDK consists of three connected layers. The bottom layer is the agent loop itself: a control flow that accepts a user request, sends it to the model, reacts to tool calls in the response stream, executes those calls and feeds the results back into the context. This loop keeps running until the model returns a final text answer without a further tool call, or a configured maximum number of turns is reached.

The second layer is the tool system: a declarative description of available functions with a name, description and a JSON schema for the parameters. Built in tools such as file system access, shell execution or web search are available immediately, and custom tools are added through simple function signatures. The third layer is the permission system, which forces a decision before every potentially risky tool call, such as writing a file or executing a shell command: allow automatically, deny automatically, or delegate to a callback function for a runtime check. Together these three layers turn the Claude Agent SDK into a complete framework rather than a thin API wrapper.


# Install the Claude Agent SDK (Python variant)
pip install claude-agent-sdk

# TypeScript / Node.js variant
npm install @anthropic-ai/claude-agent-sdk

# Authenticate via API key (same key as the raw Claude API)
export ANTHROPIC_API_KEY="sk-ant-..."

3. Installation and your first agent setup

Getting started with the Claude Agent SDK begins with a minimal agent that skips custom tools entirely and relies only on the built in file system capabilities. The basic pattern: a configuration with a system prompt, allowed tools and a working directory is passed to the query function, which returns an asynchronous stream of events. Each event in the stream corresponds to one step of the agent loop, such as a text block, a tool call or a tool result.

Important for production use: the session configuration lets you explicitly restrict the working directory to a single project folder, so the agent cannot read or write files outside that boundary. This restriction is the first of several security mechanisms covered in more depth in the permissions section. For a first test, a simple prompt asking the agent to summarize the contents of a directory is enough.


# minimal_agent.py - first agent using the Claude Agent SDK
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        system_prompt="You are a concise code review assistant.",
        allowed_tools=["Read", "Grep", "Glob"],
        cwd="./my-project",
        max_turns=8,
    )

    async for event in query(
        prompt="Summarize the structure of this project in five bullet points.",
        options=options,
    ):
        if event.type == "text":
            print(event.text, end="")
        elif event.type == "tool_use":
            print(f"\n[tool] {event.tool_name}({event.tool_input})")

asyncio.run(main())

4. Defining custom tools as agent capabilities

Built in tools cover generic capabilities, but the real value of the Claude Agent SDK appears once custom tools expose project specific knowledge. In the SDK, a tool is an annotated function with typed parameters and a clear description that serves as the model's decision basis. From this signature, the SDK automatically generates the JSON schema communicated to the model, so developers never maintain the schema by hand.

A realistic example for an internal developer tool: a function that queries the status of a deployment from an internal API and returns it in a structured form. It is essential that error cases are handled cleanly inside the tool rather than letting an exception propagate all the way into the agent loop. The model instead receives a structured error message in the tool result and can react to it, for instance by proposing an alternative strategy.


# custom_tool.py - defining a project-specific tool
from claude_agent_sdk import tool

@tool(
    name="get_deployment_status",
    description="Fetch the current deployment status for a given environment.",
)
async def get_deployment_status(environment: str) -> dict:
    # NOTE: replace with a real internal API call in production
    valid_envs = {"staging", "production"}
    if environment not in valid_envs:
        return {"error": f"Unknown environment: {environment}"}

    # Simulated lookup — swap for httpx.get(...) against the real endpoint
    status_by_env = {"staging": "healthy", "production": "degraded"}
    return {"environment": environment, "status": status_by_env[environment]}

5. Subagents and orchestrating multiple agents

For complex tasks, a single agent reaches its limits once several independent subtasks need to be handled in parallel or with different context. The Claude Agent SDK supports this through subagents: specialized agents with their own system prompt, their own tool set and their own isolated context window, invoked deliberately by a parent orchestrator agent. A subagent for test coverage needs different tools and a different focus than a subagent for documentation, and neither should burden the other with irrelevant context.

Orchestration works through a dedicated tool that the main agent calls to start a subagent run and receive its final result. The subagent operates in its own context window, separate from the main agent, so long intermediate steps taken by the subagent do not consume the main agent's context budget. Only the compressed final result flows back. This pattern not only reduces token usage, it also allows several subagents to run in parallel for independent subtasks, which meaningfully shortens the total runtime of complex workflows.

6. Context management for long sessions

Long agent sessions with many tool calls fill up the context window quickly, especially when tools return large amounts of data such as full file contents or API responses. The Claude Agent SDK provides built in mechanisms for context compression: older tool results can be automatically summarized or dropped once a configurable threshold is exceeded, while the current state of the task is preserved.

For production applications it makes sense not to leave this behavior to chance but to explicitly configure the maximum turn count and the compression threshold. An agent that runs code reviews across hundreds of files benefits from more aggressive compression than an agent working through a single, focused debugging session. Anyone who does not monitor context size risks either truncated, incomplete answers or unnecessarily high API costs from redundantly carried context.

7. Permissions and the security model

An agent that can execute shell commands or write files is a significant security risk without controls, particularly when it reacts to user input that is not fully trusted. The Claude Agent SDK addresses this with an explicit permission model at three levels: an allowlist of permitted tools, fine grained rules per tool call, such as read only access to a specific directory, and a callback function that decides on every individual call at runtime.

In practice this means: before the agent executes a shell command, a callback function can inspect the actual command and, for example, block destructive operations such as rm -rf while letting harmless read commands pass through automatically. This check happens before execution, not after, so a risky command never reaches the system in the first place. For production deployments, a deny by default strategy is generally recommended: only explicitly approved tools and paths are allowed, everything else is rejected and reported transparently to the user.

8. Deployment: from the CLI to a production service

Moving from a local experiment to a production service takes more than calling the query function in an infinite loop. A production deployment of the Claude Agent SDK needs persistent session management so a user can continue a conversation across multiple HTTP requests without resending the entire history on every request. The SDK supports this through session IDs, which let a running agent state be referenced and resumed on the server side.

On top of that, a production service needs monitoring for token consumption per session, timeouts for stuck tool calls, and a strategy for concurrent requests, since every active agent session consumes compute time and memory. A proven pattern is to manage agent sessions in a queue and cap the number of concurrently running sessions through a worker pool limit, rather than processing every incoming request immediately and without bounds. This keeps cost control intact even under fluctuating load.


// server-agent.ts - session-aware agent endpoint (simplified)
import { query } from "@anthropic-ai/claude-agent-sdk";

interface AgentRequest {
  sessionId?: string;
  prompt: string;
}

export async function handleAgentRequest(req: AgentRequest) {
  const options = {
    sessionId: req.sessionId, // resume an existing session if provided
    allowedTools: ["Read", "Grep"],
    maxTurns: 10,
    permissionMode: "default", // deny-by-default for anything unlisted
  };

  const events = [];
  for await (const event of query({ prompt: req.prompt, options })) {
    events.push(event);
  }
  return events;
}

9. Agent SDK compared to raw API access and frameworks

The choice between the Claude Agent SDK, raw API access and a generic orchestration framework depends on the complexity of the task. A raw API call is sufficient for simple, single turn requests without tool use. A generic framework with its own agent abstraction offers more flexibility across different model providers, but requires custom built logic for things the agent SDK already ships with natively.

Criterion Raw Claude API Claude Agent SDK Generic framework
Agent loop Implement yourself Built in Built in, generic
Permission system Not available Native, fine grained Usually an add on package
Subagents Orchestrate manually Natively supported Depends on framework
Switching model providers Not applicable Claude only Multiple providers
Setup effort Minimal Low to moderate High

For teams that primarily rely on Claude as their model and want to build a production ready agent quickly, the Claude Agent SDK is the most efficient choice, because it provides the agent loop, permission system and subagent orchestration without an extra abstraction layer. Generic frameworks pay off mainly when switching model providers is a realistic scenario or existing infrastructure is already built on such a framework.

Mironsoft

AI agents, automation and Claude integration for developer teams

Want a custom agent built with the Claude Agent SDK?

We design and implement production ready agents based on the Claude Agent SDK, including tool design, permission model and deployment strategy tailored to your use case.

Architecture consulting

Agent design, tool boundaries and subagent orchestration for your use case

Implementation

Custom tools, permission callbacks and context management, built production ready

Deployment

Session management, monitoring and cost control for production operation

10. Summary

The Claude Agent SDK wraps the agent loop, the tool system and the permission model that also power Claude Code internally, as an embeddable library for Python and TypeScript. Custom tools are defined through typed function signatures, from which the SDK automatically generates a JSON schema. Subagents allow orchestrating specialized sub agents with their own context window, which saves token budget on complex, multi step tasks and enables parallel work.

Production use requires, beyond plain SDK usage, a well thought out permission strategy following the deny by default principle, active context management against runaway context windows, and a session architecture with monitoring for cost and timeouts. Compared to raw API access, the Claude Agent SDK saves substantial implementation effort without sacrificing control over the agent's security and behavior.

Claude Agent SDK for developers — the essentials at a glance

Agent loop

Tool call, execution, context update and a new model request, in a built in, controlled loop instead of a custom implementation.

Tools & permissions

Custom tools via typed functions, fine grained permission callbacks before every risky call.

Subagents

Specialized sub agents with their own context window, orchestrated by the main agent, saving tokens and enabling parallelism.

Production operation

Session IDs for resuming conversations, active context management, monitoring for token cost and timeouts.

11. FAQ: Claude Agent SDK for developers

1Difference from the raw Claude API?
The SDK additionally wraps the agent loop with tool calls and repeated model requests until a multi step task is complete.
2Which languages are supported?
Python and TypeScript/Node.js as official packages with a largely identical API structure.
3How do I define a custom tool?
Through an annotated function with typed parameters, from which the SDK automatically generates the JSON schema.
4What are subagents?
Specialized agents with their own context window, invoked by a main agent to save tokens and work in parallel.
5How do I control allowed actions?
Through allowlists, fine grained rules per call and a callback function that checks every call at runtime.
6How do I prevent an overflowing context window?
Use built in context compression and explicitly cap the maximum turn count.
7Can I run an HTTP service instead of a CLI?
Yes, session IDs let you reference and resume agent state on the server across multiple requests.
8Is the SDK production ready?
Yes, provided monitoring, timeouts and a deny by default permission strategy are added.
9When does a generic framework make sense?
When switching model providers is realistic, or existing infrastructure already sits on such a framework.
10Does shell access need special safeguards?
Yes, a permission callback function should actively inspect every shell command before execution and block destructive operations.