Appearance
SDK 斜杠命令让你在 Claude Code 会话中直接触发内置和自定义操作,例如用 /compact 压缩上下文窗口、用 /refactor 执行代码重构。内置命令通过 system/init 消息获取列表,自定义命令需要放在 .claude/commands/(旧格式)或推荐用 .claude/skills/<name>/SKILL.md(技能格式)。注意 /clear 不可用,需要新会话时直接结束当前 query() 并开启新连接。自定义命令支持参数占位符、Bash 命令执行和文件引用,通过 prompt 字符串发送即可。
Claude Agent SDK 斜杠命令怎么配置和使用
斜杠命令(以 / 开头)是控制 Claude Code 会话的快捷方式,通过 SDK 发送可执行操作,如压缩上下文、查看使用量或调用自定义命令。只有不依赖交互终端的命令才支持通过 SDK 派发;system/init 消息会列出当前会话可用的命令。
发现可用斜杠命令
Claude Agent SDK 在系统初始化消息中提供可用斜杠命令的信息。在会话启动时获取:
typescript
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: ["/compact", "/context", "/usage"]
}
}python
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: ["/compact", "/context", "/usage"]
asyncio.run(main())发送斜杠命令
将斜杠命令直接写入 prompt 字符串中发送,就像普通文本一样:
typescript
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
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())常见斜杠命令
/compact - 压缩对话历史
/compact 命令通过摘要旧消息来减少对话历史体积,同时保留关键上下文。压缩完成后会收到 compact_boundary 消息,其中包含压缩前后的 tokens 数和触发原因:
typescript
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);
}
}python
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())清除对话(/clear 不可用)
交互式的 /clear 命令在 SDK 中不可用。每次 query() 调用都会开启新会话,所以要清除上下文只需结束当前 query() 并新建一个。旧会话会保存在磁盘上,可以通过传递其 session ID 给 resume 选项恢复(详见会话管理)。
创建自定义斜杠命令
除了内置命令,你还可以创建自定的斜杠命令,它们通过 SDK 自动可用。自定义命令以 Markdown 文件形式存放在特定目录中,与子代理(subagents)的配置方式类似。
.claude/commands/是旧格式,推荐使用.claude/skills/<name>/SKILL.md格式,既支持斜杠调用(/name)也允许 Claude 自主调用。详见技能文档。CLI 同时支持两种格式,下面示例对.claude/commands/依然有效。
文件存放位置
根据作用域,自定义命令存放在不同目录:
- 项目命令:
.claude/commands/— 仅当前项目可用(旧格式;优先使用.claude/skills/) - 个人命令:
~/.claude/commands/— 所有项目通用(旧格式;优先使用~/.claude/skills/)
文件格式
每个自定义命令是一个 Markdown 文件,规则如下:
- 文件名(不含
.md扩展名)即为命令名称 - 文件内容定义命令的行为
- 可选 YAML frontmatter 提供额外配置
基础示例
创建 .claude/commands/refactor.md:
markdown
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.这创建了 /refactor 命令,可在 SDK 中使用。
带 Frontmatter 的示例
创建 .claude/commands/security-check.md:
markdown
---
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 可用:
typescript
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: ["/compact", "/context", "/usage", "/refactor", "/security-check"]
}
}python
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: ["/compact", "/context", "/usage", "/refactor", "/security-check"]
asyncio.run(main())高级特性
参数与占位符
自定义命令支持使用占位符实现动态参数:
创建 .claude/commands/fix-issue.md:
markdown
---
argument-hint: [issue-number] [priority]
description: Fix a GitHub issue
---
Fix issue #$1 with priority $2.
Check the issue description and implement the necessary changes.在 SDK 中使用:
typescript
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 $1="123" and $2="high"
if (message.type === "result" && message.subtype === "success") {
console.log("Issue fixed:", message.result);
}
}python
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 $1="123" and $2="high"
if isinstance(message, ResultMessage):
print("Issue fixed:", message.result)
asyncio.run(main())Bash 命令执行
自定义命令可以执行 Bash 命令并将输出包含到 prompt 中:
创建 .claude/commands/git-commit.md:
markdown
---
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:
markdown
---
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.命名空间组织
通过子目录组织命令:
bash
.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:
markdown
---
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:
markdown
---
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 中使用这些命令:
typescript
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
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())参考
- 斜杠命令完整文档
- SDK 子代理 — 类似文件系统的子代理配置
- TypeScript SDK 参考 — 完整 API 文档
- SDK 概览 — 通用 SDK 概念
- CLI 参考 — 命令行接口
常见问题
为什么 SDK 中无法使用 /clear 命令?
交互式 /clear 在 SDK 中不可用。要清除上下文,直接结束当前 query() 并新建会话即可。旧会话通过 session ID 可恢复。
自定义命令放在 .claude/commands/ 还是 .claude/skills/?
推荐使用 .claude/skills/<name>/SKILL.md 格式(技能),它同时支持斜杠调用和自主调用。旧格式 .claude/commands/ 仍受支持,但建议迁移。
如何在自定义命令中传递多个参数?
在 frontmatter 中设置 argument-hint: [arg1] [arg2],然后在 prompt 中以空格分隔传入,如 /fix-issue 123 high,在命令内容中用 $1、$2 引用。