Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FrameworksAI guideIntermediate#frameworks#claude#anthropic#agents
Frame · ai-engineering / frameworks / 09-claude-agent-sdk.mdGuide 045 / 103

Claude Agent SDK, Claude Code as a library

The Claude Agent SDK is Anthropic's framework for building agents, and it takes an unusual approach: instead of giving you an empty loop to fill with tools, it gives you the same harness that powers Claude Code. That means file reading and editing, shell commands, web search, context management, permissions, hooks, subagents, sessions and MCP support are all there from the first line. It ships for Python (claude-agent-sdk) and TypeScript (@anthropic-ai/claude-agent-sdk), both still on 0.x version numbers as of October 2026.

Why it matters

Most agent frameworks make you build the "computer" the agent works on. You define tools for reading files, running commands and searching, then you discover all the edge cases (huge files, long outputs, context limits, dangerous commands). The Claude Agent SDK starts from an agent that already knows how to work in a workspace.

According to the official overview, the SDK gives you these Claude Code capabilities:

  • Built-in tools: read, write and edit files, run commands, search files and the web.
  • Hooks: run your own code at key points in the agent lifecycle, for example before a tool runs.
  • Subagents: spawn specialized agents for focused subtasks, each with its own context.
  • MCP: connect external tools and data through the Model Context Protocol, including in-process servers you define in your own code.
  • Permissions: decide which tools run automatically and which need approval.
  • Sessions: keep context across exchanges, then resume or fork later.
  • Skills, commands, memory and plugins: loaded from the project's .claude/ folder, the same way Claude Code loads them.

This makes it a strong choice for agents whose work looks like a knowledgeable person at a computer: code review bots, data analysis agents, research agents, internal ops assistants, CI fixers.

How it works

You call query() with a prompt and options, and iterate over the messages it streams back. Under the hood the SDK runs the Claude Code binary (bundled with the package on most platforms), which runs the agent loop.

Rendering diagram…

The options object is where you shape the agent. allowedTools pre-approves tools; tools controls which built-ins are even visible; permissionMode sets the overall approval stance (for example auto approving edits); systemPrompt customizes behavior; mcpServers adds your tools. Custom tools are defined with tool() and wrapped in an in-process MCP server with createSdkMcpServer, and their full names follow the pattern mcp__{server}__{tool}.

Reference architecture

A typical deployment runs the SDK inside a container per task or per user session, with the workspace mounted and your business tools exposed through MCP.

Rendering diagram…

Because the agent can run real commands, isolation is part of the architecture, not an afterthought: a container or sandbox per task, scoped credentials, and an allowlist of tools.

Code

A TypeScript agent that triages a repository's failing tests, with one custom tool that files a ticket. It follows the quickstart and custom tools docs.

import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const fileTicket = tool(
  "file_ticket",
  "File a bug ticket in the tracker",
  {
    title: z.string().describe("Short ticket title"),
    body: z.string().describe("Details, including failing test names"),
  },
  async (args) => {
    // Call your tracker API here
    return { content: [{ type: "text", text: `Filed ticket: ${args.title}` }] };
  }
);

const tracker = createSdkMcpServer({
  name: "tracker",
  version: "1.0.0",
  tools: [fileTicket],
});

for await (const message of query({
  prompt:
    "Run the test suite, find the root cause of any failures, " +
    "and file one ticket per distinct cause. Do not edit files.",
  options: {
    allowedTools: ["Read", "Grep", "Glob", "Bash", "mcp__tracker__file_ticket"],
    mcpServers: { tracker },
    systemPrompt: "You are a careful senior engineer triaging CI failures.",
  },
})) {
  if (message.type === "assistant" && message.message?.content) {
    for (const block of message.message.content) {
      if ("name" in block) console.log(`Tool: ${block.name}`);
    }
  } else if (message.type === "result") {
    console.log(`Done: ${message.subtype}`);
  }
}

The Python version is almost identical:

import asyncio
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query


async def main():
    async for message in query(
        prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Glob"],
            permission_mode="acceptEdits",
        ),
    ):
        if isinstance(message, ResultMessage):
            print(f"Done: {message.subtype}")


asyncio.run(main())

Set ANTHROPIC_API_KEY in the environment (the SDK does not load .env files for you), or configure Amazon Bedrock, Google Cloud or Microsoft Foundry through the documented environment variables.

Trade-offs and pitfalls

  • Claude only. The SDK is built around Claude models. If provider neutrality is a hard requirement, pick something else or put it behind your own interface.
  • Powerful tools need guardrails. Bash and Edit are real. Run in a sandbox, scope credentials, keep allowedTools tight, and use hooks to block or log risky calls.
  • Heavier runtime. It runs the Claude Code binary, not just HTTP calls. That is what gives you the harness, but it means more to package and a process per agent run.
  • Config loading from .claude/. Skills, commands and memory files in the working directory affect behavior. Know what is in the workspace you point it at.
  • Pre-1.0 APIs. Message types and options evolve; read the changelogs for both SDKs when upgrading.
  • Auth and branding rules. Third party products must use API key style authentication rather than claude.ai login, and follow Anthropic's branding guidelines.

When to pick it: agents that work on files, code or data in a workspace, tasks where you would otherwise rebuild Claude Code's tools, or teams already using Claude Code and its skills and plugins who want the same behavior in a product or CI job.

When not to: simple chat or structured extraction (use the Claude API directly), strict multi provider requirements, or you want Anthropic to host the whole agent (look at Managed Agents instead).

Checklist

  • Start with read only tools (Read, Grep, Glob) and add write tools deliberately.
  • Run each agent task in an isolated container or sandbox.
  • Expose business systems as MCP tools with narrow, well described inputs.
  • Use hooks for audit logging and policy checks on tool calls.
  • Use subagents to keep the main context small on big tasks.
  • Store session ids if users need to resume or fork conversations.
  • Pin SDK versions and test upgrades against a fixed set of tasks.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.