Getting Started with Claude Agent SDK | Implementation Guide for Python & TypeScript

For developers who want to get an autonomous AI agent running in Python or TypeScript in as little as 10 minutes, here is a step-by-step implementation guide for the Claude Agent SDK. We cover everything from a one-line pip/npm install to the autonomous loop of the query() function, 11 built-in tools, adding audit logs with hooks, and multi-cloud deployment to Bedrock, Vertex AI, and Azure — in the fastest order possible for production use.

Article Summary by AI Chatpowered by Claude
結論powered by Claude

Claude Agent SDK is the official SDK that provides the same tools and context management features as Claude Code as Python and TypeScript libraries. By simply calling the query() function, Claude autonomously loops through tool execution and next-action decisions from start to finish.

Setup is complete in one line with pip install claude-agent-sdk or npm install @anthropic-ai/claude-agent-sdk. Set your ANTHROPIC_API_KEY as an environment variable, pass the tool names you want to enable in allowed_tools, and you can immediately start using 11 built-in tools including Read, Write, Edit, and Bash.

On the operational side, hooks such as PreToolUse and PostToolUse let you inject audit logs and permission controls, and the same code runs on Amazon Bedrock, Google Vertex AI, and Microsoft Azure AI Foundry in addition to the Anthropic API — making it easy to meet enterprise governance requirements.

目次 (11)

What Is Claude Agent SDK?

Claude Agent SDK provides the same tools and context management features that power Claude Code as Python and TypeScript libraries. It was renamed from "Claude Code SDK" in 2026.

With a typical API client, your application must implement the loop of "call a tool → receive the result → call the API again." With Claude Agent SDK, a single call to query() lets Claude autonomously handle tool execution, result interpretation, and next-action decisions.

Supported platforms include the Anthropic API as well as Amazon Bedrock, Google Vertex AI, and Microsoft Azure AI Foundry.

Installation and Initial Setup

Installation is a single command.

# Python
pip install claude-agent-sdk

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

The TypeScript version bundles the native Claude Code binary, so there is no need to install the Claude Code CLI separately.

After installation, set the API key obtained from the Anthropic Console (https://platform.claude.com/) as an environment variable.

export ANTHROPIC_API_KEY=your-api-key

Basics of the query() Function

The entry point of Claude Agent SDK is the query() function. It returns an async iterator that streams messages in real time as Claude works.

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="auth.py のバグを見つけて修正してください",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
    ):
        print(message)

asyncio.run(main())

In TypeScript, you can write it the same way with a for await loop.

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find and fix the bug in auth.ts",
  options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
  console.log(message);
}

The loop continues until Claude completes the task or encounters an error, streaming thoughts, tool calls, tool results, and the final output in sequence.

11 Built-in Tools

According to the official documentation (Agent SDK overview), Claude Agent SDK comes with the following built-in tools.

Tool Function
Read Read a file
Write Create a new file
Edit Precisely edit an existing file
Bash Execute terminal commands
Monitor Monitor background scripts
Glob Search for files by pattern
Grep Search file contents with regular expressions
WebSearch Search the web for the latest information
WebFetch Fetch and parse web pages
AskUserQuestion Ask the user for confirmation
Agent Launch a sub-agent and delegate work

Simply pass the tool names you want to enable in allowedTools. Note that enabling the Agent tool allows the main agent to launch specialized sub-agents (see the "Distributing Complex Tasks with Sub-Agents" section below).

Customizing the Lifecycle with Hooks

Hooks let you inject arbitrary code before and after tool execution. Available hooks include PreToolUse, PostToolUse, Stop, SessionStart, SessionEnd, and UserPromptSubmit, among others.

The following example records the changed file path in an audit log every time Edit or Write is executed.

from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
from datetime import datetime

async def log_file_change(input_data, tool_use_id, context):
    file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
    with open("./audit.log", "a") as f:
        f.write(f"{datetime.now()}: modified {file_path}\n")
    return {}

async def main():
    async for message in query(
        prompt="utils.py をリファクタリングしてください",
        options=ClaudeAgentOptions(
            permission_mode="acceptEdits",
            hooks={
                "PostToolUse": [
                    HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
                ]
            },
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)

Distributing Complex Tasks with Sub-Agents

With Claude Agent SDK, you can launch specialized sub-agents from the main agent to delegate work. Add "Agent" to allowed_tools and define sub-agents in the agents dictionary.

from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

async def main():
    async for message in query(
        prompt="code-reviewer エージェントでコードレビューしてください",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Glob", "Grep", "Agent"],
            agents={
                "code-reviewer": AgentDefinition(
                    description="品質・セキュリティ専門のコードレビュアー",
                    prompt="コード品質を分析して改善点を提案してください。",
                    tools=["Read", "Glob", "Grep"],
                )
            },
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)

Messages within a sub-agent are tagged with a parent_tool_use_id field, making it easy to track what each sub-agent did.

Integrating with External Systems via MCP Servers

Connecting a Model Context Protocol (MCP) server enables integration with hundreds of services, including databases, browsers, and external APIs. The following example uses the Playwright MCP server to control a browser.

async for message in query(
    prompt="example.com を開いて内容を説明してください",
    options=ClaudeAgentOptions(
        mcp_servers={
            "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
        }
    ),
):
    if hasattr(message, "result"):
        print(message.result)

Enabling Cross-Context Conversations with Session Management

By saving the session ID and passing it to the resume option, you can carry over the context from a previous conversation (files read, analysis results, conversation history) and continue working.

from claude_agent_sdk import SystemMessage

session_id = None
async for message in query(
    prompt="認証モジュールを読んでください",
    options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
):
    if isinstance(message, SystemMessage) and message.subtype == "init":
        session_id = message.data["session_id"]

# Continue in the same session
async for message in query(
    prompt="それを呼び出している箇所をすべて探してください",
    options=ClaudeAgentOptions(resume=session_id),
):
    ...

Controlling Safety with Permission Modes

The permission_mode option lets you change the agent's permission level (see Quickstart).

Mode Behavior Use Case
acceptEdits Automatically approve file edits Trusted development workflows
dontAsk Reject everything outside allowedTools Headless automation
auto (TS only) Model decides each tool call Autonomous agent with safety guards
bypassPermissions Allow all tools unconditionally CI / sandbox environments
default Controlled via canUseTool callback Custom approval flows

Differences from Client SDK, Claude Code CLI, and Managed Agents

The official documentation (Agent SDK overview) provides three comparisons.

Difference from Client SDK: With the Client SDK, your application implements the tool loop. With Claude Agent SDK, Claude autonomously manages the loop.

Difference from Claude Code CLI: They have equivalent capabilities, but the CLI is for interactive development while the SDK is for automating CI/CD pipelines and custom applications. Many teams use both for different purposes.

Difference from Managed Agents: Claude Agent SDK is a library where code runs on your own infrastructure. Managed Agents, on the other hand, is a hosted REST API where Anthropic manages the infrastructure. The recommended path is to prototype locally with the SDK, then migrate to Managed Agents for production.

In Practice: Building a Bug-Fix Agent

The official quickstart (Quickstart) walks through building a bug-fix agent in the following steps.

  1. Install with pip install claude-agent-sdk or npm install @anthropic-ai/claude-agent-sdk
  2. Set ANTHROPIC_API_KEY as an environment variable
  3. Create a buggy sample file utils.py
  4. Run a script that uses query() to request a bug fix

Claude reads the file with Read, analyzes the logic, and adds error handling with Edit. The biggest appeal is that the fix is complete without a human writing a single line of code.

If you are using Opus 4.7 (claude-opus-4-7), SDK version v0.2.111 or later is required. Older versions will produce a thinking.type.enabled API error. Note that as of the time of writing, the latest version is in the Opus 4.8 series (claude-opus-4-8), so 4.7 is not the latest. If you are using Opus 4.8, please use the latest version of the SDK (check the minimum supported version in the official release notes).


The full Claude Agent SDK documentation is available at https://code.claude.com/docs/en/agent-sdk/overview. For the Python reference, see Agent SDK reference - Python. For the TypeScript reference, see TypeScript SDK. GitHub samples are available at claude-agent-sdk-demos.

参考になったら ♡
Clauder Navi 編集部
@clauder_navi

Anthropic の Claude / Claude Code を中心に、日本のエンジニア向けに最新動向と実務 を毎日発信。 運営方針 は メディアについて をご覧ください。