SpyBara
Go Premium

agent-sdk/slash-commands.md 2026-06-29 23:02 UTC to 2026-06-30 23:02 UTC

141 added, 25 removed.

2026
Tue 30 23:02 Mon 29 23:02 Sat 27 01:01 Fri 26 23:00 Thu 25 23:58 Wed 24 22:02 Tue 23 22:00 Mon 22 23:59 Fri 19 22:58 Thu 18 22:00 Wed 17 17:02 Tue 16 21:57 Mon 15 23:02 Sat 13 21:59 Fri 12 22:00 Thu 11 23:01 Wed 10 23:57 Tue 9 06:34 Mon 8 06:52 Sat 6 06:24 Fri 5 06:45 Thu 4 06:52 Wed 3 06:53 Tue 2 06:51

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", ...]
}
}

スラッシュコマンドの送信

スラッシュコマンドをプロンプト文字列に含めて送信します。通常のテキストと同じように使用します。会話履歴に作用するコマンド(/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
}
}

一般的なスラッシュコマンド

`/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
}
}

`/clear` - 会話コンテキストのリセット

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

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

カスタムスラッシュコマンドの作成

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

ファイルの場所

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

  • プロジェクトコマンド: .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", ...]
}
}

高度な機能

引数とプレースホルダー

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

.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/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/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
}

関連項目