> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK のスラッシュコマンド

> SDK を通じて Claude Code セッションを制御するスラッシュコマンドの使用方法を学びます

スラッシュコマンドは、`/` で始まる特別なコマンドを使用して Claude Code セッションを制御する方法を提供します。これらのコマンドは SDK を通じて送信でき、コンテキストのコンパクト化、コンテキスト使用状況の一覧表示、またはカスタムコマンドの呼び出しなどのアクションを実行できます。インタラクティブなターミナルなしで機能するコマンドのみが SDK を通じてディスパッチ可能です。`system/init` メッセージにはセッションで利用可能なコマンドが一覧表示されます。

<h2 id="discovering-available-slash-commands">
  利用可能なスラッシュコマンドの検出
</h2>

Claude Agent SDK は、システム初期化メッセージで利用可能なスラッシュコマンドに関する情報を提供します。セッション開始時にこの情報にアクセスします。

<CodeGroup>
  ```typescript TypeScript theme={null}
  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);
      // Includes built-in commands plus bundled skills, for example:
      // ["clear", "compact", "context", "usage", "code-review", "verify", ...]
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage


  async def main():
      async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):
          if isinstance(message, SystemMessage) and message.subtype == "init":
              print("Available slash commands:", message.data["slash_commands"])
              # Includes built-in commands plus bundled skills, for example:
              # ["clear", "compact", "context", "usage", "code-review", "verify", ...]


  asyncio.run(main())
  ```
</CodeGroup>

<h2 id="sending-slash-commands">
  スラッシュコマンドの送信
</h2>

スラッシュコマンドをプロンプト文字列に含めて送信します。通常のテキストと同じように使用します。会話履歴に作用するコマンド（`/compact` など）は、動作するために事前のメッセージが必要です。そのため、以下の例では最初に質問を送信してから、同じ会話へのフォローアップとしてコマンドを送信しています。

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Build up conversation history first
  try {
    for await (const message of query({
      prompt: "What does the README in this directory cover?",
      options: { maxTurns: 2 }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(message.result);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the follow-up query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Send a slash command as a follow-up to the same conversation
  for await (const message of query({
    prompt: "/compact",
    options: { continue: true, maxTurns: 1 }
  })) {
    if (message.type === "result") {
      console.log("Command executed, result subtype:", message.subtype);
      // Example output: Command executed, result subtype: success
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


  async def main():
      # Build up conversation history first
      try:
          async for message in query(
              prompt="What does the README in this directory cover?",
              options=ClaudeAgentOptions(max_turns=2),
          ):
              if isinstance(message, ResultMessage) and message.subtype == "success":
                  print(message.result)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the follow-up query below still runs.
          print(f"Session ended with an error: {error}")

      # Send a slash command as a follow-up to the same conversation
      async for message in query(
          prompt="/compact",
          options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
      ):
          if isinstance(message, ResultMessage):
              print("Command executed, result subtype:", message.subtype)
              # Example output: Command executed, result subtype: success


  asyncio.run(main())
  ```
</CodeGroup>

<Note>
  クエリはエラー結果で終了する場合があります。例えば、`maxTurns` / `max_turns` の制限に達してから作業が完了する前に終了する場合です。最終的な結果メッセージは `is_error: true` を持ち、`success` の代わりに `error_max_turns` などのエラーサブタイプを持ちます。

  その最終的な結果メッセージを生成した後、SDK はエラーを発生させます。これは CLI プロセスがゼロ以外のコードで終了するためです。

  コマンドが制限に達する可能性がある場合は、[Single Message Input](/ja/agent-sdk/streaming-vs-single-mode#single-message-input) に示されているように、TypeScript では `try`/`catch` でループをラップするか、Python では `try`/`except` でラップしてください。または、作業が完了するのに十分な高さに `maxTurns` を設定してください。Python では、`Exception` をキャッチしてください。SDK はエラー結果をプレーンな `Exception` として表示します。
</Note>

<h2 id="common-slash-commands">
  一般的なスラッシュコマンド
</h2>

<h3 id="/compact-compact-conversation-history">
  `/compact` - 会話履歴のコンパクト化
</h3>

`/compact` コマンドは、古いメッセージを要約しながら重要なコンテキストを保持することで、会話履歴のサイズを削減します。コンパクト化には、要約するための少なくとも 2 つの以前のやり取りがある既存の会話が必要です。この例では、まず会話を行い、その後コンパクト化して、結果を報告する `compact_boundary` システムメッセージを読み取ります。

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Compaction needs existing history, so have a conversation first
  try {
    for await (const message of query({
      prompt: "Explain what this project does",
      options: { maxTurns: 2 }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(message.result);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the follow-up query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Compact the same conversation
  for await (const message of query({
    prompt: "/compact",
    options: { continue: true, 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);
      // Example output:
      // Compaction completed
      // Pre-compaction tokens: 1842
      // Trigger: manual
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage, SystemMessage


  async def main():
      # Compaction needs existing history, so have a conversation first
      try:
          async for message in query(
              prompt="Explain what this project does",
              options=ClaudeAgentOptions(max_turns=2),
          ):
              if isinstance(message, ResultMessage) and message.subtype == "success":
                  print(message.result)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the follow-up query below still runs.
          print(f"Session ended with an error: {error}")

      # Compact the same conversation
      async for message in query(
          prompt="/compact",
          options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
      ):
          if isinstance(message, SystemMessage) and message.subtype == "compact_boundary":
              print("Compaction completed")
              print("Pre-compaction tokens:", message.data["compact_metadata"]["pre_tokens"])
              print("Trigger:", message.data["compact_metadata"]["trigger"])
              # Example output:
              # Compaction completed
              # Pre-compaction tokens: 1842
              # Trigger: manual


  asyncio.run(main())
  ```
</CodeGroup>

<Note>
  `compact_boundary` メッセージは、コンパクト化が実行された場合にのみ到着します。要約するものがない場合、`/compact` は例外を発生させる代わりに理由を報告します。実行は `success` 結果で終了し、`compact_boundary` メッセージは発行されず、結果テキストにメッセージが含まれます。例えば、単一の短いやり取りの後に `Not enough messages to compact.` のようなメッセージが表示されます。新しいワンショット `query()` 呼び出しは空のコンテキストで開始されるため、このパターンは以前のターンがあるセッションで使用してください。例えば、[ストリーミング入力モード](/ja/agent-sdk/streaming-vs-single-mode)またはセッションを再開する場合です。
</Note>

<h3 id="/clear-reset-conversation-context">
  `/clear` - 会話コンテキストのリセット
</h3>

`/clear` コマンドは、会話を空のコンテキストにリセットするため、その後のプロンプトは以前の会話履歴なしで開始されます。前の会話はディスクに保存され、セッション ID を [`resume` オプション](/ja/agent-sdk/sessions#resume-by-id) に渡すことで復帰できます。

これは[ストリーミング入力モード](/ja/agent-sdk/streaming-vs-single-mode)で便利です。ここでは、単一の接続を介して複数のプロンプトを送信します。ワンショット `query()` 呼び出しの場合、各呼び出しは既に空のコンテキストで開始されるため、`/clear` を送信しても実際の効果はありません。代わりに新しい `query()` を開始してください。

<Note>
  SDK の `/clear` には Claude Code v2.1.117 以降が必要です。以前のバージョンでは `slash_commands` から省略されています。
</Note>

<h2 id="creating-custom-slash-commands">
  カスタムスラッシュコマンドの作成
</h2>

組み込みスラッシュコマンドを使用するだけでなく、SDK を通じて利用可能な独自のカスタムコマンドを作成できます。カスタムコマンドは、サブエージェントの設定方法と同様に、特定のディレクトリ内のマークダウンファイルとして定義されます。

<Note>
  `.claude/commands/` ディレクトリはレガシー形式です。推奨される形式は `.claude/skills/<name>/SKILL.md` で、同じスラッシュコマンド呼び出し（`/name`）とともに Claude による自律的な呼び出しをサポートします。現在の形式については [Skills](/ja/agent-sdk/skills) を参照してください。CLI は両方の形式をサポートし続けており、以下の例は `.claude/commands/` に対して正確なままです。
</Note>

<h3 id="file-locations">
  ファイルの場所
</h3>

カスタムスラッシュコマンドは、スコープに基づいて指定されたディレクトリに保存されます。

* **プロジェクトコマンド**: `.claude/commands/` - 現在のプロジェクトでのみ利用可能（レガシー；`.claude/skills/` を推奨）
* **個人用コマンド**: `~/.claude/commands/` - すべてのプロジェクト全体で利用可能（レガシー；`~/.claude/skills/` を推奨）

<h3 id="file-format">
  ファイル形式
</h3>

各カスタムコマンドはマークダウンファイルで、以下の特性があります。

* ファイル名（`.md` 拡張子なし）がコマンド名になります
* ファイルコンテンツはコマンドが何をするかを定義します
* オプションの YAML frontmatter は設定を提供します

<h4 id="basic-example">
  基本的な例
</h4>

プロジェクトに `.claude/commands` ディレクトリが存在しない場合は作成し、その後 `.claude/commands/refactor.md` を作成します。

```markdown theme={null}
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.
```

これにより、SDK を通じて使用できる `/refactor` コマンドが作成されます。

<h4 id="with-frontmatter">
  Frontmatter 付き
</h4>

`.claude/commands/security-check.md` を作成します。

```markdown theme={null}
---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
model: claude-opus-4-8
---

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

<h3 id="using-custom-commands-in-the-sdk">
  SDK でカスタムコマンドを使用する
</h3>

ファイルシステムで定義されたカスタムコマンドは、SDK を通じて自動的に利用可能になります。

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Use a custom command
  try {
    for await (const message of query({
      prompt: "/refactor src/auth/login.ts",
      options: { maxTurns: 3 }
    })) {
      if (message.type === "assistant") {
        console.log("Refactoring suggestions:", message.message);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the second query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Custom commands appear in the slash_commands list
  for await (const message of query({
    prompt: "Hello",
    options: { maxTurns: 1 }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      console.log("Available commands:", message.slash_commands);
      // Includes built-in commands plus bundled skills and your custom commands, for example:
      // ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage


  async def main():
      # Use a custom command
      try:
          async for message in query(
              prompt="/refactor src/auth/login.py", options=ClaudeAgentOptions(max_turns=3)
          ):
              if isinstance(message, AssistantMessage):
                  for block in message.content:
                      if hasattr(block, "text"):
                          print("Refactoring suggestions:", block.text)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the second query below still runs.
          print(f"Session ended with an error: {error}")

      # Custom commands appear in the slash_commands list
      async for message in query(prompt="Hello", options=ClaudeAgentOptions(max_turns=1)):
          if isinstance(message, SystemMessage) and message.subtype == "init":
              print("Available commands:", message.data["slash_commands"])
              # Includes built-in commands plus bundled skills and your custom commands, for example:
              # ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]


  asyncio.run(main())
  ```
</CodeGroup>

<h3 id="advanced-features">
  高度な機能
</h3>

<h4 id="arguments-and-placeholders">
  引数とプレースホルダー
</h4>

カスタムコマンドはプレースホルダーを使用した動的引数をサポートします。

`.claude/commands/fix-issue.md` を作成します。

```markdown theme={null}
---
argument-hint: [issue-number] [priority]
description: Fix a GitHub issue
---

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

SDK で使用します。

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Pass arguments to custom command
  for await (const message of query({
    prompt: "/fix-issue 123 high",
    options: { maxTurns: 5 }
  })) {
    // Command will process with $0="123" and $1="high"
    if (message.type === "result" && message.subtype === "success") {
      console.log("Issue fixed:", message.result);
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


  async def main():
      # Pass arguments to custom command
      async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):
          # Command will process with $0="123" and $1="high"
          if isinstance(message, ResultMessage):
              print("Issue fixed:", message.result)


  asyncio.run(main())
  ```
</CodeGroup>

<h4 id="bash-command-execution">
  Bash コマンド実行
</h4>

カスタムコマンドは bash コマンドを実行し、その出力を含めることができます。

`.claude/commands/git-commit.md` を作成します。

```markdown theme={null}
---
allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)
description: Create a git commit
---

## Context

- Current status: !`git status`
- Current diff: !`git diff HEAD`

## Task

Create a git commit with appropriate message based on the changes.
```

<h4 id="file-references">
  ファイル参照
</h4>

`@` プレフィックスを使用してファイルコンテンツを含めます。

`.claude/commands/review-config.md` を作成します。

```markdown theme={null}
---
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.
```

<h3 id="organization-with-namespacing">
  名前空間を使用した組織化
</h3>

より良い構造のためにサブディレクトリ内でコマンドを整理します。

```bash theme={null}
.claude/commands/
├── frontend/
│   ├── component.md      # Creates /component (project:frontend)
│   └── style-check.md     # Creates /style-check (project:frontend)
├── backend/
│   ├── api-test.md        # Creates /api-test (project:backend)
│   └── db-migrate.md      # Creates /db-migrate (project:backend)
└── review.md              # Creates /review (project)
```

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

<h3 id="practical-examples">
  実践的な例
</h3>

<h4 id="pull-request-review-command">
  プルリクエストレビューコマンド
</h4>

`.claude/commands/review-pr.md` を作成します。

```markdown theme={null}
---
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.
```

<Note>
  Claude Code には、バンドルされた `code-review` と `verify` スキルが含まれています。カスタムコマンドをそれらの 1 つの後に名前を付けた場合（例えば `.claude/commands/code-review.md`）、カスタムコマンドはバンドルされたスキルをシャドウし、`slash_commands` はその名前を 1 回だけリストします。
</Note>

<h4 id="test-runner-command">
  テストランナーコマンド
</h4>

`.claude/commands/test.md` を作成します。

```markdown theme={null}
---
allowed-tools: Bash, Read, Edit
argument-hint: [test-pattern]
description: Run tests with optional pattern
---

Run tests matching pattern: $ARGUMENTS

1. Detect the test framework (Jest, pytest, etc.)
2. Run tests with the provided pattern
3. If tests fail, analyze and fix them
4. Re-run to verify fixes
```

SDK を通じてこれらのコマンドを使用します。

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Run code review
  try {
    for await (const message of query({
      prompt: "/review-pr",
      options: { maxTurns: 3 }
    })) {
      // Process review feedback
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the second query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Run specific tests
  for await (const message of query({
    prompt: "/test auth",
    options: { maxTurns: 5 }
  })) {
    // Handle test results
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions


  async def main():
      # Run code review
      try:
          async for message in query(prompt="/review-pr", options=ClaudeAgentOptions(max_turns=3)):
              # Process review feedback
              pass
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the second query below still runs.
          print(f"Session ended with an error: {error}")

      # Run specific tests
      async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)):
          # Handle test results
          pass


  asyncio.run(main())
  ```
</CodeGroup>

<h2 id="see-also">
  関連項目
</h2>

* [Slash Commands](/ja/skills) - スラッシュコマンドの完全なドキュメント
* [SDK のサブエージェント](/ja/agent-sdk/subagents) - サブエージェント用の同様のファイルシステムベースの設定
* [TypeScript SDK リファレンス](/ja/agent-sdk/typescript) - 完全な API ドキュメント
* [SDK の概要](/ja/agent-sdk/overview) - 一般的な SDK の概念
* [CLI リファレンス](/ja/cli-reference) - コマンドラインインターフェース
