claude-agent-sdk について
Anthropic の Claude Agent SDK を使ってツール利用型 AI エージェントを構築する開発者向けガイドです。Python と TypeScript に対応し、エージェントループ、コンテキスト管理、サブエージェント、権限、フック、MCP 連携を解説します。
主な機能
- 01エージェントループとツール呼び出しの管理
- 02Python と TypeScript に対応
- 03会話コンテキストと圧縮の管理
- 04コンテキストを分離したサブエージェントの作成
- 05権限とフックによるツール制御
- 06MCP サーバーとの連携
活用シーン
- 01ツールを反復利用するエージェントの構築
- 02複雑なタスクのサブエージェントへの委任
- 03ツール実行への検証とログの追加
- 04MCP ツールのエージェントワークフローへの接続
MCP 対応
SDK は MCP サーバーに接続し、エージェントのツール提供元として利用できます。ガイドでは MCPClient による接続方法を示しています。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ rysweet/ amplihack --skill claude-agent-sdkインストール後、Claude Code で/claude-agent-sdkを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
README.mdVALIDATION_REPORT.mddrift-detection.mdexamples.mdpatterns.mdreference.mdscripts/check_drift.py詳細
Claude Agent SDK - 包括的なスキル
概要
Claude Agent SDK は、Claude を使って本番環境に対応した AI エージェントを構築するための、Anthropic の公式フレームワークです。Messages API を高水準に抽象化し、エージェントループ、ツールのオーケストレーション、コンテキスト管理、拡張思考のパターンを自動的に処理します。
Agent SDK を使用するタイミング
Agent SDK を使用するケース:
- ツールを反復的に使用する自律型エージェントを構築する場合
- 検証と反復を伴うエージェント型ワークフローを実装する場合
- 複雑なタスク分解のためにサブエージェントの階層を作成する場合
- 標準化されたツールとして MCP(Model Context Protocol)サーバーを統合する場合
- フック、権限、コンテキスト管理などの本番環境向けパターンが必要な場合
使用しないケース:
- 単純な単一ターンの API 呼び出しで十分な場合(Messages API を直接使用してください)
- ツールの使用が不要な場合(標準的なチャット)
- カスタムのエージェントループロジックが必要な場合(SDK のループには独自の設計方針があります)
言語サポート
- Python:
claude-agentsパッケージ(ほとんどのユースケースで推奨) - TypeScript:
@anthropics/agent-sdkパッケージ(Node.js 環境)
どちらの実装も、同じコア概念と API パターンを共有しています。
クイックスタート
インストール
Python:
pip install claude-agents
TypeScript:
npm install @anthropics/agent-sdk
認証
API キーを環境変数として設定します:
export ANTHROPIC_API_KEY="your-api-key-here" # pragma: allowlist secret
または、コード内で明示的に渡します:
from claude_agents import Agent
agent = Agent(api_key="your-api-key-here")
基本的なエージェントの作成
Python の例:
from claude_agents import Agent
# Create agent with default settings
agent = Agent(
model="claude-sonnet-4-5-20250929",
system="You are a helpful assistant focused on accuracy."
)
# Run simple task
result = agent.run("What is 2+2?")
print(result.response)
TypeScript の例:
import { Agent } from "@anthropics/agent-sdk";
const agent = new Agent({
model: "claude-sonnet-4-5-20250929",
system: "You are a helpful assistant focused on accuracy.",
});
const result = await agent.run("What is 2+2?");
console.log(result.response);
最初のツールの例
ツールを使うと、外部関数によってエージェントの機能を拡張できます:
Python:
from claude_agents import Agent
from claude_agents.tools import Tool
# Define custom tool
def get_weather(location: str) -> dict:
"""Get weather for a location."""
return {"location": location, "temp": 72, "condition": "sunny"}
weather_tool = Tool(
name="get_weather",
description="Get current weather for a location",
input_schema={
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
},
function=get_weather
)
# Agent with custom tool
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[weather_tool]
)
result = agent.run("What's the weather in San Francisco?")
print(result.response)
コア概念リファレンス
エージェントループ
SDK はエージェントループ全体を自動的に管理します:
- 入力処理:ユーザーメッセージ + システムプロンプト + ツール
- モデル呼び出し:Claude が応答を生成します(テキストまたはツール呼び出し)
- ツールの実行:SDK が要求されたツールを実行し、結果を処理します
- 反復:結果をモデルに返し、完了するまで続行します
- 出力:会話履歴全体を含む最終応答
主な特性:
- タスクの完了または最大ターン数に達するまで自動的に反復します
- エラー処理と再試行のロジックを標準で備えています
- 自動圧縮オプションによるコンテキスト管理
- トークン予算の追跡と最適化
コンテキスト管理
SDK は会話のコンテキストを自動的に管理します:
コンテキストの構成要素:
- システムプロンプト(継続的な指示)
- 会話履歴(ユーザーメッセージ + アシスタントの応答)
- ツール定義(利用可能な機能)
- ツールの結果(実行結果)
コンテキストを分離するためのサブエージェント:
# Spawn subagent with isolated context
with agent.subagent(
system="You are a code reviewer focused on security.",
tools=[security_scan_tool]
) as reviewer:
review = reviewer.run("Review this code for vulnerabilities: ...")
# Subagent context doesn't pollute parent
コンテキストの圧縮: トークン上限に近づくと、SDK は重要な情報を保持しながら、以前の会話ターンを自動的に要約できます。
ツールシステム
ツールは、エージェントが外部機能を利用するためのインターフェースです。
組み込みツール:
bash:シェルコマンドを実行しますread_file:ファイルの内容を読み取りますwrite_file:ファイルにデータを書き込みますedit_file:既存のファイルを変更しますglob:ファイルパターンに一致するファイルを検索しますgrep:内容を検索します
カスタムツールのスキーマ:
Tool(
name="tool_name", # Unique identifier
description="What it does", # Clear capability description
input_schema={ # JSON Schema for parameters
"type": "object",
"properties": {...},
"required": [...]
},
function=callable # Python function or async function
)
MCP の統合: SDK は Model Context Protocol(MCP)サーバーをツールプロバイダーとして使用できます:
from claude_agents import Agent
from claude_agents.mcp import MCPClient
# Connect to MCP server
mcp_client = MCPClient("npx", ["-y", "@modelcontextprotocol/server-filesystem"])
agent = Agent(
model="claude-sonnet-4-5-20250929",
mcp_clients=[mcp_client]
)
権限システム
エージェントがアクセスできるツールを制御します:
許可するツール(許可リスト):
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[tool1, tool2, tool3, tool4],
allowed_tools=["tool1", "tool2"] # Only these can be used
)
禁止するツール(拒否リスト):
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[tool1, tool2, tool3],
disallowed_tools=["tool3"] # All except tool3
)
権限モード:
"strict":ツールを使用する前に、エージェントは必ず(フックを介して)許可を得る必要があります"permissive":エージェントは許可されたツールを自由に使用できます(デフォルト)
フックシステム
フックを使うと、ライフサイクルイベントに介入して、可観測性、検証、制御を実現できます。
利用可能なフック:
PreToolUseHook:ツール実行前(検証、ログ記録、ブロック)PostToolUseHook:ツール実行後(ログ記録、結果の変更)PreSubagentStartHook:サブエージェントの起動前(コンテキストの設定)PostSubagentStopHook:サブエージェントの完了後(結果の処理)
基本的なフックの例:
from claude_agents.hooks import PreToolUseHook
class LoggingHook(PreToolUseHook):
async def execute(self, context):
print(f"Tool: {context.tool_name}")
print(f"Args: {context.tool_input}")
return context # Allow execution
agent = Agent(
model="claude-sonnet-4-5-20250929",
hooks=[LoggingHook()]
)
ツール使用のブロック:
class ValidationHook(PreToolUseHook):
async def execute(self, context):
if context.tool_name == "bash" and "rm -rf" in context.tool_input.get("command", ""):
raise PermissionError("Destructive command blocked")
return context
よくあるパターン
ファイル操作
from claude_agents import Agent
agent = Agent(
model="claude-sonnet-4-5-20250929",
allowed_tools=["read_file", "write_file", "glob"]
)
result = agent.run(
"Read all Python files in ./src and create a summary in summary.md"
)
コード実行
agent = Agent(
model="claude-sonnet-4-5-20250929",
allowed_tools=["bash"]
)
result = agent.run(
"Run the test suite and analyze any failures"
)
エージェント型検索(Gather-Act パターン)
# Agent automatically gathers information iteratively
search_agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[web_search_tool, read_url_tool]
)
result = search_agent.run(
"Research the latest developments in quantum computing and summarize key papers"
)
サブエージェントへの委任
main_agent = Agent(model="claude-sonnet-4-5-20250929")
# Delegate specialized task to subagent
with main_agent.subagent(
system="You are an expert data analyzer.",
tools=[analyze_csv_tool, plot_tool]
) as analyzer:
analysis = analyzer.run("Analyze sales_data.csv and create visualizations")
# Results available to main agent
main_agent.run(f"Based on this analysis: {analysis.response}, what actions should we take?")
エラー処理
from claude_agents import Agent, AgentError
agent = Agent(model="claude-sonnet-4-5-20250929")
try:
result = agent.run("Your task here", max_turns=10)
except AgentError as e:
print(f"Agent failed: {e}")
print(f"Turns completed: {e.turns_completed}")
print(f"Last message: {e.last_message}")
検証パターン
# Agent can self-verify results
agent = Agent(
model="claude-sonnet-4-5-20250929",
tools=[calculator_tool, verify_tool]
)
result = agent.run(
"Calculate the compound interest for $10000 at 5% for 10 years. "
"Verify your calculation by computing it a second way."
)
ナビゲーションガイド
関連ファイルを読むタイミング
reference.md - 次の情報が必要なときに読みます:
- エージェントループの内部動作に関する深い理解
- すべての SDK 機能の完全な API リファレンス
- 詳細なツールスキーマ仕様
- 権限およびセキュリティ設定オプション
- すべてのイベントタイプを網羅した包括的なフックリファレンス
- スキルシステムの実装詳細
examples.md - 次の情報が必要なときに読みます:
- 特定のパターンに関する実用的なコード例
- ツール実装テンプレート
- フックの実装例
- 高度なパターン(サブエージェント、検証、エラー復旧)
- 既存システムとの統合例
patterns.md - 次の情報が必要なときに読みます:
- 本番環境ですぐに使えるアーキテクチャパターン
- エージェントループの最適化戦略(Gather、Act、Verify、Iterate)
- コンテキスト管理のベストプラクティス
- ツール設計の原則
- セキュリティパターンとアンチパターン
- パフォーマンス最適化手法
drift-detection.md - 次の情報が必要なときに読みます:
- このスキルが最新の状態を維持する仕組みの理解
- 他のスキル向けのドリフト検出の実装
- 更新ワークフローと検証プロセス
- 自己検証の仕組み
Amplihack との統合
Agent SDK スキルは Amplihack フレームワークと統合されます:
SDK を使用した Amplihack エージェントの作成:
# In .claude/agents/amplihack/specialized/my_agent.md
# Use Agent SDK patterns for tool-using agents
from claude_agents import Agent
from claude_agents.tools import Tool
def create_specialized_agent():
return Agent(
model="claude-sonnet-4-5-20250929",
system="<agent_role_from_md>",
tools=[...], # Custom tools for this agent
hooks=[...] # Logging, validation hooks
)
Amplihack での MCP サーバーの使用:
# Integrate MCP tools into Amplihack workflow
from claude_agents.mcp import MCPClient
mcp_client = MCPClient("npx", ["-y", "@modelcontextprotocol/server-github"])
agent = Agent(
model="claude-sonnet-4-5-20250929",
mcp_clients=[mcp_client]
)
# Agent can now use GitHub MCP tools
result = agent.run("Create a GitHub issue for the bug we just found")
Amplihack の可観測性のためのフック:
# Log all agent actions to Amplihack runtime logs
class AmplihackLoggingHook(PreToolUseHook):
async def execute(self, context):
log_to_amplihack_runtime(
session_id=get_current_session(),
tool=context.tool_name,
input=context.tool_input
)
return context
クイックリファレンス
必須コマンド
# Basic agent
agent = Agent(model="claude-sonnet-4-5-20250929")
result = agent.run("task")
# With tools
agent = Agent(model="...", tools=[tool1, tool2])
# With permissions
agent = Agent(model="...", allowed_tools=["tool1"])
# With hooks
agent = Agent(model="...", hooks=[LogHook()])
# Subagent
with agent.subagent(system="...") as sub:
result = sub.run("subtask")
# MCP integration
from claude_agents.mcp import MCPClient
mcp = MCPClient("npx", ["-y", "mcp-server-name"])
agent = Agent(model="...", mcp_clients=[mcp])
一般的なツールパターン
# File operations
tools=["read_file", "write_file", "glob"]
# Code execution
tools=["bash"]
# All built-in
tools=["bash", "read_file", "write_file", "edit_file", "glob", "grep"]
トークン予算の推奨事項
- 単純なタスク:4K~8K トークン
- 複雑なタスク:16K~32K トークン
- 調査/分析:64K~128K トークン
- 最大コンテキスト:200K トークン(モデルによって異なります)
次のステップ
- シンプルに始める:組み込みツールを使って基本的なエージェントを作成します
- カスタムツールを追加する:特定のドメイン向けのツールを実装します
- フックを追加する:ロギングと検証を実装します
- サブエージェントを使う:専門的なタスクを委任します
- MCP を統合する:標準化されたツールサーバーを使用します
- 最適化する:コンテキスト、権限、検証パターンを調整します
API の詳細については、reference.md を参照してください。
実用的なコードについては、examples.md を参照してください。
本番環境向けのパターンについては、patterns.md を参照してください。