claude-agent-sdk について
Claude Agent SDKは、Claude Codeのファイル操作、コマンド実行、ウェブ検索などを使うエージェントを構築するPythonおよびTypeScript SDKです。単発クエリと継続セッションに対応し、カスタムツール、フック、権限、サブエージェントを設定できます。
主な機能
- 01単発クエリと継続クエリ
- 02ファイル、シェル、ウェブツール
- 03カスタムツールとフック
- 04ツールの権限制御
- 05サブエージェントの作成
- 06PythonおよびTypeScript SDK
活用シーン
- 01単発のファイル操作やコーディングの自動化
- 02継続対話が可能なエージェントの構築
- 03読み取り専用のコードレビューエージェントの作成
- 04ウェブツールを使った調査
MCP 対応
エージェントはMCPサーバーをカスタムツールとして利用できます。SDKではエージェント設定にMCPサーバーを追加できます。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ tdimino/ claude-code-minoan --skill claude-agent-sdkインストール後、Claude Code で/claude-agent-sdkを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
README.mdreferences/best-practices.mdbrowser-control.mdbuilt-in-tools.mdcustom-tools.mdhooks.mdmessage-types.mdpermissions.mdpython-sdk.mdsubagents.mdtroubleshooting.mdtemplates/agent-with-tracking-python.pycontinuous-chat-python.pycustom-tool-python.pyhook-example-python.pyresearch-agent-python.pysession-api-typescript.tssimple-agent-python.pyworkflows/add-custom-tools.mdadd-hooks.mdcreate-agent.md詳細
<essential_principles>
Claude Agent SDK の概要
Claude Agent SDK は、Claude Code を支えるファイル操作、bash コマンド、ウェブ検索などのツールをエージェントに提供します。ファイルの読み取り、コマンドの実行、ウェブ検索、コードの編集、作業の検証を行う自律型エージェントを構築できます。
クエリを送る 2 つの方法
| 関数 | セッション | 最適な用途 |
|---|---|---|
query() | 毎回新規 | 単発タスク、自動化 |
ClaudeSDKClient | 継続的 | 会話、フォローアップ、フック |
主な違い: query() はより簡単ですが、フック、中断、カスタムツールには対応していません。高度な機能を使う場合は ClaudeSDKClient を使用してください。
エージェントループのパターン
エージェントはフィードバックループで動作します:
gather context → take action → verify work → repeat
インストール
Python:
uv add claude-agent-sdk
TypeScript:
npm install @anthropic-ai/claude-agent-sdk
要件:
- Claude Code CLI がインストールされていること(
npm install -g @anthropic-ai/claude-code) ANTHROPIC_API_KEY環境変数が設定されていること
クイックスタート
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find and fix bugs in auth.py",
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"])
):
print(message)
asyncio.run(main())
</essential_principles>
何をしたいですか?
- 新しいエージェントを作成する - エージェントをゼロから構築します
- カスタムツールを追加する - @tool デコレーターまたは MCP サーバーでツールを作成します
- フックを追加する - ロギング、検証、変更のためにツール呼び出しをインターセプトします
- 権限を設定する - ツールが実行できる操作を制御します
- サブエージェントを作成する - 並列作業用の特化したエージェントを定義します
- ブラウザーを制御する - Chrome 拡張機能、dev-browser スキル
- API リファレンスを確認する - Python または TypeScript SDK の詳細
先に進む前に、回答を待ちます。
| 回答 | 読み込むファイル |
|---|---|
| 1, "create", "new", "build" | workflows/create-agent.md |
| 2, "tools", "custom", "@tool" | references/custom-tools.md |
| 3, "hooks", "intercept" | references/hooks.md |
| 4, "permissions", "can_use_tool" | references/permissions.md |
| 5, "subagent", "parallel" | references/subagents.md |
| 6, "browser", "chrome", "automation" | references/browser-control.md |
| 7, "python", "reference" | references/python-sdk.md |
| 7, "typescript", "reference" | references/typescript-sdk.md |
| "built-in", "tools" | references/built-in-tools.md |
| "message", "types" | references/message-types.md |
| "best practices", "patterns" | references/best-practices.md |
| "error", "troubleshoot" | references/troubleshooting.md |
<quick_reference>
ClaudeAgentOptions(主なフィールド)
ClaudeAgentOptions(
# Tools
allowed_tools=["Read", "Write", "Bash"], # Built-in tools to enable
disallowed_tools=["WebSearch"], # Tools to block
# Prompts
system_prompt="You are...", # Custom system prompt
# Or use preset: {"type": "preset", "preset": "claude_code", "append": "..."}
# MCP Servers
mcp_servers={"calc": my_server}, # MCP server configs
# Permissions
permission_mode="acceptEdits", # default | acceptEdits | plan | bypassPermissions
can_use_tool=my_handler, # Custom permission callback
# Execution
cwd="/path/to/project", # Working directory
max_turns=10, # Limit iterations
env={"API_KEY": "..."}, # Environment variables
# Advanced
hooks={"PreToolUse": [...]}, # Behavior hooks
agents={"researcher": AgentDef(...)}, # Subagents
sandbox={"enabled": True}, # Sandbox settings
setting_sources=["project"], # Load .claude settings
)
組み込みツール
| ツール | 用途 |
|---|---|
| Read | ファイルの読み取り(テキスト、画像、PDF、ノートブック) |
| Write | 新しいファイルの作成 |
| Edit | 検索と置換による既存ファイルの編集 |
| Bash | ターミナルコマンドの実行 |
| Glob | パターンによるファイル検索(**/*.ts) |
| Grep | 正規表現によるファイル内容の検索 |
| WebSearch | ウェブの検索 |
| WebFetch | ウェブページの取得と解析 |
| Task | サブエージェントの起動 |
| NotebookEdit | Jupyter ノートブックの編集 |
| TodoWrite | タスクリストの管理 |
| KillShell | バックグラウンドシェルの終了 |
| ExitPlanMode | 計画モードの終了 |
メッセージの種類
# All messages
Message = UserMessage | AssistantMessage | SystemMessage | ResultMessage
# Content blocks in AssistantMessage
ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock
エラーの種類
from claude_agent_sdk import (
CLINotFoundError, # Claude Code CLI not installed
CLIConnectionError, # Connection failed
ProcessError, # CLI process failed
CLIJSONDecodeError, # JSON parsing failed
)
</quick_reference>
<thinking_config>
思考と労力の設定
「慎重に考えて」のようなプロンプトレベルの指示ではなく、effort パラメーターを使ってエージェントの思考の深さを制御します:
| 用途 | 労力 | 備考 |
|---|---|---|
| 素早い調査、簡単な編集 | low | 思考のオーバーヘッドを最小限に抑えます |
| 標準的な開発 | medium | ほとんどのエージェントのデフォルトです |
| 複雑なアーキテクチャ、セキュリティ | high | より深い推論を行います |
| 詳細な調査、長期的な作業 | max | 思考の予算を最大化します |
# Adaptive thinking (recommended for Claude 4.6)
options = ClaudeAgentOptions(
model="claude-opus-4-6", # or claude-sonnet-4-6
# Effort is controlled at the API level, not in the agent options
)
エージェントのシステムプロンプトに「慎重に考えて」や「徹底してください」を追加するのは避けてください。Claude 4.6 はタスクの複雑さに応じて、思考の深さを自動的に調整します。
</thinking_config>
よくあるパターン
ファイル操作エージェント
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Edit", "Glob", "Grep"],
permission_mode="acceptEdits",
cwd="/path/to/project"
)
コードレビューエージェント
options = ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep"], # Read-only
system_prompt="Review code for bugs, security issues, and style"
)
リサーチエージェント
options = ClaudeAgentOptions(
allowed_tools=["WebSearch", "WebFetch", "Write"],
max_turns=20 # Allow more iterations for research
)
ツールを使った対話型チャット
async with ClaudeSDKClient(options) as client:
await client.query("What files are in this directory?")
async for msg in client.receive_response():
print(msg)
# Follow-up - Claude remembers context
await client.query("Show me the largest one")
async for msg in client.receive_response():
print(msg)