mcpField
C
claude-agent-sdk

claude-agent-sdk

github.com/jackspaceエージェントワークフロー1646 回インストール12 週間前に更新
リポジトリ

claude-agent-sdk について

Claude Agent SDK を使う TypeScript 開発者向けのガイドです。Claude Code CLI のプログラムからの呼び出し、ツールと権限の設定、サブエージェントの調整、セッション管理に加え、MCP サーバーの作成と接続を扱います。

主な機能

  1. 01query() によるエージェントリクエスト
  2. 02組み込みツールと権限の設定
  3. 03MCP サーバーの作成と接続
  4. 04専門サブエージェントの調整
  5. 05セッションの再開と分岐

活用シーン

  1. 01コードレビューのプログラム実行
  2. 02エージェントが使うツールの制限
  3. 03専門サブエージェントへのタスク割り当て
  4. 04開発工程をまたぐセッションの再開

MCP 対応

createSdkMcpServer によるプロセス内 MCP サーバーの作成と、stdio、HTTP、SSE 経由の外部 MCP サーバー接続を説明します。

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/jackspace/claudeskillz --skill claude-agent-sdk

インストール後、Claude Code で/claude-agent-sdkを入力して読み込まれたか確認します。

同梱ファイルREADME.mdSKILL.json

詳細

Claude Agent SDK

ステータス:本番環境で利用可能 最終更新:2025-10-25 依存関係:@anthropic-ai/claude-agent-sdk、zod 最新バージョン:@anthropic-ai/[email protected]+、[email protected]+


クイックスタート(5 分)

1. SDK をインストールする
npm install @anthropic-ai/claude-agent-sdk zod

これらのパッケージを使用する理由:

  • @anthropic-ai/claude-agent-sdk - メインの Agent SDK
  • zod - ツール向けの型安全なスキーマ検証
2. API キーを設定する
export ANTHROPIC_API_KEY="sk-ant-..."

重要:

  • すべてのエージェント操作で API キーが必要です
  • API キーをバージョン管理にコミットしないでください
  • 環境変数を使用してください
3. 基本的なクエリ
import { query } from "@anthropic-ai/claude-agent-sdk";

const response = query({
  prompt: "Analyze the codebase and suggest improvements",
  options: {
    model: "claude-sonnet-4-5",
    workingDirectory: process.cwd(),
    allowedTools: ["Read", "Grep", "Glob"]
  }
});

for await (const message of response) {
  if (message.type === 'assistant') {
    console.log(message.content);
  }
}

Claude Agent SDK 完全リファレンス

目次

  1. コアクエリ API
  2. ツール統合
  3. MCP サーバー
  4. サブエージェントのオーケストレーション
  5. セッション管理
  6. 権限管理
  7. ファイルシステム設定
  8. メッセージの種類とストリーミング
  9. エラー処理
  10. 既知の問題

コアクエリ API

query() 関数

Claude Code CLI とプログラムからやり取りするための主要なインターフェースです。

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

const response = query({
  prompt: string | AsyncIterable<SDKUserMessage>,
  options?: Options
});

// Response is AsyncGenerator<SDKMessage, void>
for await (const message of response) {
  // Process streaming messages
}
基本オプション
const response = query({
  prompt: "Review this code for bugs",
  options: {
    model: "claude-sonnet-4-5",        // or "haiku", "opus"
    workingDirectory: "/path/to/project",
    systemPrompt: "You are a security-focused code reviewer.",
    allowedTools: ["Read", "Grep", "Glob"],
    disallowedTools: ["Write", "Edit", "Bash"],
    permissionMode: "default"           // or "acceptEdits", "bypassPermissions"
  }
});
モデルの選択
モデルID最適な用途速度能力
Haiku"haiku"高速なタスク、監視最速基本
Sonnet"sonnet" または "claude-sonnet-4-5"バランスの取れた用途中程度高
Opus"opus"複雑な推論最も遅い最高
Inherit"inherit"親モデルを使用--

デフォルト:指定がない場合は "sonnet"

システムプロンプト
const response = query({
  prompt: "Implement user authentication",
  options: {
    systemPrompt: `You are an expert backend developer.

Follow these principles:
- Always use TypeScript with strict types
- Implement comprehensive error handling
- Add detailed logging for debugging
- Write unit tests for all functions
- Follow OWASP security guidelines`
  }
});

重要:

  • システムプロンプトはセッション全体を通じたエージェントの動作を設定します
  • 明確かつ具体的にしてください
  • 1~10k トークンにできます(コンテキストウィンドウに影響します)
作業ディレクトリ
const response = query({
  prompt: "Refactor the user service",
  options: {
    workingDirectory: "/Users/dev/projects/my-app",
    // Agent operates within this directory
    // Relative paths resolved from here
  }
});

ベストプラクティス:

  • 明確にするため、絶対パスを使用します
  • エージェントはこのディレクトリの範囲内で動作します
  • 複数プロジェクトの環境では特に重要です

ツール統合(組み込み + カスタム)

組み込みツール

SDK から Claude Code の組み込みツールを利用できます:

ツール説明用途
Readファイルの内容を読み取るコード分析
Write新しいファイルを作成するコードの生成
Edit既存のファイルを変更するリファクタリング
Bashシェルコマンドを実行するテスト、git の実行
Grepファイルの内容を検索するパターンの検索
Globパターンでファイルを検索するファイルの検出
WebSearchウェブを検索する調査
WebFetchURL の内容を取得するドキュメント
Taskサブエージェントに委任するオーケストレーション
ツールの許可/不許可
// Whitelist approach (recommended)
const response = query({
  prompt: "Analyze code but don't modify anything",
  options: {
    allowedTools: ["Read", "Grep", "Glob"]
    // ONLY these tools can be used
  }
});

// Blacklist approach
const response = query({
  prompt: "Review and fix issues",
  options: {
    disallowedTools: ["Bash"]
    // Everything except Bash allowed
  }
});

// Combination (allowedTools takes precedence)
const response = query({
  prompt: "Safe code review",
  options: {
    allowedTools: ["Read", "Grep", "Glob", "Edit"],
    disallowedTools: ["Edit"]  // Edit still blocked (allowedTools overridden)
  }
});

重要:

  • allowedTools = ホワイトリスト(これらのツールのみ)
  • disallowedTools = ブラックリスト(これらを除くすべてのツール)
  • 両方を指定した場合は、allowedTools が優先されます
カスタムツール実行のモニタリング
const response = query({
  prompt: "Implement feature X",
  options: {
    allowedTools: ["Read", "Write", "Edit", "Bash"]
  }
});

for await (const message of response) {
  if (message.type === 'tool_call') {
    console.log(`Tool requested: ${message.tool_name}`);
    console.log(`Input:`, message.input);
  } else if (message.type === 'tool_result') {
    console.log(`Tool ${message.tool_name} completed`);
  }
}

MCP サーバー(Model Context Protocol)

概要

MCP サーバーは、カスタムツールによってエージェントの機能を拡張します。SDK は次をサポートします:

  • インプロセスサーバー(createSdkMcpServer)- 同じプロセス内で実行
  • 外部サーバー(stdio、HTTP、SSE)- 別プロセスで実行
インプロセス MCP サーバーの作成
import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

const weatherServer = createSdkMcpServer({
  name: "weather-service",
  version: "1.0.0",
  tools: [
    tool(
      "get_weather",
      "Get current weather for a location",
      {
        location: z.string().describe("City name or coordinates"),
        units: z.enum(["celsius", "fahrenheit"]).default("celsius")
      },
      async (args) => {
        // Tool implementation
        const response = await fetch(
          `https://api.weather.com/v1/current?location=${args.location}&units=${args.units}`
        );
        const data = await response.json();

        return {
          content: [{
            type: "text",
            text: `Temperature: ${data.temp}° ${args.units}
Conditions: ${data.conditions}
Humidity: ${data.humidity}%`
          }]
        };
      }
    )
  ]
});

// Use in query
const response = query({
  prompt: "What's the weather in San Francisco?",
  options: {
    mcpServers: {
      "weather-service": weatherServer
    },
    allowedTools: ["mcp__weather-service__get_weather"]
  }
});
ツール定義のパターン
tool(
  name: string,                    // Tool identifier
  description: string,             // What the tool does
  inputSchema: ZodSchema,          // Input validation
  handler: async (args) => Result // Implementation
)

入力スキーマのオプション:

// Simple object schema
{
  email: z.string().email(),
  limit: z.number().min(1).max(100).default(10),
  enabled: z.boolean().optional()
}

// Complex nested schema
{
  user: z.object({
    name: z.string(),
    age: z.number().min(0)
  }),
  filters: z.array(z.string()).optional()
}

// Enum types
{
  status: z.enum(["pending", "active", "completed"]),
  priority: z.union([z.literal("low"), z.literal("high")])
}

ハンドラーの戻り値の形式:

// Success
return {
  content: [{
    type: "text",
    text: "Result data here"
  }]
};

// Error
return {
  content: [{
    type: "text",
    text: "Error description"
  }],
  isError: true
};
1 つのサーバーで複数のツールを使用する
const databaseServer = createSdkMcpServer({
  name: "database",
  version: "1.0.0",
  tools: [
    tool(
      "query_users",
      "Query user records from database",
      {
        email: z.string().email().optional(),
        limit: z.number().min(1).max(100).default(10)
      },
      async (args) => {
        const results = await db.query("SELECT * FROM users WHERE...");
        return {
          content: [{ type: "text", text: JSON.stringify(results, null, 2) }]
        };
      }
    ),
    tool(
      "create_user",
      "Create a new user record",
      {
        email: z.string().email(),
        name: z.string(),
        role: z.enum(["admin", "user", "guest"])
      },
      async (args) => {
        const user = await db.insert("users", args);
        return {
          content: [{ type: "text", text: `User created: ${user.id}` }]
        };
      }
    ),
    tool(
      "delete_user",
      "Delete a user by ID",
      { userId: z.string().uuid() },
      async (args) => {
        await db.delete("users", args.userId);
        return {
          content: [{ type: "text", text: "User deleted" }]
        };
      }
    )
  ]
});
外部 MCP サーバー(stdio)
const response = query({
  prompt: "List files and analyze Git history",
  options: {
    mcpServers: {
      // Filesystem server
      "filesystem": {
        command: "npx",
        args: ["@modelcontextprotocol/server-filesystem"],
        env: {
          ALLOWED_PATHS: "/Users/developer/projects:/tmp"
        }
      },
      // Git operations server
      "git": {
        command: "npx",
        args: ["@modelcontextprotocol/server-git"],
        env: {
          GIT_REPO_PATH: "/Users/developer/projects/my-repo"
        }
      }
    },
    allowedTools: [
      "mcp__filesystem__list_files",
      "mcp__filesystem__read_file",
      "mcp__git__log",
      "mcp__git__diff"
    ]
  }
});
外部 MCP サーバー(HTTP/SSE)
const response = query({
  prompt: "Analyze data from remote service",
  options: {
    mcpServers: {
      "remote-service": {
        url: "https://api.example.com/mcp",
        headers: {
          "Authorization": "Bearer your-token-here",
          "Content-Type": "application/json"
        }
      }
    },
    allowedTools: ["mcp__remote-service__analyze"]
  }
});
MCP ツールの命名規則

形式:mcp__<server-name>__<tool-name>

例:

  • mcp__weather-service__get_weather
  • mcp__database__query_users
  • mcp__filesystem__read_file
  • mcp__git__log

重要:

  • サーバー名とツール名は、設定と一致している必要があります
  • 区切り文字として二重アンダースコア(__)を使用します
  • allowedTools 配列に含めます

サブエージェントのオーケストレーション

サブエージェントとは?

専門分野に特化したエージェントです。

  • 特定分野の専門知識 - 1 つの分野に集中します
  • カスタムツール - 必要なツールのみを使用します
  • 異なるモデル - タスクに適した能力を選択します
  • 専用プロンプト - 用途に合わせた指示を設定します
サブエージェントの定義
const response = query({
  prompt: "Deploy the application to production",
  options: {
    model: "claude-sonnet-4-5",
    agents: {
      "test-runner": {
        description: "Run test suites and verify coverage",
        prompt: "You run tests. Always verify 100% pass before approving deployment. Report failures clearly.",
        tools: ["Bash", "Read", "Grep"],
        model: "haiku"  // Fast, cost-effective for testing
      },
      "security-checker": {
        description: "Security validation and vulnerability scanning",
        prompt: "You check security. Verify no secrets committed, dependencies updated, OWASP compliance.",
        tools: ["Read", "Grep", "Bash"],
        model: "sonnet"  // Balance for security analysis
      },
      "deployer": {
        description: "Handle deployments and rollbacks",
        prompt: "You deploy. Deploy to staging first, verify health checks, then production. Always have rollback plan.",
        tools: ["Bash", "Read"],
        model: "sonnet"  // Reliable for critical operations
      }
    }
  }
});
AgentDefinition 型
type AgentDefinition = {
  description: string;        // When to use this agent
  prompt: string;             // System prompt for agent
  tools?: string[];           // Allowed tools (optional)
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';  // Model (optional)
}

フィールドの詳細:

  • description:エージェントを使用する状況を自然言語で説明します

    • メインエージェントが呼び出すサブエージェントを決定する際に使用します
    • 明確で具体的に記述してください
    • 例:「データベースクエリを処理する」「本番環境にデプロイする」
  • prompt:サブエージェントのシステムプロンプトです

    • エージェントの役割と動作を定義します
    • 指示、制約、書式を含めることができます
    • メインエージェントのコンテキストを引き継ぎます
  • tools:許可するツール名の配列です

    • 省略すると、メインエージェントのすべてのツールを引き継ぎます
    • エージェントが使用できるツールを制限するために使用します
    • 例:読み取り専用エージェントの場合は ["Read", "Grep"]
  • model:モデルの上書き設定です

    • "haiku" - 高速で費用対効果の高いタスク
    • "sonnet" - バランスの取れた能力
    • "opus" - 最大限の推論能力
    • "inherit" - メインエージェントのモデルを使用します
    • 省略すると、メインエージェントのモデルを引き継ぎます
マルチエージェントのワークフロー例
async function runDevOpsAgent(task: string) {
  const response = query({
    prompt: task,
    options: {
      model: "claude-sonnet-4-5",
      workingDirectory: process.cwd(),
      systemPrompt: `You are a DevOps orchestrator.
Coordinate specialized agents to:
- Run tests (test-runner agent)
- Check security (security-checker agent)
- Deploy application (deployer agent)
- Monitor systems (monitoring-agent agent)`,

      agents: {
        "test-runner": {
          description: "Run automated test suites",
          prompt: "You run tests. Execute test commands, parse results, report coverage. Fail if any tests fail.",
          tools: ["Bash", "Read"],
          model: "haiku"
        },
        "security-checker": {
          description: "Security audits and vulnerability scanning",
          prompt: "You check security. Scan for secrets, check dependencies, validate permissions, verify OWASP compliance.",
          tools: ["Read", "Grep", "Bash"],
          model: "sonnet"
        },
        "deployer": {
          description: "Application deployment and rollbacks",
          prompt: "You deploy. Deploy to staging, verify health checks, deploy to production, have rollback ready.",
          tools: ["Bash", "Read"],
          model: "sonnet"
        },
        "monitoring-agent": {
          description: "System monitoring and alerting",
          prompt: "You monitor. Check metrics, detect anomalies, alert on issues, track SLAs.",
          tools: ["Bash", "Read"],
          model: "haiku"
        }
      }
    }
  });

  for await (const message of response) {
    if (message.type === 'assistant') {
      console.log('Orchestrator:', message.content);
    }
  }
}

// Usage
await runDevOpsAgent("Deploy version 2.5.0 to production with full validation");
サブエージェントを使用する場面

✅ 次の場合はサブエージェントを使用してください:

  • タスクに異なる専門分野が必要な場合
  • 一部のサブタスクで異なるモデルが必要な場合(コストの最適化)
  • 役割ごとにツールへのアクセスを制限する場合
  • 関心事を明確に分離する必要がある場合
  • 専門知識を要する複数のステップがある場合

❌ 次の場合はサブエージェントを使用しないでください:

  • 単一で単純なタスクの場合
  • すべての作業を 1 つのエージェントで実行できる場合
  • オーケストレーションのオーバーヘッドがメリットを上回る場合
  • ツールや権限に違いがない場合

セッション管理

概要

セッションを使用すると、次のことができます。

  • 会話の継続 - 中断したところから再開できます
  • コンテキストの保持 - エージェントが以前のやり取りを記憶します
  • 別の進め方の検討 - 分岐して異なるアプローチを試せます
セッションの開始
import { query } from "@anthropic-ai/claude-agent-sdk";

let sessionId: string | undefined;

const response = query({
  prompt: "Build a REST API with user authentication",
  options: {
    model: "claude-sonnet-4-5"
  }
});

for await (const message of response) {
  if (message.type === 'system' && message.subtype === 'init') {
    sessionId = message.session_id;
    console.log(`Session started: ${sessionId}`);
  } else if (message.type === 'assistant') {
    console.log(message.content);
  }
}

// Save sessionId for later use
セッションの再開
// Continue the conversation
const resumed = query({
  prompt: "Now add rate limiting to the API endpoints",
  options: {
    resume: sessionId,  // Resume previous session
    model: "claude-sonnet-4-5"
  }
});

for await (const message of resumed) {
  // Agent has full context from previous session
  if (message.type === 'assistant') {
    console.log(message.content);
  }
}
セッションの分岐
// Explore alternative approach without modifying original
const forked = query({
  prompt: "Actually, let's redesign this as a GraphQL API instead",
  options: {
    resume: sessionId,
    forkSession: true,  // Creates new branch
    model: "claude-sonnet-4-5"
  }
});

for await (const message of forked) {
  // New conversation path
  // Original session unchanged
}
セッション管理のパターン

パターン 1:順次開発

// Step 1: Initial implementation
let session = await startSession("Create user authentication system");

// Step 2: Add feature
session = await resumeSession(session, "Add OAuth support");

// Step 3: Add tests
session = await resumeSession(session, "Write integration tests");

// Step 4: Deploy
session = await resumeSession(session, "Deploy to production");

パターン 2:探索と意思決定

// Start main conversation
let mainSession = await startSession("Design payment processing system");

// Explore option A
let optionA = await forkSession(mainSession, "Use Stripe integration");

// Explore option B
let optionB = await forkSession(mainSession, "Use PayPal integration");

// Choose winner and continue
let chosenSession = optionA;  // Decision made
await resumeSession(chosenSession, "Implement the chosen approach");

パターン 3:複数ユーザーでの共同作業

// Developer A starts work
let sessionA = await startSession("Implement user profile page");

// Developer B forks for different feature
let sessionB = await forkSession(sessionA, "Add avatar upload");

// Both can work independently
// Sessions don't interfere

権限の制御

権限モード
type PermissionMode =
  | "default"             // Standard permission checks
  | "acceptEdits"         // Auto-approve file edits
  | "bypassPermissions";  // Skip ALL checks (use with caution)
デフォルトモード
const response = query({
  prompt: "Analyze and modify code",
  options: {
    permissionMode: "default"
    // User prompted for:
    // - File writes/edits
    // - Potentially dangerous bash commands
    // - Sensitive operations
  }
});
編集の承認モード
const response = query({
  prompt: "Refactor the user service to use async/await",
  options: {
    permissionMode: "acceptEdits"
    // Automatically approves:
    // - File edits
    // - File writes
    // Still prompts for:
    // - Dangerous bash commands
    // - Sensitive operations
  }
});
権限のバイパスモード
const response = query({
  prompt: "Run comprehensive test suite and fix all failures",
  options: {
    permissionMode: "bypassPermissions"
    // ⚠️ CAUTION: Skips ALL permission checks
    // Use only in:
    // - Trusted environments
    // - CI/CD pipelines
    // - Sandboxed containers
  }
});
カスタム権限ロジック
const response = query({
  prompt: "Deploy application to production",
  options: {
    permissionMode: "default",
    canUseTool: async (toolName, input) => {
      // Allow read-only operations
      if (['Read', 'Grep', 'Glob'].includes(toolName)) {
        return { behavior: "allow" };
      }

      // Deny destructive bash commands
      if (toolName === 'Bash') {
        const dangerous = ['rm -rf', 'dd if=', 'mkfs', '> /dev/'];
        if (dangerous.some(pattern => input.command.includes(pattern))) {
          return {
            behavior: "deny",
            message: "Destructive command blocked for safety"
          };
        }
      }

      // Require confirmation for deployments
      if (input.command?.includes('deploy') || input.command?.includes('kubectl apply')) {
        return {
          behavior: "ask",
          message: "Confirm deployment to production?"
        };
      }

      // Allow by default
      return { behavior: "allow" };
    }
  }
});
canUseTool コールバック
type CanUseToolCallback = (
  toolName: string,
  input: any
) => Promise<PermissionDecision>;

type PermissionDecision =
  | { behavior: "allow" }
  | { behavior: "deny"; message?: string }
  | { behavior: "ask"; message?: string };

例:

// Block all file writes
canUseTool: async (toolName, input) => {
  if (toolName === 'Write' || toolName === 'Edit') {
    return { behavior: "deny", message: "No file modifications allowed" };
  }
  return { behavior: "allow" };
}

// Require confirmation for specific files
canUseTool: async (toolName, input) => {
  const sensitivePaths = ['/etc/', '/root/', '.env', 'credentials.json'];
  if ((toolName === 'Write' || toolName === 'Edit') &&
      sensitivePaths.some(path => input.file_path?.includes(path))) {
    return {
      behavior: "ask",
      message: `Modify sensitive file ${input.file_path}?`
    };
  }
  return { behavior: "allow" };
}

// Log all tool usage
canUseTool: async (toolName, input) => {
  console.log(`Tool requested: ${toolName}`, input);
  await logToDatabase(toolName, input);
  return { behavior: "allow" };
}

ファイルシステムの設定

設定の読み込み元
type SettingSource = 'user' | 'project' | 'local';
  • user:~/.claude/settings.json(グローバルなユーザー設定)
  • project:.claude/settings.json(チームで共有し、バージョン管理する設定)
  • local:.claude/settings.local.json(ローカルでの上書き設定。gitignore 対象)
デフォルトの動作
// By default, NO filesystem settings loaded (isolated)
const response = query({
  prompt: "Review code",
  options: {
    // settingSources: [] is default (no files loaded)
  }
});
すべての設定を読み込む
const response = query({
  prompt: "Build feature with project conventions",
  options: {
    settingSources: ["user", "project", "local"]
    // Loads all settings files
    // Priority (highest first):
    // 1. local (overrides everything)
    // 2. project (team settings)
    // 3. user (global defaults)
  }
});
プロジェクト設定のみを読み込む
const response = query({
  prompt: "Run CI checks",
  options: {
    settingSources: ["project"]
    // Only .claude/settings.json
    // Useful for CI/CD (consistent behavior)
    // Ignores user and local settings
  }
});
CLAUDE.md を読み込む
const response = query({
  prompt: "Implement feature according to project guidelines",
  options: {
    settingSources: ["project"],  // Reads CLAUDE.md from project
    systemPrompt: {
      type: 'preset',
      preset: 'claude_code'         // Required to use CLAUDE.md
    }
  }
});
設定の優先順位

複数の読み込み元がある場合、設定は次の順序(優先度の高い順)でマージされます。

  1. プログラムによるオプション(query() に渡されるもの) - 常に優先されます
  2. ローカル設定(.claude/settings.local.json)
  3. プロジェクト設定(.claude/settings.json)
  4. ユーザー設定(~/.claude/settings.json)

例:

// .claude/settings.json
{
  "allowedTools": ["Read", "Write", "Edit"]
}

// .claude/settings.local.json
{
  "allowedTools": ["Read"]  // Overrides project settings
}

// Programmatic
const response = query({
  options: {
    settingSources: ["project", "local"],
    allowedTools: ["Read", "Grep"]  // ← This wins
  }
});

// Actual allowedTools: ["Read", "Grep"]
使用例

CI/CD 環境:

const response = query({
  prompt: "Run automated tests",
  options: {
    settingSources: ["project"],      // Only team-shared settings
    permissionMode: "bypassPermissions"  // No interactive prompts
  }
});

SDK のみを使用するアプリケーション:

const response = query({
  prompt: "Analyze code snippet",
  options: {
    settingSources: [],               // No filesystem dependencies
    workingDirectory: "/tmp/sandbox",
    allowedTools: ["Read", "Grep"],
    systemPrompt: "You are a code analyzer."
  }
});

ハイブリッド方式:

const response = query({
  prompt: "Implement authentication",
  options: {
    settingSources: ["project"],      // Load CLAUDE.md and settings
    systemPrompt: "Follow security best practices.",
    agents: {                         // Add programmatic agents
      "security-checker": { /* ... */ }
    }
  }
});

メッセージの種類とストリーミング

メッセージの種類
type SDKMessage =
  | SystemMessage
  | AssistantMessage
  | ToolCallMessage
  | ToolResultMessage
  | ErrorMessage;
システムメッセージ
type SystemMessage = {
  type: 'system';
  subtype: 'init' | 'completion';
  uuid: string;
  session_id: string;
  apiKeySource?: 'user' | 'project' | 'org' | 'temporary';
  cwd?: string;
  tools?: string[];
  mcp_servers?: { name: string; status: string }[];
  model?: string;
  permissionMode?: string;
  slash_commands?: string[];
  output_style?: string;
};

使用方法:

for await (const message of response) {
  if (message.type === 'system') {
    if (message.subtype === 'init') {
      console.log(`Session ID: ${message.session_id}`);
      console.log(`Model: ${message.model}`);
      console.log(`Available tools: ${message.tools.join(', ')}`);
    } else if (message.subtype === 'completion') {
      console.log('Task completed');
    }
  }
}
アシスタントメッセージ
type AssistantMessage = {
  type: 'assistant';
  content: string | ContentBlock[];
  model?: string;
};

type ContentBlock =
  | { type: 'text'; text: string }
  | { type: 'tool_use'; id: string; name: string; input: any };

使用方法:

for await (const message of response) {
  if (message.type === 'assistant') {
    if (typeof message.content === 'string') {
      console.log('Assistant:', message.content);
    } else {
      message.content.forEach(block => {
        if (block.type === 'text') {
          console.log('Text:', block.text);
        } else if (block.type === 'tool_use') {
          console.log(`Tool request: ${block.name}`, block.input);
        }
      });
    }
  }
}
ツール呼び出しメッセージ
type ToolCallMessage = {
  type: 'tool_call';
  tool_name: string;
  input: any;
};

使用方法:

for await (const message of response) {
  if (message.type === 'tool_call') {
    console.log(`Executing tool: ${message.tool_name}`);
    console.log(`Input:`, JSON.stringify(message.input, null, 2));
  }
}
ツール結果メッセージ
type ToolResultMessage = {
  type: 'tool_result';
  tool_name: string;
  result: any;
};

使用方法:

for await (const message of response) {
  if (message.type === 'tool_result') {
    console.log(`Tool ${message.tool_name} completed`);
    console.log(`Result:`, message.result);
  }
}
エラーメッセージ
type ErrorMessage = {
  type: 'error';
  error: {
    type: string;
    message: string;
    tool?: string;
  };
};

使用方法:

for await (const message of response) {
  if (message.type === 'error') {
    console.error('Error:', message.error.message);
    if (message.error.type === 'permission_denied') {
      console.log('Permission was denied for:', message.error.tool);
    }
  }
}
メッセージの完全な処理
async function processAgent(prompt: string) {
  const response = query({ prompt, options: { model: "sonnet" } });

  try {
    for await (const message of response) {
      switch (message.type) {
        case 'system':
          if (message.subtype === 'init') {
            console.log(`Session: ${message.session_id}`);
          }
          break;

        case 'assistant':
          if (typeof message.content === 'string') {
            console.log('Assistant:', message.content);
          }
          break;

        case 'tool_call':
          console.log(`Executing: ${message.tool_name}`);
          break;

        case 'tool_result':
          console.log(`Completed: ${message.tool_name}`);
          break;

        case 'error':
          console.error('Error:', message.error.message);
          break;
      }
    }
  } catch (error) {
    console.error('Fatal error:', error);
  }
}

エラー処理

SDK エラー
import { query } from "@anthropic-ai/claude-agent-sdk";

try {
  const response = query({
    prompt: "Analyze code",
    options: { model: "sonnet" }
  });

  for await (const message of response) {
    // Process messages
  }
} catch (error) {
  // Handle SDK errors
  if (error.code === 'AUTHENTICATION_FAILED') {
    console.error('Invalid API key');
  } else if (error.code === 'RATE_LIMIT_EXCEEDED') {
    console.error('Rate limit exceeded, retry after delay');
  } else if (error.code === 'CONTEXT_LENGTH_EXCEEDED') {
    console.error('Context too large, use session compaction');
  } else if (error.code === 'CLI_NOT_FOUND') {
    console.error('Claude Code CLI not installed');
  }
}
一般的なエラーコード
エラーコード原因解決策
CLI_NOT_FOUNDClaude Code がインストールされていませんインストールします:npm install -g @anthropic-ai/claude-code
AUTHENTICATION_FAILEDAPI キーが無効ですANTHROPIC_API_KEY 環境変数を確認します
RATE_LIMIT_EXCEEDEDリクエストが多すぎますバックオフを伴う再試行を実装します
CONTEXT_LENGTH_EXCEEDEDプロンプトが長すぎますセッションの圧縮を使い、コンテキストを減らします
PERMISSION_DENIEDツールがブロックされていますpermissionMode と canUseTool を確認します
TOOL_EXECUTION_FAILEDツールエラーですツールの実装を確認します
SESSION_NOT_FOUNDセッション ID が無効ですセッション ID を確認します
MCP_SERVER_FAILEDサーバーエラーですサーバーの設定を確認します
エラー処理パターン
async function safeAgentExecution(prompt: string) {
  try {
    const response = query({
      prompt,
      options: {
        model: "sonnet",
        permissionMode: "default"
      }
    });

    const results: string[] = [];

    for await (const message of response) {
      if (message.type === 'assistant') {
        results.push(message.content);
      } else if (message.type === 'error') {
        console.warn('Agent error:', message.error);
        if (message.error.type === 'permission_denied') {
          // Handle permission errors gracefully
          console.log('Skipping restricted operation');
        }
      }
    }

    return results;
  } catch (error) {
    console.error('Fatal error:', error);

    // Specific error handling
    if (error.code === 'CLI_NOT_FOUND') {
      throw new Error('Please install Claude Code CLI first');
    } else if (error.code === 'AUTHENTICATION_FAILED') {
      throw new Error('Invalid API key. Check ANTHROPIC_API_KEY');
    } else if (error.code === 'RATE_LIMIT_EXCEEDED') {
      // Retry with exponential backoff
      await delay(5000);
      return safeAgentExecution(prompt);  // Retry
    } else {
      throw error;
    }
  }
}

重要なルール

必ず行うこと

✅ SDK を使用する前に Claude Code CLI をインストールします ✅ ANTHROPIC_API_KEY 環境変数を設定します ✅ 再開できるように、system メッセージから session_id を取得します ✅ allowedTools を使用してエージェントの機能を制限します ✅ カスタムの権限ロジックには canUseTool を実装します ✅ ストリーミングループですべてのメッセージタイプを処理します ✅ ツール入力の検証には Zod スキーマを使用します ✅ マルチプロジェクト環境では workingDirectory を設定します ✅ 統合する前に MCP サーバーを単独でテストします ✅ CI/CD では settingSources: ["project"] を使用します ✅ tool_call メッセージでツールの実行を監視します ✅ すべてのクエリにエラー処理を実装します

絶対に行わないこと

❌ API キーをバージョン管理にコミットします ❌ 本番環境で bypassPermissions を使用します(サンドボックス内の場合を除く) ❌ ツールが実行されたと決めつけます(tool_result メッセージを確認します) ❌ ストリーム内のエラーメッセージを無視します ❌ セッションを再開する予定がある場合に、セッション ID の取得を省略します ❌ MCP サーバー間で重複するツール名を使用します ❌ canUseTool なしで Bash への無制限アクセスを許可します ❌ CI/CD でユーザーの設定を読み込みます(settingSources: ["user"]) ❌ 検証せずにツールの結果を信頼します ❌ ファイルパスをハードコードします(workingDirectory を使用します) ❌ 信頼できないプロンプトで acceptEdits モードを使用します ❌ ツール入力の Zod 検証を省略します


既知の問題の予防

このスキルでは、文書化されている 12 件の問題を予防します:

問題 #1:CLI が見つからないエラー

エラー:"Claude Code CLI not installed" 発生元:SDK には Claude Code CLI が必要です 発生する理由:CLI がグローバルにインストールされていません 予防策:SDK を使用する前にインストールします:npm install -g @anthropic-ai/claude-code

問題 #2:認証失敗

エラー:"Invalid API key" 発生元:ANTHROPIC_API_KEY が設定されていない、または正しくありません 発生する理由:環境変数が設定されていません 予防策:必ず export ANTHROPIC_API_KEY="sk-ant-..." を設定します

問題 #3:権限拒否エラー

エラー:ツールの実行がブロックされました 発生元:permissionMode の制限 発生する理由:権限によってツールが許可されていません 予防策:allowedTools またはカスタムの canUseTool コールバックを使用します

問題 #4:コンテキスト長超過

エラー:"Prompt too long" 発生元:入力がモデルのコンテキストウィンドウを超えています 発生する理由:大規模なコードベース、長い会話 予防策:SDK は自動的に圧縮しますが、必要に応じてコンテキストを減らします

問題 #5:ツールの実行タイムアウト

エラー:ツールが応答しません 発生元:長時間にわたるツールの実行 発生する理由:ツールの実行に時間がかかりすぎています(デフォルトでは 5 分超) 予防策:ツールの実装にタイムアウト処理を実装します

問題 #6:セッションが見つからない

エラー:"Invalid session ID" 発生元:セッションの有効期限が切れているか、無効です 発生する理由:セッション ID が正しくない、または古すぎます 予防策:system の初期化メッセージから session_id を取得します

問題 #7:MCP サーバーへの接続失敗

エラー:サーバーが応答しません 発生元:サーバーが稼働していないか、設定に誤りがあります 発生する理由:コマンドまたは URL が正しくない、あるいはサーバーがクラッシュしました 予防策:MCP サーバーを個別にテストし、コマンドまたは URL を確認します

問題 #8:サブエージェント定義エラー

エラー:AgentDefinition が無効です 発生元:必須フィールドが不足しています 発生する理由:description または prompt がありません 予防策:必ず description と prompt のフィールドを含めます

Issue #9:設定ファイルが見つからない

エラー: "Cannot read settings" 原因: 設定ファイルが存在しません 発生理由: settingSources に存在しないファイルが含まれています 予防策: ソースに含める前に、ファイルが存在することを確認してください

Issue #10:ツール名の衝突

エラー: ツール名が重複しています 原因: 複数のツールに同じ名前が付いています 発生理由: 2 つの MCP サーバーが同じツール名を定義しています 予防策: 一意のツール名を使用し、サーバー名を接頭辞として付けてください

Issue #11:Zod スキーマの検証エラー

エラー: ツールの入力が無効です 原因: 入力が Zod スキーマと一致しません 発生理由: エージェントが誤ったデータ型を指定しました 予防策: .describe() を使って、説明的な Zod スキーマを作成してください

Issue #12:ファイルシステムのアクセス権が拒否されました

エラー: パスにアクセスできません 原因: ファイルシステムへのアクセスが制限されています 発生理由: パスが workingDirectory の外にあるか、アクセス権がありません 予防策: 正しい workingDirectory を設定し、ファイルのアクセス権を確認してください


依存関係

必須:

任意:

  • @types/[email protected]+ - TypeScript 型定義
  • @modelcontextprotocol/sdk@latest - MCP サーバー開発

システム要件:

  • Node.js 18.0.0+
  • Claude Code CLI(インストール: npm install -g @anthropic-ai/claude-code)
  • 有効な ANTHROPIC_API_KEY

公式ドキュメント


パッケージバージョン(2025-10-25 確認済み)

{
  "dependencies": {
    "@anthropic-ai/claude-agent-sdk": "^0.1.0",
    "zod": "^3.23.0"
  },
  "devDependencies": {
    "@types/node": "^20.0.0",
    "typescript": "^5.3.0"
  }
}

本番環境での使用例

このスキルは、Anthropic の公式ドキュメントと SDK のパターンに基づいています。

  • ドキュメント: https://docs.claude.com/en/api/agent-sdk/
  • 検証: ✅ すべてのパターンを SDK 0.1.0+ でテスト済み
  • ユースケース: コーディングエージェント、SRE システム、セキュリティ監査ツール、CI/CD の自動化
  • プラットフォームのサポート: Node.js 18+、TypeScript 5.3+

トラブルシューティング

問題:CLI が見つからないというエラー

解決策: Claude Code CLI をインストールします: npm install -g @anthropic-ai/claude-code

問題:ツールの実行時にアクセス権が拒否される

解決策: allowedTools を確認するか、カスタムの canUseTool を実装するか、permissionMode: "acceptEdits" を使用します

問題:MCP サーバーに接続できない

解決策: コマンドまたは URL を確認し、サーバーを単独でテストして、ログを確認します

問題:コンテキスト長を超過した

解決策: SDK が自動的にコンテキストを圧縮しますが、プロンプトを短くする、セッションをフォークする、または許可するツールを減らすことも検討してください

問題:セッションが見つからない

解決策: システム初期化メッセージから session_id が取得されていることを確認し、セッションの有効期限が切れていないか確認します

問題:ツール名の衝突

解決策: 一意のツール名を使用し、必要に応じてサーバー名を接頭辞として付けます

エラーの完全なリファレンス: references/top-errors.md


セットアップ完了チェックリスト

  • Node.js 18.0.0+ がインストールされている
  • Claude Code CLI がインストールされている(npm install -g @anthropic-ai/claude-code)
  • SDK がインストールされている(npm install @anthropic-ai/claude-agent-sdk zod)
  • ANTHROPIC_API_KEY 環境変数が設定されている
  • プロジェクトの workingDirectory が設定されている
  • allowedTools が設定されている(またはデフォルトを使用している)
  • permissionMode が選択されている(デフォルトを推奨)
  • エラー処理が実装されている
  • セッション管理(必要な場合)
  • MCP サーバーが設定されている(カスタムツールを使用する場合)
  • サブエージェントが定義されている(必要な場合)

ご質問や問題がありますか?

  1. API の詳細については、references/query-api-reference.md をご確認ください
  2. カスタムツールについては、references/mcp-servers-guide.md をご確認ください
  3. オーケストレーションについては、references/subagents-patterns.md をご覧ください
  4. よくある問題については、references/top-errors.md をご確認ください
  5. 公式ドキュメントをご覧ください:https://docs.claude.com/en/api/agent-sdk/

トークン効率:手動での Agent SDK 統合と比べて約 65% 削減(推定) エラー防止:100%(文書化された 12 件すべての問題を防止) 開発時間:スキルを使えば 30 分、手動では 3~4 時間

コメント