claude-agent-sdk について
claude-agent-sdk は、Claude Agent SDK の設定方法を扱う開発者向けリファレンススキルです。構造化出力、ツール権限、サブエージェントの連携、セッション管理、MCP サーバー設定を解説します。
主な機能
- 01JSON Schema による構造化出力
- 02ツールフックと権限制御
- 03サブエージェント連携
- 04セッションの再開と分岐
- 05サンドボックス実行設定
活用シーン
- 01エージェント出力のスキーマ検証
- 02ツール呼び出しの承認ルール設定
- 03専用サブエージェントへのタスク委任
- 04既存セッションの再開や分岐
MCP 対応
stdio、HTTP、SSE トランスポートを使うインプロセスおよび外部 MCP サーバーの設定方法と、MCP ツールの命名規則を説明します。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ jezweb/ claude-skills --skill claude-agent-sdkインストール後、Claude Code で/claude-agent-sdkを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
README.md.claude-plugin/plugin.jsonreferences/mcp-servers-guide.mdpermissions-guide.mdquery-api-reference.mdsession-management.mdsubagents-patterns.mdtop-errors.mdrules/claude-agent-sdk.mdscripts/check-versions.shtemplates/basic-query.tscustom-mcp-server.tserror-handling.tsfilesystem-settings.tsmulti-agent-workflow.tspackage.jsonpermission-control.tsquery-with-tools.tssession-management.tssubagents-orchestration.tstsconfig.json詳細
Claude Agent SDK - 構造化出力とエラー防止ガイド
パッケージ: @anthropic-ai/[email protected] 破壊的変更: v0.1.45 - 構造化出力(2025 年 11 月)、v0.1.0 - デフォルトのシステムプロンプトなし、settingSources が必須
v0.1.45 以降の新機能(2025 年 11 月)
主な機能:
1. 構造化出力(v0.1.45、2025 年 11 月 14 日)
- JSON スキーマ検証 - 応答が正確なスキーマに一致することを保証します
outputFormatパラメーター - JSON スキーマまたは Zod で出力構造を定義します- 検証済みの結果にアクセス -
message.structured_output経由でアクセスします - ベータヘッダーが必須:
structured-outputs-2025-11-13 - 型安全性 - Zod スキーマによる完全な TypeScript 推論
例:
import { query } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const schema = z.object({
summary: z.string(),
sentiment: z.enum(['positive', 'neutral', 'negative']),
confidence: z.number().min(0).max(1)
});
const response = query({
prompt: "Analyze this code review feedback",
options: {
model: "claude-sonnet-4-5",
outputFormat: {
type: "json_schema",
json_schema: {
name: "AnalysisResult",
strict: true,
schema: zodToJsonSchema(schema)
}
}
}
});
for await (const message of response) {
if (message.type === 'result' && message.structured_output) {
// Guaranteed to match schema
const validated = schema.parse(message.structured_output);
console.log(`Sentiment: ${validated.sentiment}`);
}
}
Zod との互換性(v0.1.71 以降): SDK は、ピア依存関係として Zod v3.24.1 以降と Zod v4.0.0 以降の両方をサポートします。どちらのバージョンでもインポート方法は import { z } from "zod" のままです。
2. プラグインシステム(v0.1.27)
plugins配列 - ローカルのプラグインパスを読み込みます- カスタムプラグインのサポート - エージェントの機能を拡張します
3. フックシステム(v0.1.0 以降)
全 12 種類のフックイベント:
| フック | 発生するタイミング | 用途 |
|---|---|---|
PreToolUse | ツールの実行前 | ツール呼び出しを検証、変更、またはブロックします |
PostToolUse | ツールの実行後 | 結果を記録し、副作用をトリガーします |
Notification | エージェントからの通知時 | ステータス更新を表示します |
UserPromptSubmit | ユーザーのプロンプト受信時 | 入力を前処理または検証します |
SubagentStart | サブエージェントの起動時 | 委任を追跡し、コンテキストを記録します |
SubagentStop | サブエージェントの完了時 | 結果を集約し、クリーンアップします |
PreCompact | コンテキストの圧縮前 | 切り詰める前に状態を保存します |
PermissionRequest | 権限が必要なとき | カスタムの承認ワークフローを実行します |
Stop | エージェントの停止時 | クリーンアップし、最終ログを記録します |
SessionStart | セッションの開始時 | 状態を初期化します |
SessionEnd | セッションの終了時 | 状態を永続化し、クリーンアップします |
Error | エラー発生時 | カスタムのエラー処理を行います |
フックの設定:
const response = query({
prompt: "...",
options: {
hooks: {
PreToolUse: async (input) => {
console.log(`Tool: ${input.toolName}`);
return { allow: true }; // or { allow: false, message: "..." }
},
PostToolUse: async (input) => {
await logToolUsage(input.toolName, input.result);
}
}
}
});
4. その他のオプション
fallbackModel- 失敗時にモデルを自動でフォールバックしますmaxThinkingTokens- 拡張思考のトークン予算を制御しますstrictMcpConfig- MCP 設定を厳密に検証しますcontinue- 新しいプロンプトで再開します(resumeとは異なります)permissionMode: 'plan'- 計画ワークフロー向けの新しい権限モード
📚 ドキュメント: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
Claude Agent SDK 完全リファレンス
目次
- コアクエリー API
- ツール統合
- MCP サーバー
- サブエージェントのオーケストレーション
- セッション管理
- 権限制御
- サンドボックス設定
- ファイルのチェックポイント
- ファイルシステム設定
- クエリーオブジェクトのメソッド
- メッセージの種類とストリーミング
- エラー処理
- 既知の問題
コアクエリー API
主なシグネチャ:
query(prompt: string | AsyncIterable<SDKUserMessage>, options?: Options)
-> AsyncGenerator<SDKMessage>
重要なオプション:
outputFormat- 構造化 JSON スキーマ検証(v0.1.45 以降)settingSources- ファイルシステム設定の読み込み('user'|'project'|'local')canUseTool- カスタム権限ロジックのコールバックagents- プログラムによるサブエージェント定義mcpServers- MCP サーバーの設定permissionMode- 'default'|'acceptEdits'|'bypassPermissions'|'plan'betas- ベータ機能を有効化します(例: 1M コンテキストウィンドウ)sandbox- 安全な実行のためのサンドボックス設定enableFileCheckpointing- ファイル状態のスナップショットを有効化しますsystemPrompt- システムプロンプト(文字列またはプリセットオブジェクト)
拡張コンテキスト(1M トークン)
100 万トークンのコンテキストウィンドウを有効にします。
const response = query({
prompt: "Analyze this large codebase",
options: {
betas: ['context-1m-2025-08-07'], // Enable 1M context
model: "claude-sonnet-4-5"
}
});
システムプロンプトの設定
systemPrompt の形式は 2 種類あります。
// 1. Simple string
systemPrompt: "You are a helpful coding assistant."
// 2. Preset with optional append (preserves Claude Code defaults)
systemPrompt: {
type: 'preset',
preset: 'claude_code',
append: "\n\nAdditional context: Focus on security."
}
Claude Code のデフォルトの動作に独自の追加内容を加える場合は、プリセット形式を使用します。
ツールの統合(組み込み+カスタム)
ツールの制御:
allowedTools- ホワイトリスト(優先されます)disallowedTools- ブラックリストcanUseTool- カスタム権限コールバック(「権限制御」セクションを参照)
組み込みツール: Read、Write、Edit、Bash、Grep、Glob、WebSearch、WebFetch、Task、NotebookEdit、BashOutput、KillBash、ListMcpResources、ReadMcpResource、AskUserQuestion
AskUserQuestion ツール(v0.1.71+)
エージェントの実行中にユーザーとの対話を有効にします。
const response = query({
prompt: "Review and refactor the codebase",
options: {
allowedTools: ["Read", "Write", "Edit", "AskUserQuestion"]
}
});
// Agent can now ask clarifying questions
// Questions appear in message stream as tool_call with name "AskUserQuestion"
使用例:
- タスクの途中で曖昧な要件を確認する
- 破壊的な操作の前にユーザーの承認を得る
- 選択肢を提示して選択してもらう
ツール設定(v0.1.57+)
ツール設定の 3 つの形式:
// 1. Exact allowlist (string array)
tools: ["Read", "Write", "Grep"]
// 2. Disable all tools (empty array)
tools: []
// 3. Preset with defaults (object form)
tools: { type: 'preset', preset: 'claude_code' }
注: allowedTools と disallowedTools も引き続き使用できますが、tools のほうが柔軟性に優れています。
MCP サーバー(Model Context Protocol)
サーバーの種類:
- プロセス内 -
tool()定義を使用するcreateSdkMcpServer() - 外部 - stdio、HTTP、SSE トランスポート
ツールの定義:
tool(name: string, description: string, zodSchema, handler)
ハンドラーの戻り値:
{ content: [{ type: "text", text: "..." }], isError?: boolean }
外部 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>
重要:
- サーバー名とツール名は、設定と一致している必要があります
- 区切り文字としてアンダースコアを 2 つ(
__)使用します allowedTools配列に含めます
例: mcp__weather-service__get_weather、mcp__filesystem__read_file
サブエージェントのオーケストレーション
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)
skills?: string[]; // Skills to load (v0.2.10+)
maxTurns?: number; // Maximum turns before stopping (v0.2.10+)
}
フィールドの詳細:
- description:エージェントを使用するタイミング(メインエージェントが委任する際に使用)
- prompt:システムプロンプト(役割を定義し、メインのコンテキストを継承)
- tools:許可されたツール(省略した場合、メインエージェントから継承)
- model:モデルの上書き(
haiku/sonnet/opus/inherit) - skills:エージェントに読み込むスキル(v0.2.10+)
- maxTurns:制御を戻すまでのエージェントのターン数の上限(v0.2.10+)
使用方法:
agents: {
"security-checker": {
description: "Security audits and vulnerability scanning",
prompt: "You check security. Scan for secrets, verify OWASP compliance.",
tools: ["Read", "Grep", "Bash"],
model: "sonnet",
skills: ["security-best-practices"], // Load specific skills
maxTurns: 10 // Limit to 10 turns
}
}
⚠️ サブエージェントのクリーンアップに関する警告
既知の問題:親エージェントが停止しても、サブエージェントは停止しません(Issue #132)
親エージェントが(キャンセルまたはエラーによって)停止した場合、起動されたサブエージェントは孤立プロセスとして実行を継続します。これにより、次のような問題が発生する可能性があります。
- リソースリーク
- 親エージェントの停止後もツールの実行が継続する
- 再帰的なシナリオでの RAM 不足によるメモリ切れ(Claude Code Issue #4850)
回避策:Stop フックにクリーンアップ処理を実装します。
const response = query({
prompt: "Deploy to production",
options: {
agents: {
"deployer": {
description: "Handle deployments",
prompt: "Deploy the application",
tools: ["Bash"]
}
},
hooks: {
Stop: async (input) => {
// Manual cleanup of spawned processes
console.log("Parent stopped - cleaning up subagents");
// Implement process tracking and termination
}
}
}
});
改善の追跡:Issue #142 では自動終了が提案されています。
セッション管理
オプション:
resume: sessionId- 前のセッションを続行するforkSession: true- セッションから新しいブランチを作成するcontinue: prompt- 新しいプロンプトで再開する(resumeとは異なります)
セッションフォークのパターン(独自の機能):
// Explore alternative without modifying original
const forked = query({
prompt: "Try GraphQL instead of REST",
options: {
resume: sessionId,
forkSession: true // Creates new branch, original session unchanged
}
});
セッション ID の取得:
for await (const message of response) {
if (message.type === 'system' && message.subtype === 'init') {
sessionId = message.session_id; // Save for later resume/fork
}
}
V2 セッション API(プレビュー - v0.1.54+)
複数ターンの会話を簡潔に実装するパターン:
import {
unstable_v2_createSession,
unstable_v2_resumeSession,
unstable_v2_prompt
} from "@anthropic-ai/claude-agent-sdk";
// Create a new session
const session = await unstable_v2_createSession({
model: "claude-sonnet-4-5",
workingDirectory: process.cwd(),
allowedTools: ["Read", "Grep", "Glob"]
});
// Send prompts and stream responses
const stream = unstable_v2_prompt(session, "Analyze the codebase structure");
for await (const message of stream) {
console.log(message);
}
// Continue conversation in same session
const stream2 = unstable_v2_prompt(session, "Now suggest improvements");
for await (const message of stream2) {
console.log(message);
}
// Resume a previous session
const resumedSession = await unstable_v2_resumeSession(session.sessionId);
注: V2 API はプレビュー段階です(unstable_ プレフィックス)。.receive() メソッドは v0.1.72 で .stream() に改名されました。
権限制御
権限モード:
type PermissionMode = "default" | "acceptEdits" | "bypassPermissions" | "plan";
default- 標準の権限チェックacceptEdits- ファイル編集を自動承認するbypassPermissions- すべてのチェックをスキップする(CI/CD でのみ使用)plan- 計画モード(v0.1.45+)
カスタム権限ロジック
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" };
}
サンドボックス設定(セキュリティ上重要)
Bash コマンドのサンドボックス実行を有効にします。
const response = query({
prompt: "Run system diagnostics",
options: {
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true, // Auto-approve bash in sandbox
excludedCommands: ["rm", "dd", "mkfs"], // Never auto-approve these
allowUnsandboxedCommands: false // Deny unsandboxable commands
}
}
});
SandboxSettings 型
type SandboxSettings = {
enabled: boolean;
autoAllowBashIfSandboxed?: boolean; // Default: false
excludedCommands?: string[];
allowUnsandboxedCommands?: boolean; // Default: false
network?: NetworkSandboxSettings;
ignoreViolations?: SandboxIgnoreViolations;
};
type NetworkSandboxSettings = {
enabled: boolean;
proxyUrl?: string; // HTTP proxy for network requests
};
主なオプション:
enabled- サンドボックスによる分離を有効にしますautoAllowBashIfSandboxed- 安全な bash コマンドの権限確認プロンプトをスキップしますexcludedCommands- 常に権限が必要なコマンドallowUnsandboxedCommands- サンドボックス化できないコマンドを許可します(リスクがあります)network.proxyUrl- 監視のためにネットワーク通信をプロキシ経由にします
ベストプラクティス: 信頼できない入力を扱う本番環境のエージェントでは、必ずサンドボックスを使用してください。
ファイルのチェックポイント
ロールバック機能のためにファイル状態のスナップショットを有効にします:
const response = query({
prompt: "Refactor the authentication module",
options: {
enableFileCheckpointing: true // Enable file snapshots
}
});
// Later: rewind file changes to a specific point
for await (const message of response) {
if (message.type === 'user' && message.uuid) {
// Can rewind to this point later
const userMessageUuid = message.uuid;
// To rewind (call on Query object)
await response.rewindFiles(userMessageUuid);
}
}
ユースケース:
- 失敗したリファクタリングの試行を元に戻す
- コード変更の A/B テスト
- 代替案を安全に検討する
ファイルシステム設定
設定ソース:
type SettingSource = 'user' | 'project' | 'local';
user-~/.claude/settings.json(グローバル)project-.claude/settings.json(チームで共有)local-.claude/settings.local.json(Git で無視される上書き設定)
デフォルト: 設定は読み込まれません(settingSources: [])
設定の優先順位
複数のソースを読み込む場合、設定は次の順序でマージされます(優先度の高いものから順に記載):
- プログラムによるオプション(
query()に渡されます) - 常に優先されます - ローカル設定(
.claude/settings.local.json) - プロジェクト設定(
.claude/settings.json) - ユーザー設定(
~/.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 では settingSources: ["project"] を使用してください。
Query オブジェクトのメソッド
query() 関数は、次のメソッドを持つ Query オブジェクトを返します:
const q = query({ prompt: "..." });
// Async iteration (primary usage)
for await (const message of q) { ... }
// Runtime model control
await q.setModel("claude-opus-4-5"); // Change model mid-session
await q.setMaxThinkingTokens(4096); // Set thinking budget
// Introspection
const models = await q.supportedModels(); // List available models
const commands = await q.supportedCommands(); // List available commands
const account = await q.accountInfo(); // Get account details
// MCP status
const status = await q.mcpServerStatus(); // Check MCP server status
// Returns: { [serverName]: { status: 'connected' | 'failed', error?: string } }
// File operations (requires enableFileCheckpointing)
await q.rewindFiles(userMessageUuid); // Rewind to checkpoint
ユースケース:
- タスクの複雑さに基づくモデルの動的な切り替え
- MCP サーバーの健全性の監視
- 推論タスクに応じた思考予算の調整
メッセージの種類とストリーミング
メッセージの種類:
system- セッションの初期化/完了(session_idを含みます)assistant- エージェントの応答tool_call- ツールの実行リクエストtool_result- ツールの実行結果error- エラーメッセージresult- 最終結果(v0.1.45+ ではstructured_outputを含みます)
ストリーミングのパターン:
for await (const message of response) {
if (message.type === 'system' && message.subtype === 'init') {
sessionId = message.session_id; // Capture for resume/fork
}
if (message.type === 'result' && message.structured_output) {
// Structured output available (v0.1.45+)
const validated = schema.parse(message.structured_output);
}
}
エラー処理
エラーコード:
| エラーコード | 原因 | 解決策 |
|---|---|---|
CLI_NOT_FOUND | Claude Code がインストールされていません | インストールします:npm install -g @anthropic-ai/claude-code |
AUTHENTICATION_FAILED | API キーが無効です | ANTHROPIC_API_KEY 環境変数を確認します |
RATE_LIMIT_EXCEEDED | リクエストが多すぎます | バックオフを伴うリトライを実装します |
CONTEXT_LENGTH_EXCEEDED | プロンプトが長すぎます | セッションの圧縮を使用し、コンテキストを減らします |
PERMISSION_DENIED | ツールがブロックされています | permissionMode と canUseTool を確認します |
TOOL_EXECUTION_FAILED | ツールエラーです | ツールの実装を確認します |
SESSION_NOT_FOUND | セッション ID が無効です | セッション ID を確認します |
MCP_SERVER_FAILED | サーバーエラーです | サーバー設定を確認します |
既知の問題の予防
このスキルは、文書化されている 14 件の問題を予防します:
問題 #1:CLI が見つからないエラー
エラー:「Claude Code CLI がインストールされていません」
原因:SDK には Claude Code CLI が必要です
発生理由:CLI がグローバルにインストールされていません
予防策:SDK を使用する前にインストールします:npm install -g @anthropic-ai/claude-code
問題 #2:認証失敗
エラー:「API キーが無効です」
原因:ANTHROPIC_API_KEY が設定されていないか、正しくありません
発生理由:環境変数が設定されていません
予防策:必ず export ANTHROPIC_API_KEY="sk-ant-..." を設定します
問題 #3:権限拒否エラー
エラー:ツールの実行がブロックされました
原因:permissionMode の制限
発生理由:権限によってツールが許可されていません
予防策:allowedTools またはカスタムの canUseTool コールバックを使用します
Issue #4: コンテキスト長の上限超過(セッションが使用不能になる)
エラー: "Prompt too long"
原因: 入力がモデルのコンテキストウィンドウを超えています(Issue #138)
発生する理由: 大規模なコードベース、長い会話
⚠️ 重大な動作: セッションがコンテキスト上限に達すると:
- そのセッションへの以降のリクエストはすべて「Prompt too long」を返します
/compactコマンドも同じエラーで失敗します- セッションは恒久的に使用不能となり、破棄する必要があります
予防策:
// 1. Proactive session forking (create checkpoints before hitting limit)
const checkpoint = query({
prompt: "Checkpoint current state",
options: {
resume: sessionId,
forkSession: true // Create branch before hitting limit
}
});
// 2. Monitor time and rotate sessions proactively
const MAX_SESSION_TIME = 80 * 60 * 1000; // 80 minutes (before 90-min crash)
let sessionStartTime = Date.now();
function shouldRotateSession() {
return Date.now() - sessionStartTime > MAX_SESSION_TIME;
}
// 3. Start new sessions before hitting context limits
if (shouldRotateSession()) {
const summary = await getSummary(currentSession);
const newSession = query({
prompt: `Continue with context: ${summary}`
});
sessionStartTime = Date.now();
}
注: SDK は自動でコンパクト化しますが、上限に達するとセッションは復旧不能になります
Issue #5: ツール実行のタイムアウト
エラー: ツールが応答しません 原因: 長時間にわたるツール実行 発生する理由: ツールの実行に時間がかかりすぎています(デフォルトでは 5 分超) 予防策: ツールの実装でタイムアウト処理を行います
Issue #6: セッションが見つからない
エラー: "Invalid session ID"
原因: セッションの有効期限切れ、または無効
発生する理由: セッション ID が正しくないか、古すぎます
予防策: system の初期化メッセージから session_id を取得します
Issue #7: MCP サーバーへの接続失敗
エラー: サーバーが応答しません 原因: サーバーが実行されていないか、設定に誤りがあります 発生する理由: コマンドまたは URL が正しくない、サーバーがクラッシュした 予防策: MCP サーバーを個別にテストし、コマンドまたは URL を確認します
Issue #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 を設定し、ファイルのアクセス許可を確認します
Issue #13: MCP サーバー設定に type フィールドがありません
エラー: "Claude Code process exited with code 1"(不明瞭で、原因の説明がありません)
原因: GitHub Issue #131
発生する理由: URL ベースの MCP サーバーには、type: "http" または type: "sse" フィールドを明示的に指定する必要があります
予防策: URL ベースの MCP サーバーでは、必ずトランスポートの種類を指定します
// ❌ Wrong - missing type field (causes cryptic exit code 1)
mcpServers: {
"my-server": {
url: "https://api.example.com/mcp"
}
}
// ✅ Correct - type field required for URL-based servers
mcpServers: {
"my-server": {
url: "https://api.example.com/mcp",
type: "http" // or "sse" for Server-Sent Events
}
}
診断の手がかり: 他に情報がないまま「process exited with code 1」と表示された場合は、MCP サーバーの設定に type フィールドがないか確認してください。
Issue #14: Unicode の行区切り文字を含む MCP ツールの結果
エラー: JSON の解析エラー、エージェントが応答しなくなります 原因: GitHub Issue #137 発生する理由: Unicode U+2028(行区切り文字)と U+2029(段落区切り文字)は JSON では有効ですが、JavaScript の解析を妨げます 予防策: MCP ツールの結果内でこれらの文字をエスケープします
// MCP tool handler - sanitize external data
tool("fetch_content", "Fetch text content", {}, async (args) => {
const content = await fetchExternalData();
// ✅ Sanitize Unicode line/paragraph separators
const sanitized = content
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
return {
content: [{ type: "text", text: sanitized }]
};
});
該当するケース: これらの文字が含まれる可能性のある外部データソース(API、ウェブスクレイピング、ユーザー入力)
関連情報: MCP Python SDK Issue #1356
公式ドキュメント
- Agent SDK 概要: https://platform.claude.com/docs/en/api/agent-sdk/overview
- TypeScript API: https://platform.claude.com/docs/en/api/agent-sdk/typescript
- 構造化出力: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
- GitHub(TypeScript): https://github.com/anthropics/claude-agent-sdk-typescript
- 変更履歴: https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md
トークン効率:
- スキルなし:~15,000 トークン(MCP のセットアップ、権限パターン、セッション API、サンドボックス設定、フック、構造化出力、エラー処理)
- スキルあり:~4,500 トークン(v0.2.12 の包括的なカバー範囲 + エラー防止 + 高度なパターン)
- 削減率:~70%(~10,500 トークン)
防止できるエラー:正確な解決策を含む、文書化された 14 件の問題(コミュニティから寄せられた注意点 2 件を含む) 主な価値:V2 Session API、Sandbox Settings、File Checkpointing、Query メソッド、AskUserQuestion ツール、構造化出力(v0.1.45+)、セッションのフォーク、canUseTool パターン、完全なフックシステム(12 イベント)、Zod v4 のサポート、サブエージェントのクリーンアップパターン
最終確認日:2026-01-20 | スキルバージョン:3.1.0 | 変更点:Issue #13(MCP type フィールド)と Issue #14(Unicode U+2028/U+2029)を追加、Issue #4(セッションを中断させる問題)を拡充、Stop フックパターンを使ったサブエージェントのクリーンアップに関する警告を追加