agent-sdk/slash-commands.md +0 −438 deleted
File Deleted View Diff
1> ## Documentation Index
2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
3> Use this file to discover all available pages before exploring further.
4
5# Slash Commands in the SDK
6
7> Learn how to use slash commands to control Claude Code sessions through the SDK
8
9Slash 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.
10
11## Discovering Available Slash Commands
12
13The Claude Agent SDK provides information about available slash commands in the system initialization message. Access this information when your session starts:
14
15<CodeGroup>
16 ```typescript TypeScript theme={null}
17 import { query } from "@anthropic-ai/claude-agent-sdk";
18
19 for await (const message of query({
20 prompt: "Hello Claude",
21 options: { maxTurns: 1 }
22 })) {
23 if (message.type === "system" && message.subtype === "init") {
24 console.log("Available slash commands:", message.slash_commands);
25 // Example output: ["clear", "compact", "context", "usage"]
26 }
27 }
28 ```
29
30 ```python Python theme={null}
31 import asyncio
32 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage
33
34
35 async def main():
36 async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):
37 if isinstance(message, SystemMessage) and message.subtype == "init":
38 print("Available slash commands:", message.data["slash_commands"])
39 # Example output: ["clear", "compact", "context", "usage"]
40
41
42 asyncio.run(main())
43 ```
44</CodeGroup>
45
46## Sending Slash Commands
47
48Send slash commands by including them in your prompt string, just like regular text:
49
50<CodeGroup>
51 ```typescript TypeScript theme={null}
52 import { query } from "@anthropic-ai/claude-agent-sdk";
53
54 // Send a slash command
55 for await (const message of query({
56 prompt: "/compact",
57 options: { maxTurns: 1 }
58 })) {
59 if (message.type === "result" && message.subtype === "success") {
60 console.log("Command executed:", message.result);
61 }
62 }
63 ```
64
65 ```python Python theme={null}
66 import asyncio
67 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
68
69
70 async def main():
71 # Send a slash command
72 async for message in query(prompt="/compact", options=ClaudeAgentOptions(max_turns=1)):
73 if isinstance(message, ResultMessage):
74 print("Command executed:", message.result)
75
76
77 asyncio.run(main())
78 ```
79</CodeGroup>
80
81## Common Slash Commands
82
83### `/compact` - Compact conversation history
84
85The `/compact` command reduces the size of your conversation history by summarizing older messages while preserving important context:
86
87<CodeGroup>
88 ```typescript TypeScript theme={null}
89 import { query } from "@anthropic-ai/claude-agent-sdk";
90
91 for await (const message of query({
92 prompt: "/compact",
93 options: { maxTurns: 1 }
94 })) {
95 if (message.type === "system" && message.subtype === "compact_boundary") {
96 console.log("Compaction completed");
97 console.log("Pre-compaction tokens:", message.compact_metadata.pre_tokens);
98 console.log("Trigger:", message.compact_metadata.trigger);
99 }
100 }
101 ```
102
103 ```python Python theme={null}
104 import asyncio
105 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage
106
107
108 async def main():
109 async for message in query(prompt="/compact", options=ClaudeAgentOptions(max_turns=1)):
110 if isinstance(message, SystemMessage) and message.subtype == "compact_boundary":
111 print("Compaction completed")
112 print("Pre-compaction tokens:", message.data["compact_metadata"]["pre_tokens"])
113 print("Trigger:", message.data["compact_metadata"]["trigger"])
114
115
116 asyncio.run(main())
117 ```
118</CodeGroup>
119
120### `/clear` - Reset conversation context
121
122The `/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](/en/agent-sdk/sessions#resume-by-id).
123
124This is useful in [streaming input mode](/en/agent-sdk/streaming-vs-single-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.
125
126<Note>
127 `/clear` in the SDK requires Claude Code v2.1.117 or later. In earlier versions it is omitted from `slash_commands`.
128</Note>
129
130## Creating Custom Slash Commands
131
132In 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.
133
134<Note>
135 The `.claude/commands/` directory is the legacy format. The recommended format is `.claude/skills/<name>/SKILL.md`, which supports the same slash-command invocation (`/name`) plus autonomous invocation by Claude. See [Skills](/en/agent-sdk/skills) for the current format. The CLI continues to support both formats, and the examples below remain accurate for `.claude/commands/`.
136</Note>
137
138### File Locations
139
140Custom slash commands are stored in designated directories based on their scope:
141
142* **Project commands**: `.claude/commands/` - Available only in the current project (legacy; prefer `.claude/skills/`)
143* **Personal commands**: `~/.claude/commands/` - Available across all your projects (legacy; prefer `~/.claude/skills/`)
144
145### File Format
146
147Each custom command is a markdown file where:
148
149* The filename (without `.md` extension) becomes the command name
150* The file content defines what the command does
151* Optional YAML frontmatter provides configuration
152
153#### Basic Example
154
155Create `.claude/commands/refactor.md`:
156
157```markdown theme={null}
158Refactor the selected code to improve readability and maintainability.
159Focus on clean code principles and best practices.
160```
161
162This creates the `/refactor` command that you can use through the SDK.
163
164#### With Frontmatter
165
166Create `.claude/commands/security-check.md`:
167
168```markdown theme={null}
169allowed-tools: Read, Grep, Glob
170description: Run security vulnerability scan
171model: claude-opus-4-7
172
173Analyze the codebase for security vulnerabilities including:
174- SQL injection risks
175- XSS vulnerabilities
176- Exposed credentials
177- Insecure configurations
178```
179
180### Using Custom Commands in the SDK
181
182Once defined in the filesystem, custom commands are automatically available through the SDK:
183
184<CodeGroup>
185 ```typescript TypeScript theme={null}
186 import { query } from "@anthropic-ai/claude-agent-sdk";
187
188 // Use a custom command
189 for await (const message of query({
190 prompt: "/refactor src/auth/login.ts",
191 options: { maxTurns: 3 }
192 })) {
193 if (message.type === "assistant") {
194 console.log("Refactoring suggestions:", message.message);
195 }
196 }
197
198 // Custom commands appear in the slash_commands list
199 for await (const message of query({
200 prompt: "Hello",
201 options: { maxTurns: 1 }
202 })) {
203 if (message.type === "system" && message.subtype === "init") {
204 // Will include both built-in and custom commands
205 console.log("Available commands:", message.slash_commands);
206 // Example: ["clear", "compact", "context", "usage", "refactor", "security-check"]
207 }
208 }
209 ```
210
211 ```python Python theme={null}
212 import asyncio
213 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage
214
215
216 async def main():
217 # Use a custom command
218 async for message in query(
219 prompt="/refactor src/auth/login.py", options=ClaudeAgentOptions(max_turns=3)
220 ):
221 if isinstance(message, AssistantMessage):
222 for block in message.content:
223 if hasattr(block, "text"):
224 print("Refactoring suggestions:", block.text)
225
226 # Custom commands appear in the slash_commands list
227 async for message in query(prompt="Hello", options=ClaudeAgentOptions(max_turns=1)):
228 if isinstance(message, SystemMessage) and message.subtype == "init":
229 # Will include both built-in and custom commands
230 print("Available commands:", message.data["slash_commands"])
231 # Example: ["clear", "compact", "context", "usage", "refactor", "security-check"]
232
233
234 asyncio.run(main())
235 ```
236</CodeGroup>
237
238### Advanced Features
239
240#### Arguments and Placeholders
241
242Custom commands support dynamic arguments using placeholders:
243
244Create `.claude/commands/fix-issue.md`:
245
246```markdown theme={null}
247argument-hint: [issue-number] [priority]
248description: Fix a GitHub issue
249
250Fix issue #$0 with priority $1.
251Check the issue description and implement the necessary changes.
252```
253
254Use in SDK:
255
256<CodeGroup>
257 ```typescript TypeScript theme={null}
258 import { query } from "@anthropic-ai/claude-agent-sdk";
259
260 // Pass arguments to custom command
261 for await (const message of query({
262 prompt: "/fix-issue 123 high",
263 options: { maxTurns: 5 }
264 })) {
265 // Command will process with $0="123" and $1="high"
266 if (message.type === "result" && message.subtype === "success") {
267 console.log("Issue fixed:", message.result);
268 }
269 }
270 ```
271
272 ```python Python theme={null}
273 import asyncio
274 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
275
276
277 async def main():
278 # Pass arguments to custom command
279 async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):
280 # Command will process with $0="123" and $1="high"
281 if isinstance(message, ResultMessage):
282 print("Issue fixed:", message.result)
283
284
285 asyncio.run(main())
286 ```
287</CodeGroup>
288
289#### Bash Command Execution
290
291Custom commands can execute bash commands and include their output:
292
293Create `.claude/commands/git-commit.md`:
294
295```markdown theme={null}
296allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)
297description: Create a git commit
298
299## Context
300
301- Current status: !`git status`
302- Current diff: !`git diff HEAD`
303
304## Task
305
306Create a git commit with appropriate message based on the changes.
307```
308
309#### File References
310
311Include file contents using the `@` prefix:
312
313Create `.claude/commands/review-config.md`:
314
315```markdown theme={null}
316description: Review configuration files
317
318Review the following configuration files for issues:
319- Package config: @package.json
320- TypeScript config: @tsconfig.json
321- Environment config: @.env
322
323Check for security issues, outdated dependencies, and misconfigurations.
324```
325
326### Organization with Namespacing
327
328Organize commands in subdirectories for better structure:
329
330```bash theme={null}
331.claude/commands/
332├── frontend/
333│ ├── component.md # Creates /component (project:frontend)
334│ └── style-check.md # Creates /style-check (project:frontend)
335├── backend/
336│ ├── api-test.md # Creates /api-test (project:backend)
337│ └── db-migrate.md # Creates /db-migrate (project:backend)
338└── review.md # Creates /review (project)
339```
340
341The subdirectory appears in the command description but doesn't affect the command name itself.
342
343### Practical Examples
344
345#### Code Review Command
346
347Create `.claude/commands/code-review.md`:
348
349```markdown theme={null}
350allowed-tools: Read, Grep, Glob, Bash(git diff *)
351description: Comprehensive code review
352
353## Changed Files
354!`git diff --name-only HEAD~1`
355
356## Detailed Changes
357!`git diff HEAD~1`
358
359## Review Checklist
360
361Review the above changes for:
3621. Code quality and readability
3632. Security vulnerabilities
3643. Performance implications
3654. Test coverage
3665. Documentation completeness
367
368Provide specific, actionable feedback organized by priority.
369```
370
371#### Test Runner Command
372
373Create `.claude/commands/test.md`:
374
375```markdown theme={null}
376allowed-tools: Bash, Read, Edit
377argument-hint: [test-pattern]
378description: Run tests with optional pattern
379
380Run tests matching pattern: $ARGUMENTS
381
3821. Detect the test framework (Jest, pytest, etc.)
3832. Run tests with the provided pattern
3843. If tests fail, analyze and fix them
3854. Re-run to verify fixes
386```
387
388Use these commands through the SDK:
389
390<CodeGroup>
391 ```typescript TypeScript theme={null}
392 import { query } from "@anthropic-ai/claude-agent-sdk";
393
394 // Run code review
395 for await (const message of query({
396 prompt: "/code-review",
397 options: { maxTurns: 3 }
398 })) {
399 // Process review feedback
400 }
401
402 // Run specific tests
403 for await (const message of query({
404 prompt: "/test auth",
405 options: { maxTurns: 5 }
406 })) {
407 // Handle test results
408 }
409 ```
410
411 ```python Python theme={null}
412 import asyncio
413 from claude_agent_sdk import query, ClaudeAgentOptions
414
415
416 async def main():
417 # Run code review
418 async for message in query(prompt="/code-review", options=ClaudeAgentOptions(max_turns=3)):
419 # Process review feedback
420 pass
421
422 # Run specific tests
423 async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)):
424 # Handle test results
425 pass
426
427
428 asyncio.run(main())
429 ```
430</CodeGroup>
431
432## See Also
433
434* [Slash Commands](/en/skills) - Complete slash command documentation
435* [Subagents in the SDK](/en/agent-sdk/subagents) - Similar filesystem-based configuration for subagents
436* [TypeScript SDK reference](/en/agent-sdk/typescript) - Complete API documentation
437* [SDK overview](/en/agent-sdk/overview) - General SDK concepts
438* [CLI reference](/en/cli-reference) - Command-line interface