SDK のスラッシュコマンド
SDK を通じて Claude Code セッションを制御するスラッシュコマンドの使用方法を学びます
スラッシュコマンドは、/ で始まる特別なコマンドを使用して Claude Code セッションを制御する方法を提供します。これらのコマンドは SDK を通じて送信でき、コンテキストのコンパクト化、コンテキスト使用状況の一覧表示、またはカスタムコマンドの呼び出しなどのアクションを実行できます。インタラクティブなターミナルなしで機能するコマンドのみが SDK を通じてディスパッチ可能です。system/init メッセージにはセッションで利用可能なコマンドが一覧表示されます。
利用可能なスラッシュコマンドの検出
Claude Agent SDK は、システム初期化メッセージで利用可能なスラッシュコマンドに関する情報を提供します。セッション開始時にこの情報にアクセスします。
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", ...]
}
}
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())
スラッシュコマンドの送信
スラッシュコマンドをプロンプト文字列に含めて送信します。通常のテキストと同じように使用します。会話履歴に作用するコマンド(/compact など)は、動作するために事前のメッセージが必要です。そのため、以下の例では最初に質問を送信してから、同じ会話へのフォローアップとしてコマンドを送信しています。
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
}
}
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())
クエリはエラー結果で終了する場合があります。例えば、maxTurns / max_turns の制限に達してから作業が完了する前に終了する場合です。最終的な結果メッセージは is_error: true を持ち、success の代わりに error_max_turns などのエラーサブタイプを持ちます。
その最終的な結果メッセージを生成した後、SDK はエラーを発生させます。これは CLI プロセスがゼロ以外のコードで終了するためです。
コマンドが制限に達する可能性がある場合は、Single Message Input に示されているように、TypeScript では try/catch でループをラップするか、Python では try/except でラップしてください。または、作業が完了するのに十分な高さに maxTurns を設定してください。Python では、Exception をキャッチしてください。SDK はエラー結果をプレーンな Exception として表示します。
一般的なスラッシュコマンド
`/compact` - 会話履歴のコンパクト化
/compact コマンドは、古いメッセージを要約しながら重要なコンテキストを保持することで、会話履歴のサイズを削減します。コンパクト化には、要約するための少なくとも 2 つの以前のやり取りがある既存の会話が必要です。この例では、まず会話を行い、その後コンパクト化して、結果を報告する compact_boundary システムメッセージを読み取ります。
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
}
}
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())
compact_boundary メッセージは、コンパクト化が実行された場合にのみ到着します。要約するものがない場合、/compact は例外を発生させる代わりに理由を報告します。実行は success 結果で終了し、compact_boundary メッセージは発行されず、結果テキストにメッセージが含まれます。例えば、単一の短いやり取りの後に Not enough messages to compact. のようなメッセージが表示されます。新しいワンショット query() 呼び出しは空のコンテキストで開始されるため、このパターンは以前のターンがあるセッションで使用してください。例えば、ストリーミング入力モードまたはセッションを再開する場合です。
`/clear` - 会話コンテキストのリセット
/clear コマンドは、会話を空のコンテキストにリセットするため、その後のプロンプトは以前の会話履歴なしで開始されます。前の会話はディスクに保存され、セッション ID を resume オプション に渡すことで復帰できます。
これはストリーミング入力モードで便利です。ここでは、単一の接続を介して複数のプロンプトを送信します。ワンショット query() 呼び出しの場合、各呼び出しは既に空のコンテキストで開始されるため、/clear を送信しても実際の効果はありません。代わりに新しい query() を開始してください。
SDK の /clear には Claude Code v2.1.117 以降が必要です。以前のバージョンでは slash_commands から省略されています。
カスタムスラッシュコマンドの作成
組み込みスラッシュコマンドを使用するだけでなく、SDK を通じて利用可能な独自のカスタムコマンドを作成できます。カスタムコマンドは、サブエージェントの設定方法と同様に、特定のディレクトリ内のマークダウンファイルとして定義されます。
.claude/commands/ ディレクトリはレガシー形式です。推奨される形式は .claude/skills/<name>/SKILL.md で、同じスラッシュコマンド呼び出し(/name)とともに Claude による自律的な呼び出しをサポートします。現在の形式については Skills を参照してください。CLI は両方の形式をサポートし続けており、以下の例は .claude/commands/ に対して正確なままです。
ファイルの場所
カスタムスラッシュコマンドは、スコープに基づいて指定されたディレクトリに保存されます。
- プロジェクトコマンド:
.claude/commands/- 現在のプロジェクトでのみ利用可能(レガシー;.claude/skills/を推奨) - 個人用コマンド:
~/.claude/commands/- すべてのプロジェクト全体で利用可能(レガシー;~/.claude/skills/を推奨)
ファイル形式
各カスタムコマンドはマークダウンファイルで、以下の特性があります。
- ファイル名(
.md拡張子なし)がコマンド名になります - ファイルコンテンツはコマンドが何をするかを定義します
- オプションの YAML frontmatter は設定を提供します
基本的な例
プロジェクトに .claude/commands ディレクトリが存在しない場合は作成し、その後 .claude/commands/refactor.md を作成します。
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.
これにより、SDK を通じて使用できる /refactor コマンドが作成されます。
Frontmatter 付き
.claude/commands/security-check.md を作成します。
---
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
SDK でカスタムコマンドを使用する
ファイルシステムで定義されたカスタムコマンドは、SDK を通じて自動的に利用可能になります。
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", ...]
}
}
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())
高度な機能
引数とプレースホルダー
カスタムコマンドはプレースホルダーを使用した動的引数をサポートします。
.claude/commands/fix-issue.md を作成します。
---
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 で使用します。
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);
}
}
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())
Bash コマンド実行
カスタムコマンドは bash コマンドを実行し、その出力を含めることができます。
.claude/commands/git-commit.md を作成します。
---
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.
ファイル参照
@ プレフィックスを使用してファイルコンテンツを含めます。
.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.
名前空間を使用した組織化
より良い構造のためにサブディレクトリ内でコマンドを整理します。
.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)
サブディレクトリはコマンドの説明に表示されますが、コマンド名自体には影響しません。
実践的な例
プルリクエストレビューコマンド
.claude/commands/review-pr.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.
Claude Code には、バンドルされた code-review と verify スキルが含まれています。カスタムコマンドをそれらの 1 つの後に名前を付けた場合(例えば .claude/commands/code-review.md)、カスタムコマンドはバンドルされたスキルをシャドウし、slash_commands はその名前を 1 回だけリストします。
テストランナーコマンド
.claude/commands/test.md を作成します。
---
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 を通じてこれらのコマンドを使用します。
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
}
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())
関連項目
- Slash Commands - スラッシュコマンドの完全なドキュメント
- SDK のサブエージェント - サブエージェント用の同様のファイルシステムベースの設定
- TypeScript SDK リファレンス - 完全な API ドキュメント
- SDK の概要 - 一般的な SDK の概念
- CLI リファレンス - コマンドラインインターフェース