Claude Agent SDKは、Claude Codeを動かしているものと同じエージェントループへのプログラムによるアクセスを提供します。エージェントはファイルの読み取り、シェルコマンドの実行、Web検索、コードの編集、MCPサーバーを介した外部APIの呼び出し、サブエージェントのオーケストレーションなど - すべてをTypeScriptまたはPythonの数行のコードで実現できます。
標準のAnthropic Client SDKでは自分でツールループを構築する必要がありますが、Agent SDKはツールの実行、コンテキスト管理、リトライ、オーケストレーションを内部で処理します。やりたいことを記述し、ツールを提供すれば、エージェントが残りを判断します。
アーキテクチャ
SDKはシンプルなループに従います: コンテキストの収集、アクションの実行、検証、繰り返し。
コアのエントリポイントは query() で、エージェントが作業する間にメッセージをストリーミングする非同期イテレータを返します。各メッセージはエージェントが何をしているかを示します: 推論中、ツール呼び出し中、結果の受信中、または最終出力の配信中。
はじめに
インストール
# TypeScript npm install @anthropic-ai/claude-agent-sdk # Python pip install claude-agent-sdk
環境変数として ANTHROPIC_API_KEY にAnthropic APIキーを設定する必要があります。
最初のエージェント
import { query } from "@anthropic-ai/claude-agent-sdk"; const conversation = query({ prompt: "Find all TODO comments in the codebase and create a summary", options: { allowedTools: ["Read", "Glob", "Grep"], }, }); for await (const message of conversation) { if (message.type === "assistant") { process.stdout.write(message.content); } if (message.type === "result" && message.subtype === "success") { console.log("\nDone:", message.result); } }
これだけです。エージェントはGlobでファイルを検索し、GrepでTODOパターンを検索し、Readでマッチを確認し、構造化されたサマリーを返します。オーケストレーションロジックを書く必要はありません - SDKが処理します。
Python版
from claude_agent_sdk import query async for message in query( prompt="Find all TODO comments in the codebase and create a summary", options={"allowed_tools": ["Read", "Glob", "Grep"]}, ): if message.type == "assistant": print(message.content, end="") if message.type == "result" and message.subtype == "success": print(f"\nDone: {message.result}")
ビルトインツール
SDKにはClaude Codeで利用可能なものと同じツールが付属しています:
| ツール | 説明 |
|---|---|
| Read | ファイルの内容を読み取る |
| Write | 新しいファイルを作成する |
| Edit | 既存のファイルに対象を絞った編集を行う |
| Bash | シェルコマンドを実行する |
| Glob | パターンでファイルを検索する |
| Grep | 正規表現でファイル内容を検索する |
| WebSearch | Webを検索する |
| WebFetch | URLを取得して内容を返す |
| AskUserQuestion | ユーザーに入力を求める |
allowedTools でエージェントが使用できるツールを制御します。リストにないツールは、エージェントから呼び出すことができません。
パーミッションモード
エージェントは実際のシステム上で実際のコマンドを実行するため、パーミッションが重要です。
| モード | 動作 | ユースケース |
|---|---|---|
default | カスタム canUseTool コールバックが呼び出しごとに判断 | きめ細かい制御 |
acceptEdits | ファイル操作を自動承認、Bashはプロンプト | 開発ワークフロー |
dontAsk | allowedToolsにないものはすべて拒否 | 制限されたエージェント |
bypassPermissions | すべてを自動的に承認 | 信頼されたサンドボックス環境 |
auto | モデルの分類器が安全性を判断 | バランスの取れた自動化 |
const conversation = query({ prompt: "Refactor the auth module to use JWT", options: { allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"], permissionMode: "acceptEdits", }, });
本番環境では、常にサンドボックス化された環境(コンテナ、VM)でエージェントを実行し、エージェントがタスクを遂行できる範囲で最も制限的なパーミッションモードを使用してください。
MCPによるカスタムツールの構築
SDKの真の力は、独自のツールでエージェントを拡張できることにあります。カスタムツールはインプロセスMCPサーバーとして定義されます - サブプロセス管理もネットワークオーバーヘッドも不要です。
例: 天気ツール
import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk"; import { z } from "zod"; const getTemperature = tool( "get_temperature", "Get the current temperature at a location", { latitude: z.number().describe("Latitude"), longitude: z.number().describe("Longitude"), }, async ({ latitude, longitude }) => { const res = await fetch( `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m&temperature_unit=celsius` ); const data = await res.json(); return { content: [ { type: "text", text: `Current temperature: ${data.current.temperature_2m}C`, }, ], }; } ); const weatherServer = createSdkMcpServer({ name: "weather", version: "1.0.0", tools: [getTemperature], }); for await (const message of query({ prompt: "What's the weather like in Rome?", options: { mcpServers: { weather: weatherServer }, allowedTools: ["mcp__weather__get_temperature"], }, })) { if (message.type === "result" && message.subtype === "success") { console.log(message.result); } }
カスタムツールは mcp__{server_name}__{tool_name} という命名規則に従います。allowedTools ではワイルドカードが使用できます: "mcp__weather__*" はweatherサーバーのすべてのツールを許可します。
例: データベースクエリツール
const queryDb = tool( "query_database", "Run a read-only SQL query against the application database", { sql: z.string().describe("SQL SELECT query to execute"), }, async ({ sql }) => { // Validate: only allow SELECT queries if (!sql.trim().toUpperCase().startsWith("SELECT")) { return { content: [{ type: "text", text: "Error: Only SELECT queries are allowed." }], }; } const result = await pool.query(sql); return { content: [ { type: "text", text: JSON.stringify(result.rows, null, 2), }, ], }; } );
外部MCPサーバーへの接続
インプロセスツールに加えて、既存のMCPサーバーに接続することもできます - Claude Desktop、Cursor、その他のMCPクライアントで動作するものと同じサーバーです。
for await (const message of query({ prompt: "Check the latest issues in the frontend repo and summarize them", options: { mcpServers: { github: { command: "npx", args: ["-y", "@modelcontextprotocol/server-github"], env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN }, }, }, allowedTools: ["mcp__github__*"], }, })) { // ... }
複数のMCPサーバーを組み合わせることができます。エージェントは接続されたすべてのサーバーのすべてのツールを認識し、必要に応じて使用します。
マルチエージェントオーケストレーション
複雑なワークフローでは、親エージェントがタスクを委任する専門的なサブエージェントを定義できます。各サブエージェントは独自のプロンプト、ツール、専門領域を持ちます。
for await (const message of query({ prompt: "Review the PR, check for security issues, and update the changelog", options: { allowedTools: ["Read", "Edit", "Bash", "Glob", "Grep", "Agent"], agents: [ { name: "security-reviewer", description: "Reviews code for security vulnerabilities", prompt: "You are a security expert. Analyze code for OWASP Top 10 vulnerabilities.", allowedTools: ["Read", "Glob", "Grep"], }, { name: "changelog-writer", description: "Updates the CHANGELOG.md file based on recent changes", prompt: "You maintain the project changelog. Follow Keep a Changelog format.", allowedTools: ["Read", "Edit", "Bash"], }, ], }, })) { // The parent agent will: // 1. Read the PR diff // 2. Delegate security review to security-reviewer // 3. Delegate changelog update to changelog-writer // 4. Synthesize results }
委任を有効にするには、親の allowedTools に "Agent" を含めてください。サブエージェントは独自のツールで動作し、明示的に許可されない限り親のツールにはアクセスできません。
セッションと継続性
エージェントはセッションを使って複数のクエリにわたってコンテキストを維持できます。最初のインタラクションから session_id を取得し、後続のクエリで resume に渡します。
let sessionId: string | undefined; // First query for await (const message of query({ prompt: "Read the project structure and understand the architecture", options: { allowedTools: ["Read", "Glob", "Grep"] }, })) { if (message.type === "init") { sessionId = message.session_id; } } // Follow-up query (same session, full context preserved) for await (const message of query({ prompt: "Now refactor the auth module based on what you learned", resume: sessionId, options: { allowedTools: ["Read", "Edit", "Bash"] }, })) { // Agent remembers the full project context from the first query }
Claude Managed Agents
エージェントのインフラを自分でホスティングしたくない場合、Claude Managed Agents(2026年4月ローンチ)がフルマネージドのクラウドサービスを提供します。Anthropicがコンテナを実行し、スケーリングを処理し、ストリーミングAPIを提供します。
主な違い: Agent SDKでは、自分のインフラでエージェントループを実行します。Managed Agentsでは、Anthropicがエージェントをホスティングして実行します。セッションベースのAPIでやり取りし、Server-Sent Eventsでイベントを受信します。
料金:
- Agent SDK: 標準のClaude APIトークン料金のみ。ホスティングは自分で行います。
- Managed Agents: トークン料金に加えて、セッション時間あたり$0.08(ミリ秒単位で課金)。
本番環境のベストプラクティス
1. 常にサンドボックス化する
本番マシンで無制限のパーミッションでエージェントを実行しないでください。コンテナ(Docker、Fly.io、Modal)やサンドボックス環境(E2B、Vercel Sandbox)を使用してください。
2. ツールアクセスを制限する
最小権限の原則に従ってください。レポートを生成するエージェントに Bash や Write は不要です。
// Too permissive allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"] // Better: only what's needed allowedTools: ["Read", "Glob", "Grep"]
3. フックでガードレールを設定する
フックを使うと、ツール呼び出しの実行前後にインターセプトできます。ログ記録、バリデーション、レート制限に使用してください。
const conversation = query({ prompt: "Analyze the codebase", options: { allowedTools: ["Read", "Glob", "Grep"], hooks: { PreToolUse: async (toolName, input) => { console.log(`Tool call: ${toolName}`, input); // Return false to block the call if (toolName === "Bash" && input.command.includes("rm")) { return false; } return true; }, }, }, });
4. エラーを適切に処理する
エージェントループはエラーを生成する可能性があります - ツールの失敗、APIレート制限、コンテキストウィンドウのオーバーフロー。常にメッセージタイプを確認してください。
for await (const message of conversation) { switch (message.type) { case "assistant": // Agent reasoning break; case "tool_use": // Agent is calling a tool break; case "result": if (message.subtype === "error") { console.error("Agent failed:", message.error); } break; } }
5. トークン使用量を監視する
エージェントループは、特に大規模なコードベースで大量のトークンを消費する可能性があります。SDKには自動コンテキスト圧縮が含まれていますが、使用量は引き続き監視すべきです。
まとめ
Claude Agent SDKは、LLMを質問応答マシンからジュニアデベロッパーに近い存在に変えます。エージェントは読み取り、書き込み、実行、検証、反復が可能です - 人間が行うのと同じワークフローです。
小さく始めましょう: いくつかのビルトインツールでエージェントを構築してください。次に、特定のドメイン向けにカスタムMCPツールを追加してください。ワークフローに専門化が必要になったら、マルチエージェントオーケストレーションにスケールアップしてください。
エージェントループはClaude Codeを動かしているものと同じです。それがソフトウェアを構築できるなら、あなたのエージェントにもできます。
はじめるためのチェックリスト:
- SDKをインストールする (
npm install @anthropic-ai/claude-agent-sdk)- 環境変数に
ANTHROPIC_API_KEYを設定する- ビルトインツール(Read、Glob、Grep)でシンプルなエージェントを構築する
- インプロセスMCPサーバーでカスタムツールを追加する
- 外部MCPサーバー(GitHub、PostgreSQLなど)に接続する
- サブエージェントによるマルチエージェントオーケストレーションを実装する
- 本番環境用にサンドボックス化された環境を構築する
- ログ記録とガードレール用のフックを追加する