| title | Slash Commands in the SDK |
|---|---|
| source | https://code.claude.com/docs/en/agent-sdk/slash-commands |
| category | code |
| generated | true |
Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.
Learn how to use slash commands to control Claude Code sessions through the SDK
Slash commands provide a way to control Claude Code sessions with special commands that start with /. These commands can be sent through the SDK to perform actions like compacting context, listing context usage, or invoking custom commands. Only commands that work without an interactive terminal are dispatchable through the SDK; the system/init message lists the ones available in your session.
The Claude Agent SDK provides information about available slash commands in the system initialization message. Access this information when your session starts:
```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); // Example output: ["clear", "compact", "context", "usage"] } }
```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"])
# Example output: ["clear", "compact", "context", "usage"]
asyncio.run(main())
Send slash commands by including them in your prompt string, just like regular text:
```typescript TypeScript theme={null} 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); } }
```python Python theme={null}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
# Send a slash command
async for message in query(prompt="/compact", options=ClaudeAgentOptions(max_turns=1)):
if isinstance(message, ResultMessage):
print("Command executed:", message.result)
asyncio.run(main())
The /compact command reduces the size of your conversation history by summarizing older messages while preserving important context:
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); } }
```python Python theme={null}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage
async def main():
async for message in query(prompt="/compact", options=ClaudeAgentOptions(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"])
asyncio.run(main())
The /clear command resets the conversation to an empty context, so subsequent prompts start with no prior conversation history. The previous conversation remains on disk and can be returned to by passing its session ID to the resume option.
This is useful in streaming input mode, where you send multiple prompts over a single connection. For one-shot query() calls, each call already starts with empty context, so sending /clear has no practical effect; start a new query() instead.
In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. Custom commands are defined as markdown files in specific directories, similar to how subagents are configured.
The `.claude/commands/` directory is the legacy format. The recommended format is `.claude/skills//SKILL.md`, which supports the same slash-command invocation (`/name`) plus autonomous invocation by Claude. See [Skills](./code-agent-sdk/skills.md) for the current format. The CLI continues to support both formats, and the examples below remain accurate for `.claude/commands/`.Custom slash commands are stored in designated directories based on their scope:
- Project commands:
.claude/commands/- Available only in the current project (legacy; prefer.claude/skills/) - Personal commands:
~/.claude/commands/- Available across all your projects (legacy; prefer~/.claude/skills/)
Each custom command is a markdown file where:
- The filename (without
.mdextension) becomes the command name - The file content defines what the command does
- Optional YAML frontmatter provides configuration
Create .claude/commands/refactor.md:
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.This creates the /refactor command that you can use through the SDK.
Create .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 configurationsOnce defined in the filesystem, custom commands are automatically available through the SDK:
```typescript TypeScript theme={null} 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"] } }
```python Python theme={null}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage
async def main():
# Use a custom command
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)
# 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":
# Will include both built-in and custom commands
print("Available commands:", message.data["slash_commands"])
# Example: ["clear", "compact", "context", "usage", "refactor", "security-check"]
asyncio.run(main())
Custom commands support dynamic arguments using placeholders:
Create .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.Use in SDK:
```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())
Custom commands can execute bash commands and include their output:
Create .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.Include file contents using the @ prefix:
Create .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.Organize commands in subdirectories for better structure:
.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)The subdirectory appears in the command description but doesn't affect the command name itself.
Create .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.Create .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 fixesUse these commands through the SDK:
```typescript TypeScript theme={null} 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 }
```python Python theme={null}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
# Run code review
async for message in query(prompt="/code-review", options=ClaudeAgentOptions(max_turns=3)):
# Process review feedback
pass
# 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 - Complete slash command documentation
- Subagents in the SDK - Similar filesystem-based configuration for subagents
- TypeScript SDK reference - Complete API documentation
- SDK overview - General SDK concepts
- CLI reference - Command-line interface