スラッシュコマンドは、/ で始まる特別なコマンドを使用して 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);
// Example output: ["clear", "compact", "context", "usage"]
}
}
スラッシュコマンドの送信
スラッシュコマンドをプロンプト文字列に含めて送信します。通常のテキストと同じように使用します。
import { query } from "@anthropic-ai/claude-agent-sdk";
// Send a slash command
for await (const message of query({
prompt: "/compact",
options: { maxTurns: 1 }
})) {
if (message.type === "result" && message.subtype === "success") {
console.log("Command executed:", message.result);
}
}
一般的なスラッシュコマンド
/compact - 会話履歴のコンパクト化
/compact コマンドは、古いメッセージを要約しながら重要なコンテキストを保持することで、会話履歴のサイズを削減します。
import { query } from "@anthropic-ai/claude-agent-sdk";
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);
}
}
/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/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-7
---
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
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);
}
}
// 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") {
// Will include both built-in and custom commands
console.log("Available commands:", message.slash_commands);
// Example: ["clear", "compact", "context", "usage", "refactor", "security-check"]
}
}
高度な機能
引数とプレースホルダー
カスタムコマンドはプレースホルダーを使用した動的引数をサポートします。
.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);
}
}
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/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.
テストランナーコマンド
.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
for await (const message of query({
prompt: "/code-review",
options: { maxTurns: 3 }
})) {
// Process review feedback
}
// Run specific tests
for await (const message of query({
prompt: "/test auth",
options: { maxTurns: 5 }
})) {
// Handle test results
}
関連項目