Skip to main content
guidesSource-backed

Slash Commands in Claude Agent SDK Sessions

A practical walkthrough of slash commands in the Claude Agent SDK. Read the slash_commands array from the system init message, dispatch a command by placing it in the prompt string, handle built-ins like /compact and /clear, and author your own as SKILL.md files with allowed-tools frontmatter.

by JPette1783·added 2026-06-05·
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/agent-sdk/slash-commands, https://github.com/JSONbored/awesome-claude/blob/main/content/guides/slash-commands-in-claude-agent-sdk-sessions.mdx
Safety notes
Only non-interactive commands are dispatchable through the SDK; the system init message lists which are available in your session., Custom commands can run bash and reference files; scope their allowed-tools frontmatter and review what each command does., Commands that embed bash output or file contents send that data to the model; keep secrets out of referenced files.
Privacy notes
Slash command definitions and any embedded file or bash output are sent to the model provider as prompt content., Custom command files live on disk in .claude/; avoid putting credentials in them or in files they reference with @., Built-in /compact summarizes history; the summary still goes to the provider like the rest of the session.
Author
JPette1783
Submitted by
JPette1783
Claim status
unclaimed
Last verified
2026-06-05

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

63

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Needs review

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    No reviewed flag detected in metadata.

    Pending

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

Copy & paste

Copy-ready — paste the snippet to get started.

Adoption plan

Balanced adoption plan

Current risk score 24/100. Use staged verification before broader rollout.

Risk 24

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    No review metadata found; increase manual validation.

    Pending
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Missing required evidence: Metadata review. Risk score 31.

Risk 31

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Missing

Review metadata is missing.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required gaps: Metadata review

Decision timeline

Decision timeline · balanced

Blocking gaps: Check metadata review status. Risk 28.

Risk 28

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is missing.

Pending

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

Blockers: Check metadata review status

Prerequisite readiness

Prerequisite readiness

3 prerequisites to line up before setup.

0/3 ready
Install & runtime1General2

Safety & privacy surface

Safety & privacy surface

3 safety and 3 privacy notes across 3 risk areas. Review closely: credentials & tokens, permissions & scopes, third-party handling.

3 areas
  • SafetyCredentials & tokensOnly non-interactive commands are dispatchable through the SDK; the system init message lists which are available in your session.
  • SafetyPermissions & scopesCustom commands can run bash and reference files; scope their allowed-tools frontmatter and review what each command does.
  • SafetyCredentials & tokensCommands that embed bash output or file contents send that data to the model; keep secrets out of referenced files.
  • PrivacyThird-party handlingSlash command definitions and any embedded file or bash output are sent to the model provider as prompt content.
  • PrivacyCredentials & tokensCustom command files live on disk in .claude/; avoid putting credentials in them or in files they reference with @.
  • PrivacyCredentials & tokensBuilt-in /compact summarizes history; the summary still goes to the provider like the rest of the session.

Safety notes

  • Only non-interactive commands are dispatchable through the SDK; the system init message lists which are available in your session.
  • Custom commands can run bash and reference files; scope their allowed-tools frontmatter and review what each command does.
  • Commands that embed bash output or file contents send that data to the model; keep secrets out of referenced files.

Privacy notes

  • Slash command definitions and any embedded file or bash output are sent to the model provider as prompt content.
  • Custom command files live on disk in .claude/; avoid putting credentials in them or in files they reference with @.
  • Built-in /compact summarizes history; the summary still goes to the provider like the rest of the session.

Prerequisites

  • The Claude Agent SDK installed for Python or TypeScript.
  • For custom commands, a .claude/skills/ or legacy .claude/commands/ directory.
  • Awareness that only commands that work without an interactive terminal are dispatchable through the SDK.

Schema details

Install type
copy
Troubleshooting
No
Full copyable content
## Overview

Slash commands control a Claude Agent SDK session with special `/` 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.

## Discover available commands

```typescript
for await (const message of query({ prompt: "Hello", options: { maxTurns: 1 } })) {
  if (message.type === "system" && message.subtype === "init") {
    console.log("Available slash commands:", message.slash_commands);
    // e.g. ["clear", "compact", "context", "usage"]
  }
}
```

## Send a command

Send a slash command by putting it in the prompt string:

```typescript
for await (const message of query({ prompt: "/compact", options: { maxTurns: 1 } })) {
  if (message.type === "result" && message.subtype === "success") {
    console.log("Command executed:", message.result);
  }
}
```

Common built-ins include `/compact` (summarize history; emits a
`compact_boundary` system message with `pre_tokens`) and `/clear` (reset context;
useful in streaming-input mode, requires v2.1.117+). For one-shot `query()` calls
`/clear` has no effect since each call starts empty.

## Define custom commands

Custom commands are markdown files; the filename becomes the command name. The
recommended format is `.claude/skills/<name>/SKILL.md` (which also supports
autonomous invocation); `.claude/commands/` is the legacy format and still works.

```markdown
---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
---

Analyze the codebase for security vulnerabilities including SQL injection,
XSS, exposed credentials, and insecure configurations.
```

Custom commands support arguments (`$0`, `$1`, `$ARGUMENTS`), embedded bash output
(`` !`git status` ``), and file references (`@package.json`). They appear in the
`slash_commands` list and are invoked like built-ins:

```typescript
for await (const message of query({ prompt: "/security-check", options: { maxTurns: 3 } })) {
  /* ... */
}
```

## Organization

Group commands in subdirectories (for example `.claude/commands/frontend/`); the
subdirectory shows in the description but not the command name.

## Source

- Slash Commands in the SDK: https://code.claude.com/docs/en/agent-sdk/slash-commands

About this resource

Overview

Slash commands control a Claude Agent SDK session with special / 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.

Discover available commands

for await (const message of query({ prompt: "Hello", options: { maxTurns: 1 } })) {
  if (message.type === "system" && message.subtype === "init") {
    console.log("Available slash commands:", message.slash_commands);
    // e.g. ["clear", "compact", "context", "usage"]
  }
}

Send a command

Send a slash command by putting it in the prompt string:

for await (const message of query({ prompt: "/compact", options: { maxTurns: 1 } })) {
  if (message.type === "result" && message.subtype === "success") {
    console.log("Command executed:", message.result);
  }
}

Common built-ins include /compact (summarize history; emits a compact_boundary system message with pre_tokens) and /clear (reset context; useful in streaming-input mode, requires v2.1.117+). For one-shot query() calls /clear has no effect since each call starts empty.

Define custom commands

Custom commands are markdown files; the filename becomes the command name. The recommended format is .claude/skills/<name>/SKILL.md (which also supports autonomous invocation); .claude/commands/ is the legacy format and still works.

---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
---

Analyze the codebase for security vulnerabilities including SQL injection,
XSS, exposed credentials, and insecure configurations.

Custom commands support arguments ($0, $1, $ARGUMENTS), embedded bash output (!`git status`), and file references (@package.json). They appear in the slash_commands list and are invoked like built-ins:

for await (const message of query({ prompt: "/security-check", options: { maxTurns: 3 } })) {
  /* ... */
}

Organization

Group commands in subdirectories (for example .claude/commands/frontend/); the subdirectory shows in the description but not the command name.

Source

Source citations

Add this badge to your README

Show that Slash Commands in Claude Agent SDK Sessions is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/guides/slash-commands-in-claude-agent-sdk-sessions.svg)](https://heyclau.de/entry/guides/slash-commands-in-claude-agent-sdk-sessions)

How it compares

Slash Commands in Claude Agent SDK Sessions side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

2 trust signals differ across this comparison (Source provenance, Submitter).

Field

A practical walkthrough of slash commands in the Claude Agent SDK. Read the slash_commands array from the system init message, dispatch a command by placing it in the prompt string, handle built-ins like /compact and /clear, and author your own as SKILL.md files with allowed-tools frontmatter.

Open dossier

A practical walkthrough of defining in-process custom tools for the Claude Agent SDK with createSdkMcpServer and the tool helper, wiring them into query via mcpServers, allowing them, error handling, and returning images or structured data.

Open dossier

How to design custom tools for the Claude Agent SDK: in-process tool definitions with typed input schemas, permission scoping, structured isError results, and when to reach for an external MCP server instead.

Open dossier

A practical walkthrough of mirroring Claude Agent SDK session transcripts to external storage: the SessionStore interface, the SessionKey shape, resuming across hosts, reference adapters for S3/Redis/Postgres, and behavior notes.

Open dossier
Next steps
Trust
Review statusNot reviewedNot reviewedNot reviewedNot reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceDiffersSource-backedSource-backedSubmission linkedSource submissionSource-backed
SubmitterDiffersJPette1783JPette1783kiannidevJPette1783
Install riskReview firstReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
Brand
Categoryguidesguidesguidesguides
SourceSource-backedSource-backedSource-backedSource-backed
AuthorJPette1783JPette1783kiannidevJPette1783
Added2026-06-052026-06-052026-06-142026-06-05
Platforms
Harness
Source repo
Safety notesOnly non-interactive commands are dispatchable through the SDK; the system init message lists which are available in your session. Custom commands can run bash and reference files; scope their allowed-tools frontmatter and review what each command does. Commands that embed bash output or file contents send that data to the model; keep secrets out of referenced files.Custom tool handlers run your code in-process whenever Claude calls them; validate inputs and gate destructive actions inside the handler. List each tool in allowedTools (mcp__server__tool) so it runs without a prompt only when you intend; otherwise it goes through the permission flow. Return isError instead of throwing so a failed tool keeps the agent loop alive rather than crashing the whole query. Tool annotations like readOnlyHint are metadata, not enforcement; keep them accurate to what the handler actually does.Tool descriptions are not enforcement—validate destructive inputs inside handlers. Wildcard `mcp__server__*` allowlists expand blast radius; prefer per-tool grants in production. Returning thrown exceptions fails the whole query; use isError responses for recoverable faults.The store is a mirror, not a replacement: the CLI writes locally first, then append() forwards. sessionStore cannot combine with persistSession: false or enableFileCheckpointing. Mirror writes are best-effort; a failed append emits a system mirror_error message and the query continues, so monitor for mirror_error to detect store data loss. Deleting the main session key must cascade to subagent subkeys; implement delete carefully or treat the backend as append-only.
Privacy notesSlash command definitions and any embedded file or bash output are sent to the model provider as prompt content. Custom command files live on disk in .claude/; avoid putting credentials in them or in files they reference with @. Built-in /compact summarizes history; the summary still goes to the provider like the rest of the session.In-process tools run inside your application, so data they touch stays in your process unless the handler sends it elsewhere. Tool descriptions, inputs, and results are sent to the model provider as part of the conversation; avoid placing secrets in them. Every tool definition consumes context on each turn; for large tool sets, load them on demand rather than sending all schemas.Tool schemas and results enter model context every turn—avoid secrets in descriptions or payloads. Large tool sets increase context usage; defer rarely used tools via tool search. Structured outputs may log to host telemetry—redact customer fields at the handler boundary.Transcripts contain the full conversation, tool inputs, and outputs; store them in a backend you govern with your own encryption, access controls, and retention. The SDK never deletes from your store; retention (TTLs, S3 lifecycle, scheduled cleanup) is your responsibility. Keep backend credentials out of code; pass a pre-configured client to the adapter so you control TLS, region, and pooling.
Prerequisites
  • The Claude Agent SDK installed for Python or TypeScript.
  • For custom commands, a .claude/skills/ or legacy .claude/commands/ directory.
  • Awareness that only commands that work without an interactive terminal are dispatchable through the SDK.
  • The Claude Agent SDK installed for Python (claude-agent-sdk) or TypeScript (@anthropic-ai/claude-agent-sdk).
  • For TypeScript, Zod for input schemas; for Python, a dict or JSON Schema per tool.
  • An Anthropic API key or other configured provider credentials for the SDK.
  • Claude Agent SDK installed and a running `query` loop in TypeScript or Python.
  • Zod (TS) or JSON Schema (Python) literacy for tool input contracts.
  • A written list of side effects each custom tool may perform.
  • Decision record template for build vs buy on external MCP integrations.
  • The Claude Agent SDK installed for Python or TypeScript.
  • An external backend (S3, Redis, a database) and its client library.
  • A working-directory layout where local transcript writes are available (the store mirrors them).
Install
Config
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.