SpyBara
Go Premium

Documentation 2026-08-19 17:02 UTC to 2026-08-20 23:01 UTC

1 file changed +0 −594. View all changes and history on the product overview
2026
Fri 21 01:00 Thu 20 23:01 Wed 19 17:02 Tue 18 23:59 Mon 17 22:57 Sun 16 14:59 Sat 15 16:00 Fri 14 23:00 Thu 13 23:57 Wed 12 23:59 Tue 11 22:03 Mon 10 22:57 Sun 9 04:02 Sat 8 04:59 Fri 7 23:57 Thu 6 15:02 Wed 5 22:02 Tue 4 22:59 Mon 3 20:02 Sun 2 19:00

agent-sdk/slash-commands.md +0 −594 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# SDK의 슬래시 명령어

6 

7> SDK를 통해 Claude Code 세션을 제어하기 위해 슬래시 명령어를 사용하는 방법을 알아봅니다

8 

9슬래시 명령어는 `/`로 시작하는 특수 명령어를 사용하여 Claude Code 세션을 제어하는 방법을 제공합니다. 이러한 명령어는 SDK를 통해 전송되어 컨텍스트 압축, 컨텍스트 사용량 나열 또는 사용자 정의 명령어 호출과 같은 작업을 수행할 수 있습니다. 대화형 터미널 없이 작동하는 명령어만 SDK를 통해 전달할 수 있으며, `system/init` 메시지에 세션에서 사용 가능한 명령어가 나열됩니다.

10 

11<h2 id="discovering-available-slash-commands">

12 사용 가능한 슬래시 명령어 발견

13</h2>

14 

15Claude Agent SDK는 시스템 초기화 메시지에서 사용 가능한 슬래시 명령어에 대한 정보를 제공합니다. 세션이 시작될 때 이 정보에 접근합니다:

16 

17<CodeGroup>

18 ```typescript TypeScript theme={null}

19 import { query } from "@anthropic-ai/claude-agent-sdk";

20 

21 for await (const message of query({

22 prompt: "Hello Claude",

23 options: { maxTurns: 1 }

24 })) {

25 if (message.type === "system" && message.subtype === "init") {

26 console.log("Available slash commands:", message.slash_commands);

27 // Includes built-in commands plus bundled skills, for example:

28 // ["clear", "compact", "context", "usage", "code-review", "verify", ...]

29 }

30 }

31 ```

32 

33 ```python Python theme={null}

34 import asyncio

35 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage

36 

37 

38 async def main():

39 async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):

40 if isinstance(message, SystemMessage) and message.subtype == "init":

41 print("Available slash commands:", message.data["slash_commands"])

42 # Includes built-in commands plus bundled skills, for example:

43 # ["clear", "compact", "context", "usage", "code-review", "verify", ...]

44 

45 

46 asyncio.run(main())

47 ```

48</CodeGroup>

49 

50<h2 id="sending-slash-commands">

51 슬래시 명령어 전송

52</h2>

53 

54슬래시 명령어를 프롬프트 문자열에 포함하여 일반 텍스트처럼 전송합니다. `/compact`와 같이 대화 기록에 작용하는 명령어는 작업할 이전 메시지가 필요하므로, 아래 예제에서는 먼저 질문을 한 다음 같은 대화에 대한 후속 명령어로 명령어를 전송합니다:

55 

56<CodeGroup>

57 ```typescript TypeScript theme={null}

58 import { query } from "@anthropic-ai/claude-agent-sdk";

59 

60 // Build up conversation history first

61 try {

62 for await (const message of query({

63 prompt: "What does the README in this directory cover?",

64 options: { maxTurns: 2 }

65 })) {

66 if (message.type === "result" && message.subtype === "success") {

67 console.log(message.result);

68 }

69 }

70 } catch (error) {

71 // A single-shot query() throws after yielding an error result,

72 // so the follow-up query below still runs.

73 console.error(`Session ended with an error: ${error}`);

74 }

75 

76 // Send a slash command as a follow-up to the same conversation

77 for await (const message of query({

78 prompt: "/compact",

79 options: { continue: true, maxTurns: 1 }

80 })) {

81 if (message.type === "result") {

82 console.log("Command executed, result subtype:", message.subtype);

83 // Example output: Command executed, result subtype: success

84 }

85 }

86 ```

87 

88 ```python Python theme={null}

89 import asyncio

90 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

91 

92 

93 async def main():

94 # Build up conversation history first

95 try:

96 async for message in query(

97 prompt="What does the README in this directory cover?",

98 options=ClaudeAgentOptions(max_turns=2),

99 ):

100 if isinstance(message, ResultMessage) and message.subtype == "success":

101 print(message.result)

102 except Exception as error:

103 # A single-shot query() raises after yielding an error result,

104 # so the follow-up query below still runs.

105 print(f"Session ended with an error: {error}")

106 

107 # Send a slash command as a follow-up to the same conversation

108 async for message in query(

109 prompt="/compact",

110 options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),

111 ):

112 if isinstance(message, ResultMessage):

113 print("Command executed, result subtype:", message.subtype)

114 # Example output: Command executed, result subtype: success

115 

116 

117 asyncio.run(main())

118 ```

119</CodeGroup>

120 

121<Note>

122 쿼리는 오류 결과로 끝날 수 있습니다. 예를 들어 작업이 완료되기 전에 `maxTurns` / `max_turns` 제한에 도달한 경우입니다. 최종 결과 메시지는 `is_error: true`를 가지며 `success` 대신 `error_max_turns`와 같은 오류 서브타입을 가집니다.

123 

124 해당 최종 결과 메시지를 생성한 후 SDK는 CLI 프로세스가 0이 아닌 코드로 종료되기 때문에 오류를 발생시킵니다.

125 

126 명령어가 제한에 도달할 수 있는 경우 TypeScript에서는 루프를 `try`/`catch`로 감싸거나 Python에서는 `try`/`except`로 감싸십시오. [단일 메시지 입력](/ko/agent-sdk/streaming-vs-single-mode#single-message-input)에 표시된 대로 하거나, 작업이 완료될 수 있도록 `maxTurns`를 충분히 높게 설정하십시오. Python에서는 `Exception`을 캐치하십시오: SDK는 오류 결과를 일반 `Exception`으로 표시합니다.

127</Note>

128 

129<h2 id="common-slash-commands">

130 일반적인 슬래시 명령어

131</h2>

132 

133<h3 id="/compact-compact-conversation-history">

134 `/compact` - 대화 기록 압축

135</h3>

136 

137`/compact` 명령어는 이전 메시지를 요약하면서 중요한 컨텍스트를 보존하여 대화 기록의 크기를 줄입니다. 압축을 수행하려면 최소 두 번의 이전 교환이 있는 기존 대화가 필요합니다. 이 예제는 먼저 대화를 진행한 후 압축을 수행하고 결과를 보고하는 `compact_boundary` 시스템 메시지를 읽습니다:

138 

139<CodeGroup>

140 ```typescript TypeScript theme={null}

141 import { query } from "@anthropic-ai/claude-agent-sdk";

142 

143 // Compaction needs existing history, so have a conversation first

144 try {

145 for await (const message of query({

146 prompt: "Explain what this project does",

147 options: { maxTurns: 2 }

148 })) {

149 if (message.type === "result" && message.subtype === "success") {

150 console.log(message.result);

151 }

152 }

153 } catch (error) {

154 // A single-shot query() throws after yielding an error result,

155 // so the follow-up query below still runs.

156 console.error(`Session ended with an error: ${error}`);

157 }

158 

159 // Compact the same conversation

160 for await (const message of query({

161 prompt: "/compact",

162 options: { continue: true, maxTurns: 1 }

163 })) {

164 if (message.type === "system" && message.subtype === "compact_boundary") {

165 console.log("Compaction completed");

166 console.log("Pre-compaction tokens:", message.compact_metadata.pre_tokens);

167 console.log("Trigger:", message.compact_metadata.trigger);

168 // Example output:

169 // Compaction completed

170 // Pre-compaction tokens: 1842

171 // Trigger: manual

172 }

173 }

174 ```

175 

176 ```python Python theme={null}

177 import asyncio

178 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage, SystemMessage

179 

180 

181 async def main():

182 # Compaction needs existing history, so have a conversation first

183 try:

184 async for message in query(

185 prompt="Explain what this project does",

186 options=ClaudeAgentOptions(max_turns=2),

187 ):

188 if isinstance(message, ResultMessage) and message.subtype == "success":

189 print(message.result)

190 except Exception as error:

191 # A single-shot query() raises after yielding an error result,

192 # so the follow-up query below still runs.

193 print(f"Session ended with an error: {error}")

194 

195 # Compact the same conversation

196 async for message in query(

197 prompt="/compact",

198 options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),

199 ):

200 if isinstance(message, SystemMessage) and message.subtype == "compact_boundary":

201 print("Compaction completed")

202 print("Pre-compaction tokens:", message.data["compact_metadata"]["pre_tokens"])

203 print("Trigger:", message.data["compact_metadata"]["trigger"])

204 # Example output:

205 # Compaction completed

206 # Pre-compaction tokens: 1842

207 # Trigger: manual

208 

209 

210 asyncio.run(main())

211 ```

212</CodeGroup>

213 

214<Note>

215 `compact_boundary` 메시지는 압축이 실행되었을 때만 도착합니다. 요약할 내용이 없으면 `/compact`는 대신 이유를 보고합니다. 실행은 여전히 `success` 결과로 끝나고, `compact_boundary` 메시지는 발생하지 않으며, 결과 텍스트에 메시지가 포함됩니다. 예를 들어 짧은 단일 교환 후 `Not enough messages to compact.`입니다. 새로운 일회성 `query()` 호출은 빈 컨텍스트로 시작하므로 이 패턴을 이전 턴이 있는 세션에서 사용하세요. 예를 들어 [스트리밍 입력 모드](/ko/agent-sdk/streaming-vs-single-mode)에서 또는 세션을 재개할 때입니다.

216</Note>

217 

218<h3 id="/clear-reset-conversation-context">

219 `/clear` - 대화 컨텍스트 초기화

220</h3>

221 

222`/clear` 명령어는 대화를 빈 컨텍스트로 초기화하므로 이후의 프롬프트는 이전 대화 기록 없이 시작됩니다. 이전 대화는 디스크에 남아 있으며 세션 ID를 [`resume` 옵션](/ko/agent-sdk/sessions#resume-by-id)에 전달하여 돌아갈 수 있습니다.

223 

224이는 단일 연결을 통해 여러 프롬프트를 보내는 [스트리밍 입력 모드](/ko/agent-sdk/streaming-vs-single-mode)에서 유용합니다. 일회성 `query()` 호출의 경우 각 호출은 이미 빈 컨텍스트로 시작하므로 `/clear`를 보내는 것은 실질적인 효과가 없습니다. 대신 새로운 `query()`를 시작하세요.

225 

226<Note>

227 SDK의 `/clear`는 Claude Code v2.1.117 이상이 필요합니다. 이전 버전에서는 `slash_commands`에서 생략됩니다.

228</Note>

229 

230<h2 id="creating-custom-slash-commands">

231 사용자 정의 슬래시 명령어 만들기

232</h2>

233 

234기본 제공 슬래시 명령어를 사용하는 것 외에도 SDK를 통해 사용 가능한 자신만의 사용자 정의 명령어를 만들 수 있습니다. 사용자 정의 명령어는 서브에이전트가 구성되는 방식과 유사하게 특정 디렉토리의 마크다운 파일로 정의됩니다.

235 

236<Note>

237 `.claude/commands/` 디렉토리는 레거시 형식입니다. 권장되는 형식은 `.claude/skills/<name>/SKILL.md`이며, 이는 동일한 슬래시 명령어 호출(`/name`)과 Claude의 자율적 호출을 지원합니다. 현재 형식은 [Skills](/ko/agent-sdk/skills)를 참조하세요. CLI는 두 형식을 모두 계속 지원하며, 아래 예제는 `.claude/commands/`에 대해 정확합니다.

238</Note>

239 

240<h3 id="file-locations">

241 파일 위치

242</h3>

243 

244사용자 정의 슬래시 명령어는 범위에 따라 지정된 디렉토리에 저장됩니다:

245 

246* **프로젝트 명령어**: `.claude/commands/` - 현재 프로젝트에서만 사용 가능 (레거시; `.claude/skills/` 선호)

247* **개인 명령어**: `~/.claude/commands/` - 모든 프로젝트에서 사용 가능 (레거시; `~/.claude/skills/` 선호)

248 

249<h3 id="file-format">

250 파일 형식

251</h3>

252 

253각 사용자 정의 명령어는 마크다운 파일이며:

254 

255* 파일명(`.md` 확장자 제외)이 명령어 이름이 됩니다

256* 파일 내용이 명령어의 기능을 정의합니다

257* 선택적 YAML frontmatter가 구성을 제공합니다

258 

259<h4 id="basic-example">

260 기본 예제

261</h4>

262 

263프로젝트에 `.claude/commands` 디렉토리가 없으면 생성한 후 `.claude/commands/refactor.md`를 생성합니다:

264 

265```markdown theme={null}

266Refactor the selected code to improve readability and maintainability.

267Focus on clean code principles and best practices.

268```

269 

270이는 SDK를 통해 사용할 수 있는 `/refactor` 명령어를 만듭니다.

271 

272<h4 id="with-frontmatter">

273 Frontmatter 포함

274</h4>

275 

276`.claude/commands/security-check.md` 생성:

277 

278```markdown theme={null}

279allowed-tools: Read, Grep, Glob

280description: Run security vulnerability scan

281model: claude-opus-4-8

282 

283Analyze the codebase for security vulnerabilities including:

284- SQL injection risks

285- XSS vulnerabilities

286- Exposed credentials

287- Insecure configurations

288```

289 

290<h3 id="using-custom-commands-in-the-sdk">

291 SDK에서 사용자 정의 명령어 사용

292</h3>

293 

294파일 시스템에서 정의되면 사용자 정의 명령어는 SDK를 통해 자동으로 사용 가능합니다:

295 

296<CodeGroup>

297 ```typescript TypeScript theme={null}

298 import { query } from "@anthropic-ai/claude-agent-sdk";

299 

300 // 사용자 정의 명령어 사용

301 try {

302 for await (const message of query({

303 prompt: "/refactor src/auth/login.ts",

304 options: { maxTurns: 3 }

305 })) {

306 if (message.type === "assistant") {

307 console.log("Refactoring suggestions:", message.message);

308 }

309 }

310 } catch (error) {

311 // 단일 쿼리 query()는 오류 결과를 반환한 후 throw하므로,

312 // 아래의 두 번째 쿼리는 여전히 실행됩니다.

313 console.error(`Session ended with an error: ${error}`);

314 }

315 

316 // 사용자 정의 명령어는 slash_commands 목록에 나타납니다

317 for await (const message of query({

318 prompt: "Hello",

319 options: { maxTurns: 1 }

320 })) {

321 if (message.type === "system" && message.subtype === "init") {

322 console.log("Available commands:", message.slash_commands);

323 // 기본 제공 명령어와 번들된 스킬 및 사용자 정의 명령어를 포함합니다. 예를 들어:

324 // ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]

325 }

326 }

327 ```

328 

329 ```python Python theme={null}

330 import asyncio

331 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, SystemMessage

332 

333 

334 async def main():

335 # 사용자 정의 명령어 사용

336 try:

337 async for message in query(

338 prompt="/refactor src/auth/login.py", options=ClaudeAgentOptions(max_turns=3)

339 ):

340 if isinstance(message, AssistantMessage):

341 for block in message.content:

342 if hasattr(block, "text"):

343 print("Refactoring suggestions:", block.text)

344 except Exception as error:

345 # 단일 쿼리 query()는 오류 결과를 반환한 후 raise하므로,

346 # 아래의 두 번째 쿼리는 여전히 실행됩니다.

347 print(f"Session ended with an error: {error}")

348 

349 # 사용자 정의 명령어는 slash_commands 목록에 나타납니다

350 async for message in query(prompt="Hello", options=ClaudeAgentOptions(max_turns=1)):

351 if isinstance(message, SystemMessage) and message.subtype == "init":

352 print("Available commands:", message.data["slash_commands"])

353 # 기본 제공 명령어와 번들된 스킬 및 사용자 정의 명령어를 포함합니다. 예를 들어:

354 # ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]

355 

356 

357 asyncio.run(main())

358 ```

359</CodeGroup>

360 

361<h3 id="advanced-features">

362 고급 기능

363</h3>

364 

365<h4 id="arguments-and-placeholders">

366 인수 및 플레이스홀더

367</h4>

368 

369사용자 정의 명령어는 플레이스홀더를 사용하여 동적 인수를 지원합니다:

370 

371`.claude/commands/fix-issue.md` 생성:

372 

373```markdown theme={null}

374argument-hint: [issue-number] [priority]

375description: Fix a GitHub issue

376 

377Fix issue #$0 with priority $1.

378Check the issue description and implement the necessary changes.

379```

380 

381SDK에서 사용:

382 

383<CodeGroup>

384 ```typescript TypeScript theme={null}

385 import { query } from "@anthropic-ai/claude-agent-sdk";

386 

387 // 사용자 정의 명령어에 인수 전달

388 for await (const message of query({

389 prompt: "/fix-issue 123 high",

390 options: { maxTurns: 5 }

391 })) {

392 // 명령어는 $0="123"과 $1="high"로 처리됩니다

393 if (message.type === "result" && message.subtype === "success") {

394 console.log("Issue fixed:", message.result);

395 }

396 }

397 ```

398 

399 ```python Python theme={null}

400 import asyncio

401 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

402 

403 

404 async def main():

405 # 사용자 정의 명령어에 인수 전달

406 async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):

407 # 명령어는 $0="123"과 $1="high"로 처리됩니다

408 if isinstance(message, ResultMessage):

409 print("Issue fixed:", message.result)

410 

411 

412 asyncio.run(main())

413 ```

414</CodeGroup>

415 

416<h4 id="bash-command-execution">

417 Bash 명령어 실행

418</h4>

419 

420사용자 정의 명령어는 bash 명령어를 실행하고 출력을 포함할 수 있습니다:

421 

422`.claude/commands/git-commit.md` 생성:

423 

424```markdown theme={null}

425allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)

426description: Create a git commit

427 

428## Context

429 

430- Current status: !`git status`

431- Current diff: !`git diff HEAD`

432 

433## Task

434 

435Create a git commit with appropriate message based on the changes.

436```

437 

438<h4 id="file-references">

439 파일 참조

440</h4>

441 

442`@` 접두사를 사용하여 파일 내용을 포함합니다:

443 

444`.claude/commands/review-config.md` 생성:

445 

446```markdown theme={null}

447description: Review configuration files

448 

449Review the following configuration files for issues:

450- Package config: @package.json

451- TypeScript config: @tsconfig.json

452- Environment config: @.env

453 

454Check for security issues, outdated dependencies, and misconfigurations.

455```

456 

457<h3 id="organization-with-namespacing">

458 네임스페이싱을 통한 조직화

459</h3>

460 

461더 나은 구조를 위해 명령어를 하위 디렉토리에 구성합니다:

462 

463```bash theme={null}

464.claude/commands/

465├── frontend/

466│ ├── component.md # /component 생성 (project:frontend)

467│ └── style-check.md # /style-check 생성 (project:frontend)

468├── backend/

469│ ├── api-test.md # /api-test 생성 (project:backend)

470│ └── db-migrate.md # /db-migrate 생성 (project:backend)

471└── review.md # /review 생성 (project)

472```

473 

474하위 디렉토리는 명령어 설명에 나타나지만 명령어 이름 자체에는 영향을 주지 않습니다.

475 

476<h3 id="practical-examples">

477 실용적인 예제

478</h3>

479 

480<h4 id="pull-request-review-command">

481 풀 리퀘스트 리뷰 명령어

482</h4>

483 

484`.claude/commands/review-pr.md`를 생성합니다:

485 

486```markdown theme={null}

487allowed-tools: Read, Grep, Glob, Bash(git diff *)

488description: Comprehensive code review

489 

490## Changed Files

491!`git diff --name-only HEAD~1`

492 

493## Detailed Changes

494!`git diff HEAD~1`

495 

496## Review Checklist

497 

498Review the above changes for:

4991. Code quality and readability

5002. Security vulnerabilities

5013. Performance implications

5024. Test coverage

5035. Documentation completeness

504 

505Provide specific, actionable feedback organized by priority.

506```

507 

508<Note>

509 Claude Code에는 번들된 `code-review` 및 `verify` 스킬이 포함되어 있습니다. 예를 들어 `.claude/commands/code-review.md`와 같이 사용자 정의 명령어의 이름을 이 중 하나로 지정하면, 사용자 정의 명령어가 번들된 스킬을 가리고 `slash_commands`는 이름을 한 번만 나열합니다.

510</Note>

511 

512<h4 id="test-runner-command">

513 테스트 러너 명령어

514</h4>

515 

516`.claude/commands/test.md` 생성:

517 

518```markdown theme={null}

519allowed-tools: Bash, Read, Edit

520argument-hint: [test-pattern]

521description: Run tests with optional pattern

522 

523Run tests matching pattern: $ARGUMENTS

524 

5251. Detect the test framework (Jest, pytest, etc.)

5262. Run tests with the provided pattern

5273. If tests fail, analyze and fix them

5284. Re-run to verify fixes

529```

530 

531SDK를 통해 이러한 명령어를 사용합니다:

532 

533<CodeGroup>

534 ```typescript TypeScript theme={null}

535 import { query } from "@anthropic-ai/claude-agent-sdk";

536 

537 // 코드 리뷰 실행

538 try {

539 for await (const message of query({

540 prompt: "/review-pr",

541 options: { maxTurns: 3 }

542 })) {

543 // 리뷰 피드백 처리

544 }

545 } catch (error) {

546 // 단일 쿼리 query()는 오류 결과를 반환한 후 throw하므로,

547 // 아래의 두 번째 쿼리는 여전히 실행됩니다.

548 console.error(`Session ended with an error: ${error}`);

549 }

550 

551 // 특정 테스트 실행

552 for await (const message of query({

553 prompt: "/test auth",

554 options: { maxTurns: 5 }

555 })) {

556 // 테스트 결과 처리

557 }

558 ```

559 

560 ```python Python theme={null}

561 import asyncio

562 from claude_agent_sdk import query, ClaudeAgentOptions

563 

564 

565 async def main():

566 # 코드 리뷰 실행

567 try:

568 async for message in query(prompt="/review-pr", options=ClaudeAgentOptions(max_turns=3)):

569 # 리뷰 피드백 처리

570 pass

571 except Exception as error:

572 # 단일 쿼리 query()는 오류 결과를 반환한 후 raise하므로,

573 # 아래의 두 번째 쿼리는 여전히 실행됩니다.

574 print(f"Session ended with an error: {error}")

575 

576 # 특정 테스트 실행

577 async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)):

578 # 테스트 결과 처리

579 pass

580 

581 

582 asyncio.run(main())

583 ```

584</CodeGroup>

585 

586<h2 id="see-also">

587 참고 항목

588</h2>

589 

590* [Slash Commands](/ko/skills) - 완전한 슬래시 명령어 문서

591* [SDK의 서브에이전트](/ko/agent-sdk/subagents) - 서브에이전트를 위한 유사한 파일 시스템 기반 구성

592* [TypeScript SDK 참조](/ko/agent-sdk/typescript) - 완전한 API 문서

593* [SDK 개요](/ko/agent-sdk/overview) - 일반 SDK 개념

594* [CLI 참조](/ko/cli-reference) - 명령줄 인터페이스