Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Claude Agent SDK Usage Guide

Claude Agent SDK Usage Guide

The Claude Agent SDK lets you build AI agents that can autonomously read files, run commands, search the web, edit code, and more.

The Claude Agent SDK exposes the tools, agent loop, and context management capabilities that power Claude Code as programmable Python and TypeScript libraries.

Simply put, this is an SDK that uses Claude Code as a library. You can embed it in your own applications, CI pipelines, or automation scripts to build AI agents that can autonomously accomplish complex tasks.


Core capability

The SDK has built-in tools for reading files, running commands, and editing code, so your agent does not need to implement tool execution logic itself and can start working immediately. Key capabilities include:

Capability Description
Built-in Tools File reading and writing, terminal commands, code editing, web search, and more
Hooks Execute custom logic before and after tool calls
Subagents Break large tasks into smaller ones and dispatch them in parallel to independent subagents
MCP servers Connect to databases, browsers, external APIs, and more
Permission Control Fine-grained control over what the agent can do and when user approval is required
Session Management (Sessions) Build multi-turn conversational agents that maintain context

Precondition


Step 1: Install the SDK

TypeScript

npm install @anthropic-ai/claude-agent-sdk

The TypeScript SDK packages the Claude Code binary for your current platform as an optional dependency, so there is no need to install Claude Code separately.

Python

# 使用 pip

pip install claude-agent-sdk



# or use uv (recommended)

uv add claude-agent-sdk

Note: The Claude Code CLI is automatically installed with the package, so no separate installation is needed! The SDK uses the bundled CLI by default.

If you want to use a system-level installation or a specific version, you can ClaudeAgentOptions(cli_path="/path/to/claude") to specify the path.


Step 2: Configure the API Key

From the Claude Console Obtain an API Key, then create a file in the .env File:

ANTHROPIC_API_KEY=your-api-key-here

project directory, or set it directly as an environment variable:

export ANTHROPIC_API_KEY=your-api-key-here

Support for Third-Party Cloud Platforms

The SDK also supports authentication through third-party API providers: Amazon Bedrock (set the CLAUDE_CODE_USE_BEDROCK=1 environment variable and configure AWS credentials), Google Vertex AI (set CLAUDE_CODE_USE_VERTEX=1) and Microsoft Azure (set CLAUDE_CODE_USE_FOUNDRY=1)。

⚠️ Important: Unless otherwise approved in advance by Anthropic, third-party developers are not permitted to offer claude.ai login or rate limits in products built on the Claude Agent SDK. Please use the API Key authentication method described in the documentation.


Step 3: Run Your First Agent

The following example creates an agent that lists the files in the current directory:

Python

Example

import

asyncio

from

claude_agent_sdk

import

query

,

ClaudeAgentOptions

async

def

main

(

)

:

    async

for

message

in

query

(

        prompt

=

"What files are in this directory?"

,

        options

=

ClaudeAgentOptions

(

allowed_tools

=

[

"Bash"

,

"Glob"

]

)

,

   

)

:

       

if

hasattr

(

message

,

"result"

)

:

           

print

(

message.

result

)

asyncio.

run

(

main

(

)

)

TypeScript

Example

import

{

query

}

from

"@anthropic-ai/claude-agent-sdk"

;

async

function

main

(

)

{

 

for

await

(

const

message of query

(

{

    prompt

:

"What files are in this directory?"

,

    options

:

{

allowedTools

:

[

"Bash"

,

"Glob"

]

}

,

 

}

)

)

{

   

if

(

"result"

in

message

)

{

      console.

log

(

message.

result

)

;

   

}

 

}

}

main

(

)

;


Hands-On: Building an Agent That Automatically Fixes Bugs

The following complete example demonstrates the core usage of the Agent SDK.

Prepare a File with a Bug

creation utils.py, containing two intentionally introduced bugs:

Example

def

calculate_average

(

numbers

)

:

    total

=

0

   

for

num

in

numbers:

        total +

=

num

   

return

total /

len

(

numbers

)

 

Bug: Division by zero when the list is empty

def

get_user_name

(

user

)

:

   

return

user

[

"name"

]

.

upper

(

)

 

Bug: TypeError when user is None

Write the Agent

creation agent.py:

Example

import

asyncio

from

claude_agent_sdk

import

query

,

ClaudeAgentOptions

,

AssistantMessage

,

ResultMessage

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"

]

,

 

Allowed tools

            permission_mode

=

"acceptEdits"

,

           

Automatically approve file edits

       

)

,

   

)

:

       

if

isinstance

(

message

,

AssistantMessage

)

:

           

for

block

in

message.

content

:

               

if

hasattr

(

block

,

"text"

)

:

                   

print

(

block.

text

)

         

Claude's reasoning process

               

elif

hasattr

(

block

,

"name"

)

:

                   

print

(

f

"Tool: {block.name}"

)

Tool being called

       

elif

isinstance

(

message

,

ResultMessage

)

:

           

print

(

f

"Done: {message.subtype}"

)

 

Final result

asyncio.

run

(

main

(

)

)

Run

python agent.py

After running, check utils.py, and you will see that the agent autonomously completed the following actions:

  1. ReadRead utils.py file
  2. Analyzedthe code logic, identifying edge cases that could cause crashes
  3. Editingthe file, adding comprehensive error handling

Core Concept Analysis

function — the entry point of the agent loop

query is the main entry point for creating an agent loop, returning an async iterator, so you use async for to stream messages produced as Claude works in real time. The loop ends when Claude completes the task or encounters an error. The SDK handles orchestration (tool execution, context management, retries), and you only need to consume this message stream.

Each iteration produces a message, which may be:

Tools —— control what the agent can do

Tool combinations Agent Capabilities
Read, Glob, Grep Read-only analysis
Read, Edit, Glob Analyze and modify code
Read, Edit, Bash, Glob, Grep Full Automation
plus WebSearch Add web search capability

Permission Modes - controlling the level of human oversight

Mode Behavior Applicable scenarios
acceptEdits Auto-approve file edits; other operations still require confirmation Trusted development workflows
dontAsk rejected allowedTools and all operations outside of them Locked-down unattended agents
auto(TypeScript only) Model classifier automatically approves/rejects every tool call Autonomous agents with safety guardrails
bypassPermissions Run all tools directly without prompting Sandboxed CI environment
default Must provide canUseTool A callback to handle approvals Custom approval flow

Customize agent behavior

Add web search

options = ClaudeAgentOptions(

    allowed_tools=["Read", "Edit", "Glob", "WebSearch"],

    permission_mode="acceptEdits"

)

Add a custom system prompt

options = ClaudeAgentOptions(

    allowed_tools=["Read", "Edit", "Glob"],

    permission_mode="acceptEdits",

    system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.",

)

Allow terminal command execution

options = ClaudeAgentOptions(

    allowed_tools=["Read", "Edit", "Glob", "Bash"],

    permission_mode="acceptEdits"

)

# Try:

# prompt="Write unit tests for utils.py, run them, and fix any failures"

Load project configuration (CLAUDE.md, etc.)

The SDK is built on the same foundation as Claude Code, so SDK agents can access the same filesystem-based capabilities: project instructions (CLAUDE.md and rules), skills, Hooks, and more. By default, the SDK does not load any filesystem settings.

options = ClaudeAgentOptions(

    allowed_tools=["Read", "Edit"],

    # "user" loaded from ~/.claude/, "project" loaded from ./.claude/

    setting_sources=["user", "project"],

)


Error handling

from claude_agent_sdk import (

    ClaudeSDKError,      # 基础错误

    CLINotFoundError,    # Claude Code 未安装

    CLIConnectionError,  # 连接问题

    ProcessError,        # 进程失败

    CLIJSONDecodeError,  # JSON 解析失败

)



try:

    async for message in query(prompt="Hello"):

        pass

except CLINotFoundError:

    print("请先安装 Claude Code")

except ProcessError as e:

    print(f"进程失败,退出码:{e.exit_code}")

except CLIJSONDecodeError as e:

    print(f"响应解析失败:{e}")


Agent SDK vs. other Claude tools

Agent SDK Client SDK(Messages API) Claude Code CLI
Usage Python/TypeScript libraries HTTP API calls Terminal command-line tool
Tool execution Built-in, automatic Must be implemented manually Built-in, interactive
Applicable scenarios Build autonomous agents; application integration General LLM calls Direct coding assistance
State management Stateful, with session support Stateless Stateful, interactive

SDK feature comparison table

The SDK also supports Claude Code's filesystem-based configuration. To use these features, set in the options setting_sources=["project"](Python) or settingSources: ['project'](TypeScript)。

Function Description Position
Skills Specialized capabilities defined in Markdown .claude/skills/*/SKILL.md
Slash Commands Custom commands for common tasks .claude/commands/*.md
Memory Project context and instructions CLAUDE.md
Plugins Pass plugins Option extensions Configure through code