概要

本章では、Claude Agent SDKにおける拡張機能とMCP(Model Context Protocol)連携について解説します。 スラッシュコマンド、スキル、プラグインでエージェントを拡張し、MCPで外部ツールと連携できます。

主要な機能を以下に示します。

機能 説明
スラッシュコマンド /で始まる特殊コマンドでセッションを制御
スキル Claudeが自律的に呼び出す専門機能
プラグイン コマンド、エージェント、スキルをパッケージ化
MCP連携 外部ツールやデータソースとの接続
コスト追跡 トークン使用量と課金の追跡
Todoリスト タスク進捗の構造化された管理

スラッシュコマンド

スラッシュコマンドは、/で始まる特殊コマンドでClaude Codeセッションを制御する機能です。

利用可能なコマンドの確認

システム初期化メッセージから利用可能なスラッシュコマンドを取得できます。

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

for await (const message of query({
  prompt: "Hello Claude",
  options: { maxTurns: 1 }
})) {
  if (message.type === "system" && message.subtype === "init") {
    console.log("Available slash commands:", message.slash_commands);
    // 出力例: ["/compact", "/clear", "/help"]
  }
}

このコードはセッション開始時に利用可能なスラッシュコマンドを取得しています。

組み込みコマンド

主要な組み込みコマンドを以下に示します。

コマンド 説明
/compact 会話履歴を要約して圧縮
/clear 会話をクリアして新規セッション開始
/help ヘルプ情報を表示

コマンドの送信例を示します。

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

// /compactコマンドを送信
for await (const message of query({
  prompt: "/compact",
  options: { maxTurns: 1 }
})) {
  if (message.type === "system" && message.subtype === "compact_boundary") {
    console.log("Compaction completed");
    console.log("Pre-compaction tokens:", message.compact_metadata.pre_tokens);
    console.log("Trigger:", message.compact_metadata.trigger);
  }
}

このコードは/compactコマンドを実行し、圧縮結果のメタデータを取得しています。

カスタムコマンドの作成

カスタムスラッシュコマンドはMarkdownファイルとして定義します。

ファイルの配置場所を以下に示します。

スコープ ディレクトリ
プロジェクト .claude/commands/
ユーザー ~/.claude/commands/

基本的なコマンドファイルの例を示します。

.claude/commands/refactor.md
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.

このファイルを作成すると/refactorコマンドが利用可能になります。

フロントマター付きのコマンドファイルを示します。

.claude/commands/security-check.md
---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
model: claude-sonnet-4-5-20250929
---

Analyze the codebase for security vulnerabilities including:
- SQL injection risks
- XSS vulnerabilities
- Exposed credentials
- Insecure configurations

フロントマターで許可するツール、説明、使用するモデルを指定できます。

引数とプレースホルダー

カスタムコマンドは引数をサポートします。

.claude/commands/fix-issue.md
---
argument-hint: [issue-number] [priority]
description: Fix a GitHub issue
---

Fix issue #$1 with priority $2.
Check the issue description and implement the necessary changes.

SDKからの呼び出し例を示します。

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

// 引数付きでカスタムコマンドを呼び出し
for await (const message of query({
  prompt: "/fix-issue 123 high",
  options: { maxTurns: 5 }
})) {
  // コマンドは$1="123"、$2="high"として処理される
  if (message.type === "result") {
    console.log("Issue fixed:", message.result);
  }
}

このコードは引数をプレースホルダーに渡してコマンドを実行しています。

Bashコマンドの実行

カスタムコマンドはBashコマンドの出力を含めることができます。

.claude/commands/code-review.md
---
allowed-tools: Read, Grep, Glob, Bash(git diff:*)
description: Comprehensive code review
---

## Changed Files
!`git diff --name-only HEAD~1`

## Detailed Changes
!`git diff HEAD~1`

## Review Checklist

Review the above changes for:
1. Code quality and readability
2. Security vulnerabilities
3. Performance implications
4. Test coverage
5. Documentation completeness

Provide specific, actionable feedback organized by priority.

!バッククォートでBashコマンドの出力をコマンドに埋め込めます。

ファイル参照

@プレフィックスでファイル内容を参照できます。

.claude/commands/review-config.md
---
description: Review configuration files
---

Review the following configuration files for issues:
- Package config: @package.json
- TypeScript config: @tsconfig.json
- Environment config: @.env

Check for security issues, outdated dependencies, and misconfigurations.

@ファイル名でファイルの内容がコマンドに展開されます。

名前空間による整理

サブディレクトリでコマンドを整理できます。

text
.claude/commands/
├── frontend/
│   ├── component.md      # /component (project:frontend)
│   └── style-check.md    # /style-check (project:frontend)
├── backend/
│   ├── api-test.md       # /api-test (project:backend)
│   └── db-migrate.md     # /db-migrate (project:backend)
└── review.md             # /review (project)

サブディレクトリ名はコマンドの説明に表示されますが、コマンド名自体には影響しません。

スキル

スキル(Agent Skills)は、Claudeが自律的に呼び出す専門機能です。

SDKでのスキルの仕組み

スキルは以下の特徴を持ちます。

特徴 説明
ファイルシステムベース .claude/skills/ディレクトリにSKILL.mdとして定義
自動検出 起動時にメタデータが検出され、必要に応じて全文がロード
モデル呼び出し Claudeがコンテキストに基づいて自律的に使用を判断
明示的な有効化 allowed_toolsに"Skill"を追加する必要あり

デフォルトではSDKはファイルシステム設定をロードしません。 スキルを使用するにはsetting_sourcesを明示的に設定する必要があります。

スキルの使用

スキルを使用するには、setting_sourcesとallowed_toolsを設定します。

use_skills.py
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        cwd="/path/to/project",  # .claude/skills/を含むプロジェクト
        setting_sources=["user", "project"],  # ファイルシステムからスキルをロード
        allowed_tools=["Skill", "Read", "Write", "Bash"]  # Skillツールを有効化
    )

    async for message in query(
        prompt="Help me process this PDF document",
        options=options
    ):
        print(message)

asyncio.run(main())

このコードはスキルを有効化してクエリを実行しています。 setting_sourcesで"user"と"project"を指定し、両方のディレクトリからスキルをロードします。

スキルの配置場所

スキルは以下のディレクトリに配置します。

スコープ ディレクトリ 説明
プロジェクト .claude/skills/ gitでチーム共有可能
ユーザー ~/.claude/skills/ すべてのプロジェクトで利用可能
プラグイン プラグインにバンドル インストール済みプラグインに含まれる

スキルの作成

スキルはSKILL.mdファイルとして定義します。

text
.claude/skills/processing-pdfs/
└── SKILL.md

SKILL.mdの構造を示します。

SKILL.md
---
description: PDFファイルを処理して内容を抽出するスキル
---

# PDF Processing Skill

PDFファイルからテキストを抽出し、構造化されたデータとして返します。

## 使用方法

1. PDFファイルのパスを指定
2. 抽出したい情報の種類を指定
3. 結果を整形して返却

descriptionフィールドがClaudeがスキルを使用するタイミングを決定します。

ツール制限

SKILL.mdのallowed-toolsフロントマターフィールドはCLI直接使用時のみ有効です。 SDKではメインのallowedToolsオプションでツールアクセスを制御します。

skill_tools.py
options = ClaudeAgentOptions(
    setting_sources=["user", "project"],  # スキルをロード
    allowed_tools=["Skill", "Read", "Grep", "Glob"]  # 制限されたツールセット
)

async for message in query(
    prompt="Analyze the codebase structure",
    options=options
):
    print(message)

このコードは読み取り専用ツールのみを許可しています。

利用可能なスキルの確認

Claudeに直接尋ねることでスキルを確認できます。

discover_skills.py
options = ClaudeAgentOptions(
    setting_sources=["user", "project"],
    allowed_tools=["Skill"]
)

async for message in query(
    prompt="What Skills are available?",
    options=options
):
    print(message)

このコードは利用可能なスキルの一覧を取得しています。

プラグイン

プラグインは、コマンド、エージェント、スキル、フックをパッケージ化して共有可能にする仕組みです。

プラグインの構成要素

プラグインには以下の要素を含められます。

要素 説明
コマンド カスタムスラッシュコマンド
エージェント 特定タスク向けサブエージェント
スキル Claudeが自律的に呼び出す機能
フック イベントハンドラ
MCPサーバー 外部ツール連携

プラグインのロード

プラグインはローカルファイルシステムパスを指定してロードします。

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

for await (const message of query({
  prompt: "Hello",
  options: {
    plugins: [
      { type: "local", path: "./my-plugin" },
      { type: "local", path: "/absolute/path/to/another-plugin" }
    ]
  }
})) {
  // プラグインのコマンド、エージェント、その他の機能が利用可能
}

このコードは2つのプラグインをロードしています。 パスはプラグインのルートディレクトリ(.claude-plugin/plugin.jsonを含むディレクトリ)を指定します。

プラグインのインストール確認

プラグインが正常にロードされたか確認します。

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

for await (const message of query({
  prompt: "Hello",
  options: {
    plugins: [{ type: "local", path: "./my-plugin" }]
  }
})) {
  if (message.type === "system" && message.subtype === "init") {
    // ロードされたプラグインを確認
    console.log("Plugins:", message.plugins);
    // 出力例: [{ name: "my-plugin", path: "./my-plugin" }]

    // プラグインからのコマンドを確認
    console.log("Commands:", message.slash_commands);
    // 出力例: ["/help", "/compact", "my-plugin:custom-command"]
  }
}

このコードはプラグインのロード状態と利用可能なコマンドを確認しています。

プラグインコマンドの使用

プラグインのコマンドはプラグイン名:コマンド名の形式で名前空間化されます。

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

// プラグインの/greetコマンドを使用
for await (const message of query({
  prompt: "/my-plugin:greet",  // 名前空間付きでコマンドを使用
  options: {
    plugins: [{ type: "local", path: "./my-plugin" }]
  }
})) {
  if (message.type === "assistant") {
    console.log(message.content);
  }
}

このコードはプラグインのカスタムコマンドを呼び出しています。

プラグインのディレクトリ構造

プラグインの標準的なディレクトリ構造を示します。

text
my-plugin/
├── .claude-plugin/
│   └── plugin.json          # 必須: プラグインマニフェスト
├── commands/                 # カスタムスラッシュコマンド
│   └── custom-cmd.md
├── agents/                   # カスタムエージェント
│   └── specialist.md
├── skills/                   # スキル
│   └── my-skill/
│       └── SKILL.md
├── hooks/                    # イベントハンドラ
│   └── hooks.json
└── .mcp.json                # MCPサーバー定義

.claude-plugin/plugin.jsonがプラグインのマニフェストファイルで必須です。

一般的なユースケース

プラグインの活用パターンを以下に示します。

ユースケース 設定
開発とテスト グローバルインストールせずにプラグインをロード
プロジェクト固有 プロジェクトリポジトリにプラグインを含めてチーム共有
複数ソース 異なる場所からのプラグインを組み合わせ

複数プラグインの組み合わせ例を示します。

multiple_plugins.ts
const options = {
  plugins: [
    { type: "local", path: "./local-plugin" },
    { type: "local", path: "~/.claude/custom-plugins/shared-plugin" }
  ]
};

このコードはローカルプラグインと共有プラグインを組み合わせています。

完全な例

プラグインのロードと使用を示す完全な例を示します。

run_with_plugin.ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import * as path from "path";

async function runWithPlugin() {
  const pluginPath = path.join(__dirname, "plugins", "my-plugin");

  console.log("Loading plugin from:", pluginPath);

  for await (const message of query({
    prompt: "What custom commands do you have available?",
    options: {
      plugins: [
        { type: "local", path: pluginPath }
      ],
      maxTurns: 3
    }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      console.log("Loaded plugins:", message.plugins);
      console.log("Available commands:", message.slash_commands);
    }

    if (message.type === "assistant") {
      console.log("Assistant:", message.content);
    }
  }
}

runWithPlugin().catch(console.error);

このコードは以下の処理を行います。

  1. path.joinでプラグインパスを構築
  2. プラグインをロードしてクエリを実行
  3. 初期化メッセージでロードされたプラグインとコマンドを確認
  4. アシスタントの応答を出力

CLIでインストールしたプラグイン(例: /plugin install my-plugin@marketplace)もSDKで使用できます。 ~/.claude/plugins/でCLIインストール済みプラグインを確認できます。

MCP連携

MCP(Model Context Protocol)は、AIエージェントを外部ツールやデータソースに接続するオープン標準です。

クイックスタート

HTTP経由でMCPサーバーに接続する例を示します。

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

for await (const message of query({
  prompt: "Use the docs MCP server to explain what hooks are in Claude Code",
  options: {
    mcpServers: {
      "claude-code-docs": {
        type: "http",
        url: "https://code.claude.com/docs/mcp"
      }
    },
    allowedTools: ["mcp__claude-code-docs__*"]
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

このコードはClaude Codeドキュメントサーバーに接続し、hooksについての情報を取得しています。

MCPサーバーの追加

MCPサーバーはコード内または設定ファイルで構成できます。

コード内での設定を示します。

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

for await (const message of query({
  prompt: "List files in my project",
  options: {
    mcpServers: {
      "filesystem": {
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
      }
    },
    allowedTools: ["mcp__filesystem__*"]
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

このコードはファイルシステムMCPサーバーを使用してプロジェクトファイルを一覧しています。

設定ファイルでの構成例を示します。

.mcp.json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
    }
  }
}

.mcp.jsonをプロジェクトルートに配置するとSDKが自動的にロードします。

MCPツールの許可

MCPツールは明示的な許可が必要です。

ツールの命名規則を示します。

text
mcp__<サーバー名>__<ツール名>

例えば、githubサーバーのlist_issuesツールはmcp__github__list_issuesになります。

allowedToolsでの許可設定を示します。

mcp_allowed_tools.ts
options: {
  mcpServers: { /* サーバー設定 */ },
  allowedTools: [
    "mcp__github__*",              // githubサーバーのすべてのツール
    "mcp__db__query",              // dbサーバーのqueryツールのみ
    "mcp__slack__send_message"     // slackサーバーのsend_messageのみ
  ]
}

ワイルドカード(*)でサーバーのすべてのツールを許可できます。

permissionModeによる許可

allowedToolsを個別に指定する代わりに、permissionModeで広範なアクセスを許可できます。

モード 説明
acceptEdits ツール使用を自動承認(破壊的操作はプロンプト表示)
bypassPermissions すべての安全プロンプトをスキップ(本番環境では注意)
permission_mode.ts
options: {
  mcpServers: { /* サーバー設定 */ },
  permissionMode: "acceptEdits"  // allowedToolsは不要
}

bypassPermissionsはファイル削除やシェルコマンド実行などの破壊的操作も含めてすべてスキップします。 このモードはTaskツールで生成されたサブエージェントにも伝播します。

トランスポートタイプ

MCPサーバーは異なるトランスポートプロトコルで通信します。

タイプ 説明 使用場面
stdio stdin/stdout経由のローカルプロセス ローカルで実行するMCPサーバー
HTTP HTTPリクエスト クラウドホストのMCPサーバー
SSE Server-Sent Events リアルタイム通信が必要な場合
SDK MCP アプリケーション内で定義 カスタムツールを直接実装

MCPツール検索

多数のMCPツールを構成している場合、ツール定義がコンテキストウィンドウを圧迫します。 ツール検索機能は必要に応じてツールを動的にロードします。

動作の仕組みを以下に示します。

  1. MCPツールにdefer_loading: trueが設定される(事前ロードしない)
  2. Claudeが必要に応じて検索ツールを使用してMCPツールを発見
  3. 実際に必要なツールのみがコンテキストにロードされる

ツール検索はデフォルトでautoモードです。 MCPツール定義がコンテキストウィンドウの10%を超えると自動的に有効化されます。

ツール検索はtool_referenceブロックをサポートするモデルが必要です。 Sonnet 4以降、Opus 4以降で利用可能です。 Haikuモデルはツール検索をサポートしていません。

設定方法を示します。

tool_search_config.ts
const options = {
  mcpServers: { /* MCPサーバー設定 */ },
  env: {
    ENABLE_TOOL_SEARCH: "auto:5"  // 5%のしきい値で有効化
  }
};

設定値を以下に示します。

値 動作
auto MCPツールがコンテキストの10%を超えると有効化(デフォルト)
auto:5 5%のしきい値で有効化(パーセンテージをカスタマイズ)
true 常に有効
false 無効、すべてのMCPツールを事前ロード

認証

ほとんどのMCPサーバーは外部サービスへのアクセスに認証が必要です。

環境変数での認証情報渡しを示します。

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

for await (const message of query({
  prompt: "List the 3 most recent issues in anthropics/claude-code",
  options: {
    mcpServers: {
      "github": {
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-github"],
        env: {
          GITHUB_TOKEN: process.env.GITHUB_TOKEN
        }
      }
    },
    allowedTools: ["mcp__github__list_issues"]
  }
})) {
  // MCP接続を確認
  if (message.type === "system" && message.subtype === "init") {
    console.log("MCP servers:", message.mcp_servers);
  }

  // MCPツール呼び出しをログ
  if (message.type === "assistant") {
    for (const block of message.content) {
      if (block.type === "tool_use" && block.name.startsWith("mcp__")) {
        console.log("MCP tool called:", block.name);
      }
    }
  }

  // 最終結果を出力
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

このコードはGitHub MCPサーバーに認証情報を渡してissueを取得しています。

HTTPサーバーへのヘッダー認証を示します。

mcp_http_auth.ts
// OAuthフロー完了後
const accessToken = await getAccessTokenFromOAuthFlow();

const options = {
  mcpServers: {
    "oauth-api": {
      type: "http",
      url: "https://api.example.com/mcp",
      headers: {
        Authorization: `Bearer ${accessToken}`
      }
    }
  },
  allowedTools: ["mcp__oauth-api__*"]
};

このコードはOAuth2トークンをHTTPヘッダーで渡しています。

エラーハンドリング

MCPサーバーの接続状態を確認します。

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

for await (const message of query({
  prompt: "Process data",
  options: {
    mcpServers: {
      "data-processor": dataServer
    }
  }
})) {
  if (message.type === "system" && message.subtype === "init") {
    const failedServers = message.mcp_servers.filter(
      s => s.status !== "connected"
    );

    if (failedServers.length > 0) {
      console.warn("Failed to connect:", failedServers);
    }
  }

  if (message.type === "result" && message.subtype === "error_during_execution") {
    console.error("Execution failed");
  }
}

このコードは接続失敗したサーバーを検出し、実行エラーを処理しています。

コスト追跡

Claude Agent SDKは各インタラクションの詳細なトークン使用量情報を提供します。

主要概念

コスト追跡の主要概念を以下に示します。

概念 説明
ステップ アプリケーションとClaude間の1回のリクエスト/レスポンスペア
メッセージ ステップ内の個別メッセージ(テキスト、ツール使用、ツール結果)
使用量 アシスタントメッセージに付随するトークン消費データ

使用量の追跡

使用量を追跡するコスト追跡クラスを示します。

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

class CostTracker {
  private processedMessageIds = new Set<string>();
  private stepUsages: Array<any> = [];

  async trackConversation(prompt: string) {
    const result = await query({
      prompt,
      options: {
        onMessage: (message) => {
          this.processMessage(message);
        }
      }
    });

    return {
      result,
      stepUsages: this.stepUsages,
      totalCost: result.usage?.total_cost_usd || 0
    };
  }

  private processMessage(message: any) {
    // アシスタントメッセージで使用量がある場合のみ処理
    if (message.type !== 'assistant' || !message.usage) {
      return;
    }

    // 既に処理済みのメッセージIDはスキップ
    if (this.processedMessageIds.has(message.id)) {
      return;
    }

    // 処理済みとしてマークし、使用量を記録
    this.processedMessageIds.add(message.id);
    this.stepUsages.push({
      messageId: message.id,
      timestamp: new Date().toISOString(),
      usage: message.usage,
      costUSD: this.calculateCost(message.usage)
    });
  }

  private calculateCost(usage: any): number {
    // 簡易的なコスト計算例
    const inputCost = usage.input_tokens * 0.00003;
    const outputCost = usage.output_tokens * 0.00015;
    const cacheReadCost = (usage.cache_read_input_tokens || 0) * 0.0000075;

    return inputCost + outputCost + cacheReadCost;
  }
}

// 使用例
const tracker = new CostTracker();
const { result, stepUsages, totalCost } = await tracker.trackConversation(
  "Analyze and refactor this code"
);

console.log(`Steps processed: ${stepUsages.length}`);
console.log(`Total cost: $${totalCost.toFixed(4)}`);

このコードはメッセージIDで重複を排除しながらステップごとの使用量を追跡しています。

重要なルール

コスト追跡の重要なルールを以下に示します。

ルール 説明
同一ID = 同一使用量 同じIDのメッセージはすべて同じ使用量を報告
ステップごとに1回課金 同じIDの複数メッセージでも1回のみ課金
累積使用量 最終結果メッセージに全ステップの累積使用量が含まれる

モデル別使用量

結果メッセージにはmodelUsageフィールドでモデル別の使用量データが含まれます。

model_usage.ts
// modelUsageはモデル名からModelUsageへのマップ
for (const [modelName, usage] of Object.entries(result.modelUsage)) {
  console.log(`${modelName}: $${usage.costUSD.toFixed(4)}`);
  console.log(`  Input tokens: ${usage.inputTokens}`);
  console.log(`  Output tokens: ${usage.outputTokens}`);
}

このコードはモデルごとのコストとトークン数を表示しています。 複数モデルを使用する場合(例えばサブエージェントにHaiku、メインにOpus)に有用です。

使用量フィールド

各使用量オブジェクトに含まれるフィールドを以下に示します。

フィールド 説明
input_tokens 処理された入力トークン数
output_tokens 生成された出力トークン数
cache_creation_input_tokens キャッシュエントリ作成に使用されたトークン数
cache_read_input_tokens キャッシュから読み込まれたトークン数
service_tier 使用されたサービスティア(例: "standard")
total_cost_usd 合計コスト(USD)(結果メッセージのみ)

エッジケースの処理

出力トークンの不一致が発生した場合の対処方法を示します。

同じIDのメッセージで異なるoutput_tokens値が観測される場合があります。 この場合は以下のように対処します。

  1. 最大値を使用する(グループ内の最終メッセージが正確な合計を含む)
  2. total_cost_usdと照合する(結果メッセージの値が権威的)
  3. 不整合を報告する(Claude Code GitHubリポジトリにissueを作成)

キャッシュトークンの追跡では、以下のトークン種類を別々に追跡します。

cache_usage.ts
interface CacheUsage {
  cache_creation_input_tokens: number;
  cache_read_input_tokens: number;
  cache_creation: {
    ephemeral_5m_input_tokens: number;
    ephemeral_1h_input_tokens: number;
  };
}

このインターフェースは5分と1時間のエフェメラルキャッシュトークンを区別しています。

ベストプラクティス

コスト追跡のベストプラクティスを以下に示します。

プラクティス 説明
メッセージIDで重複排除 処理済みメッセージIDを追跡して二重課金を防止
結果メッセージを監視 最終結果に権威的な累積使用量が含まれる
ロギングを実装 監査とデバッグのためにすべての使用量データをログ
失敗を適切に処理 会話が失敗しても部分的な使用量を追跡
ストリーミングを考慮 ストリーミングレスポンスでは到着時に使用量を累積

課金ダッシュボードの構築

ユーザーごとの使用量を集計する課金アグリゲータの例を示します。

billing_aggregator.ts
class BillingAggregator {
  private userUsage = new Map<string, {
    totalTokens: number;
    totalCost: number;
    conversations: number;
  }>();

  async processUserRequest(userId: string, prompt: string) {
    const tracker = new CostTracker();
    const { result, stepUsages, totalCost } = await tracker.trackConversation(prompt);

    // ユーザーの合計を更新
    const current = this.userUsage.get(userId) || {
      totalTokens: 0,
      totalCost: 0,
      conversations: 0
    };

    const totalTokens = stepUsages.reduce((sum, step) =>
      sum + step.usage.input_tokens + step.usage.output_tokens, 0
    );

    this.userUsage.set(userId, {
      totalTokens: current.totalTokens + totalTokens,
      totalCost: current.totalCost + totalCost,
      conversations: current.conversations + 1
    });

    return result;
  }

  getUserBilling(userId: string) {
    return this.userUsage.get(userId) || {
      totalTokens: 0,
      totalCost: 0,
      conversations: 0
    };
  }
}

このコードはユーザーごとの総トークン数、総コスト、会話数を追跡しています。 CostTrackerクラスと組み合わせて課金システムを構築できます。

Todoリスト

Todoリストは、タスク進捗を構造化して管理し、ユーザーに表示する機能です。

Todoのライフサイクル

Todoは以下のライフサイクルに従います。

状態 説明
pending タスク特定時に作成
in_progress 作業開始時にアクティブ化
completed タスク成功時に完了
削除 グループ内の全タスク完了時

Todoが使用される場面

SDKは以下の場合に自動的にTodoを作成します。

  • 3つ以上の異なるアクションを必要とする複雑なマルチステップタスク
  • ユーザーが複数の項目を言及したタスクリスト
  • 進捗追跡が有益な非自明な操作
  • ユーザーがTodo整理を明示的に要求した場合

Todoの監視

Todoの変更を監視する例を示します。

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

for await (const message of query({
  prompt: "Optimize my React app performance and track progress with todos",
  options: { maxTurns: 15 }
})) {
  // Todo更新はメッセージストリームに反映される
  if (message.type === "assistant") {
    for (const block of message.message.content) {
      if (block.type === "tool_use" && block.name === "TodoWrite") {
        const todos = block.input.todos;

        console.log("Todo Status Update:");
        todos.forEach((todo, index) => {
          const status = todo.status === "completed" ? "✓" :
                        todo.status === "in_progress" ? "▶" : "○";
          console.log(`${index + 1}. ${status} ${todo.content}`);
        });
      }
    }
  }
}

このコードはTodoWriteツールの呼び出しを検出し、進捗状況を表示しています。

リアルタイム進捗表示

より高度な進捗表示クラスを示します。

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

class TodoTracker {
  private todos: any[] = [];

  displayProgress() {
    if (this.todos.length === 0) return;

    const completed = this.todos.filter(t => t.status === "completed").length;
    const inProgress = this.todos.filter(t => t.status === "in_progress").length;
    const total = this.todos.length;

    console.log(`\nProgress: ${completed}/${total} completed`);
    console.log(`Currently working on: ${inProgress} task(s)\n`);

    this.todos.forEach((todo, index) => {
      const icon = todo.status === "completed" ? "✓" :
                  todo.status === "in_progress" ? "▶" : "○";
      const text = todo.status === "in_progress" ? todo.activeForm : todo.content;
      console.log(`${index + 1}. ${icon} ${text}`);
    });
  }

  async trackQuery(prompt: string) {
    for await (const message of query({
      prompt,
      options: { maxTurns: 20 }
    })) {
      if (message.type === "assistant") {
        for (const block of message.message.content) {
          if (block.type === "tool_use" && block.name === "TodoWrite") {
            this.todos = block.input.todos;
            this.displayProgress();
          }
        }
      }
    }
  }
}

// 使用例
const tracker = new TodoTracker();
await tracker.trackQuery("Build a complete authentication system with todos");

このコードはTodoの進捗をリアルタイムで追跡し、完了数、作業中タスク数、各タスクの状態を表示しています。

トラブルシューティング

よくある問題と解決策を示します。

スラッシュコマンド関連

問題 原因 解決策
カスタムコマンドが見つからない ファイルの配置場所が間違っている .claude/commands/または~/.claude/commands/に配置
引数が渡されない プレースホルダーの形式が間違っている $1、$2の形式を使用

スキル関連

問題 原因 解決策
スキルが見つからない setting_sourcesが未設定 setting_sources: ["user", "project"]を追加
スキルが使用されない allowed_toolsにSkillがない allowed_toolsに"Skill"を追加
descriptionが不明確 キーワードが不足 具体的で関連キーワードを含むdescriptionを記述

プラグイン関連

問題 原因 解決策
プラグインがロードされない パスが間違っている .claude-plugin/を含むルートディレクトリを指定
コマンドが動作しない 名前空間を使用していない プラグイン名:コマンド名の形式を使用
パスが解決されない 相対パスの基準が異なる 絶対パスを使用するか、pathユーティリティでパスを構築

MCP関連

問題 原因 解決策
サーバーが"failed"状態 認証情報が不足、サーバー未インストール 環境変数を確認、パッケージをインストール
ツールが呼び出されない allowedToolsに許可がない allowedToolsにMCPツールを追加
接続タイムアウト サーバーの起動に時間がかかる サーバーを事前ウォームアップ、軽量サーバーを使用

参考情報