> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Slash Commands im SDK

> Erfahren Sie, wie Sie Slash Commands verwenden, um Claude Code-Sitzungen über das SDK zu steuern

Slash Commands bieten eine Möglichkeit, Claude Code-Sitzungen mit speziellen Befehlen zu steuern, die mit `/` beginnen. Diese Befehle können über das SDK gesendet werden, um Aktionen wie das Komprimieren von Kontext, das Auflisten der Kontextnutzung oder das Aufrufen benutzerdefinierter Befehle auszuführen. Nur Befehle, die ohne ein interaktives Terminal funktionieren, können über das SDK versendet werden; die `system/init`-Nachricht listet die in Ihrer Sitzung verfügbaren auf.

<h2 id="discovering-available-slash-commands">
  Verfügbare Slash Commands entdecken
</h2>

Das Claude Agent SDK stellt Informationen über verfügbare Slash Commands in der Systeminitalisierungsnachricht bereit. Greifen Sie auf diese Informationen zu, wenn Ihre Sitzung startet:

<CodeGroup>
  ```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);
      // Includes built-in commands plus bundled skills, for example:
      // ["clear", "compact", "context", "usage", "code-review", "verify", ...]
    }
  }
  ```

  ```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"])
              # Includes built-in commands plus bundled skills, for example:
              # ["clear", "compact", "context", "usage", "code-review", "verify", ...]


  asyncio.run(main())
  ```
</CodeGroup>

<h2 id="sending-slash-commands">
  Slash Commands senden
</h2>

Senden Sie Slash Commands, indem Sie sie in Ihre Eingabeaufforderung einbeziehen, genau wie normalen Text. Befehle, die auf der Konversationsverlauf wirken, wie `/compact`, benötigen vorherige Nachrichten zum Arbeiten, daher fragen die folgenden Beispiele zunächst eine Frage und senden dann den Befehl als Folgemaßnahme zur gleichen Konversation:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Build up conversation history first
  try {
    for await (const message of query({
      prompt: "What does the README in this directory cover?",
      options: { maxTurns: 2 }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(message.result);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the follow-up query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Send a slash command as a follow-up to the same conversation
  for await (const message of query({
    prompt: "/compact",
    options: { continue: true, maxTurns: 1 }
  })) {
    if (message.type === "result") {
      console.log("Command executed, result subtype:", message.subtype);
      // Example output: Command executed, result subtype: success
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


  async def main():
      # Build up conversation history first
      try:
          async for message in query(
              prompt="What does the README in this directory cover?",
              options=ClaudeAgentOptions(max_turns=2),
          ):
              if isinstance(message, ResultMessage) and message.subtype == "success":
                  print(message.result)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the follow-up query below still runs.
          print(f"Session ended with an error: {error}")

      # Send a slash command as a follow-up to the same conversation
      async for message in query(
          prompt="/compact",
          options=ClaudeAgentOptions(continue_conversation=True, max_turns=1),
      ):
          if isinstance(message, ResultMessage):
              print("Command executed, result subtype:", message.subtype)
              # Example output: Command executed, result subtype: success


  asyncio.run(main())
  ```
</CodeGroup>

<Note>
  Eine Abfrage kann mit einem Fehler-Ergebnis enden, beispielsweise wenn das Limit `maxTurns` / `max_turns` erreicht wird, bevor die Arbeit abgeschlossen ist. Die endgültige Ergebnisnachricht hat dann `is_error: true` und einen Fehler-Subtyp wie `error_max_turns` statt `success`.

  Nach dem Ausgeben dieser endgültigen Ergebnisnachricht wirft das SDK einen Fehler, da der CLI-Prozess mit einem Nicht-Null-Code beendet wird.

  Umhüllen Sie die Schleife in einem `try`/`catch` in TypeScript oder `try`/`except` in Python, wenn Ihr Befehl das Limit erreichen könnte, wie in [Single Message Input](/de/agent-sdk/streaming-vs-single-mode#single-message-input) gezeigt, oder setzen Sie `maxTurns` hoch genug, damit die Arbeit abgeschlossen wird. In Python fangen Sie `Exception`: Das SDK zeigt Fehler-Ergebnisse als einfache `Exception`.
</Note>

<h2 id="common-slash-commands">
  Häufige Slash Commands
</h2>

<h3 id="/compact-compact-conversation-history">
  `/compact` - Konversationsverlauf komprimieren
</h3>

Der `/compact`-Befehl reduziert die Größe Ihres Konversationsverlaufs, indem er ältere Nachrichten zusammenfasst und dabei wichtigen Kontext bewahrt. Die Komprimierung benötigt eine vorhandene Konversation mit mindestens zwei vorherigen Austauschvorgängen zum Zusammenfassen. Dieses Beispiel zeigt zunächst eine Konversation, komprimiert sie dann und liest die `compact_boundary`-Systemnachricht, die das Ergebnis meldet:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Compaction needs existing history, so have a conversation first
  try {
    for await (const message of query({
      prompt: "Explain what this project does",
      options: { maxTurns: 2 }
    })) {
      if (message.type === "result" && message.subtype === "success") {
        console.log(message.result);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the follow-up query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // Compact the same conversation
  for await (const message of query({
    prompt: "/compact",
    options: { continue: true, 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);
      // Example output:
      // Compaction completed
      // Pre-compaction tokens: 1842
      // Trigger: manual
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage, SystemMessage


  async def main():
      # Compaction needs existing history, so have a conversation first
      try:
          async for message in query(
              prompt="Explain what this project does",
              options=ClaudeAgentOptions(max_turns=2),
          ):
              if isinstance(message, ResultMessage) and message.subtype == "success":
                  print(message.result)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the follow-up query below still runs.
          print(f"Session ended with an error: {error}")

      # Compact the same conversation
      async for message in query(
          prompt="/compact",
          options=ClaudeAgentOptions(continue_conversation=True, 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"])
              # Example output:
              # Compaction completed
              # Pre-compaction tokens: 1842
              # Trigger: manual


  asyncio.run(main())
  ```
</CodeGroup>

<Note>
  Eine `compact_boundary`-Nachricht kommt nur an, wenn die Komprimierung ausgeführt wurde. Wenn es nichts zu zusammenfassen gibt, meldet `/compact` stattdessen den Grund: Der Durchlauf endet immer noch mit einem `success`-Ergebnis, es wird keine `compact_boundary`-Nachricht ausgegeben, und der Ergebnistext enthält die Nachricht, zum Beispiel `Not enough messages to compact.` nach einem einzelnen kurzen Austausch. Ein neuer einmaliger `query()`-Aufruf startet mit leerem Kontext, daher verwenden Sie dieses Muster in einer Sitzung mit vorherigen Durchläufen, zum Beispiel im [Streaming-Eingabemodus](/de/agent-sdk/streaming-vs-single-mode) oder beim Fortsetzen einer Sitzung.
</Note>

<h3 id="/clear-reset-conversation-context">
  `/clear` - Konversationskontext zurücksetzen
</h3>

Der `/clear`-Befehl setzt die Konversation auf einen leeren Kontext zurück, sodass nachfolgende Eingabeaufforderungen ohne vorherigen Konversationsverlauf starten. Die vorherige Konversation bleibt auf der Festplatte gespeichert und kann durch Übergabe ihrer Sitzungs-ID an die [`resume`-Option](/de/agent-sdk/sessions#resume-by-id) wieder aufgerufen werden.

Dies ist nützlich im [Streaming-Eingabemodus](/de/agent-sdk/streaming-vs-single-mode), in dem Sie mehrere Eingabeaufforderungen über eine einzelne Verbindung senden. Für einmalige `query()`-Aufrufe startet jeder Aufruf bereits mit leerem Kontext, daher hat das Senden von `/clear` keine praktische Auswirkung; starten Sie stattdessen eine neue `query()`.

<Note>
  `/clear` im SDK erfordert Claude Code v2.1.117 oder später. In früheren Versionen wird es aus `slash_commands` weggelassen.
</Note>

<h2 id="creating-custom-slash-commands">
  Benutzerdefinierte Slash Commands erstellen
</h2>

Zusätzlich zur Verwendung integrierter Slash Commands können Sie Ihre eigenen benutzerdefinierten Befehle erstellen, die über das SDK verfügbar sind. Benutzerdefinierte Befehle werden als Markdown-Dateien in bestimmten Verzeichnissen definiert, ähnlich wie Subagenten konfiguriert werden.

<Note>
  Das `.claude/commands/`-Verzeichnis ist das Legacy-Format. Das empfohlene Format ist `.claude/skills/<name>/SKILL.md`, das die gleiche Slash-Command-Aufrufe (`/name`) plus autonome Aufrufe durch Claude unterstützt. Siehe [Skills](/de/agent-sdk/skills) für das aktuelle Format. Die CLI unterstützt weiterhin beide Formate, und die folgenden Beispiele bleiben für `.claude/commands/` genau.
</Note>

<h3 id="file-locations">
  Dateispeicherorte
</h3>

Benutzerdefinierte Slash Commands werden in bestimmten Verzeichnissen basierend auf ihrem Umfang gespeichert:

* **Projektbefehle**: `.claude/commands/` - Nur im aktuellen Projekt verfügbar (Legacy; bevorzugen Sie `.claude/skills/`)
* **Persönliche Befehle**: `~/.claude/commands/` - Verfügbar in allen Ihren Projekten (Legacy; bevorzugen Sie `~/.claude/skills/`)

<h3 id="file-format">
  Dateiformat
</h3>

Jeder benutzerdefinierte Befehl ist eine Markdown-Datei, bei der:

* Der Dateiname (ohne `.md`-Erweiterung) zum Befehlsnamen wird
* Der Dateiinhalt definiert, was der Befehl tut
* Optionale YAML-Frontmatter bietet Konfiguration

<h4 id="basic-example">
  Grundlegendes Beispiel
</h4>

Erstellen Sie das `.claude/commands`-Verzeichnis in Ihrem Projekt, falls es nicht vorhanden ist, und erstellen Sie dann `.claude/commands/refactor.md`:

```markdown theme={null}
Refactor the selected code to improve readability and maintainability.
Focus on clean code principles and best practices.
```

Dies erstellt den `/refactor`-Befehl, den Sie über das SDK verwenden können.

<h4 id="with-frontmatter">
  Mit Frontmatter
</h4>

Erstellen Sie `.claude/commands/security-check.md`:

```markdown theme={null}
---
allowed-tools: Read, Grep, Glob
description: Run security vulnerability scan
model: claude-opus-4-8
---

Analyze the codebase for security vulnerabilities including:
- SQL injection risks
- XSS vulnerabilities
- Exposed credentials
- Insecure configurations
```

<h3 id="using-custom-commands-in-the-sdk">
  Benutzerdefinierte Commands im SDK verwenden
</h3>

Sobald sie im Dateisystem definiert sind, sind benutzerdefinierte Befehle automatisch über das SDK verfügbar:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Use a custom command
  try {
    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);
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the second query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // 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") {
      console.log("Available commands:", message.slash_commands);
      // Includes built-in commands plus bundled skills and your custom commands, for example:
      // ["clear", "compact", "context", "usage", "code-review", "verify", "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
      try:
          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)
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the second query below still runs.
          print(f"Session ended with an error: {error}")

      # 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":
              print("Available commands:", message.data["slash_commands"])
              # Includes built-in commands plus bundled skills and your custom commands, for example:
              # ["clear", "compact", "context", "usage", "code-review", "verify", "refactor", "security-check", ...]


  asyncio.run(main())
  ```
</CodeGroup>

<h3 id="advanced-features">
  Erweiterte Funktionen
</h3>

<h4 id="arguments-and-placeholders">
  Argumente und Platzhalter
</h4>

Benutzerdefinierte Befehle unterstützen dynamische Argumente mit Platzhaltern:

Erstellen Sie `.claude/commands/fix-issue.md`:

```markdown theme={null}
---
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.
```

Verwendung im SDK:

<CodeGroup>
  ```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())
  ```
</CodeGroup>

<h4 id="bash-command-execution">
  Bash-Befehlsausführung
</h4>

Benutzerdefinierte Befehle können Bash-Befehle ausführen und deren Ausgabe einbeziehen:

Erstellen Sie `.claude/commands/git-commit.md`:

```markdown theme={null}
---
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.
```

<h4 id="file-references">
  Dateireferenzen
</h4>

Beziehen Sie Dateiinhalte mit dem `@`-Präfix ein:

Erstellen Sie `.claude/commands/review-config.md`:

```markdown theme={null}
---
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.
```

<h3 id="organization-with-namespacing">
  Organisation mit Namensräumen
</h3>

Organisieren Sie Befehle in Unterverzeichnissen für bessere Struktur:

```bash theme={null}
.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)
```

Das Unterverzeichnis wird in der Befehlsbeschreibung angezeigt, beeinflusst aber nicht den Befehlsnamen selbst.

<h3 id="practical-examples">
  Praktische Beispiele
</h3>

<h4 id="pull-request-review-command">
  Pull-Request-Review-Befehl
</h4>

Erstellen Sie `.claude/commands/review-pr.md`:

```markdown theme={null}
---
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.
```

<Note>
  Claude Code enthält gebündelte `code-review`- und `verify`-Skills. Wenn Sie einen benutzerdefinierten Befehl nach einem von ihnen benennen, z. B. `.claude/commands/code-review.md`, überschattet Ihr Befehl den gebündelten Skill und `slash_commands` listet den Namen einmal auf.
</Note>

<h4 id="test-runner-command">
  Test Runner-Befehl
</h4>

Erstellen Sie `.claude/commands/test.md`:

```markdown theme={null}
---
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
```

Verwenden Sie diese Befehle über das SDK:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { query } from "@anthropic-ai/claude-agent-sdk";

  // Run code review
  try {
    for await (const message of query({
      prompt: "/review-pr",
      options: { maxTurns: 3 }
    })) {
      // Process review feedback
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result,
    // so the second query below still runs.
    console.error(`Session ended with an error: ${error}`);
  }

  // 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
      try:
          async for message in query(prompt="/review-pr", options=ClaudeAgentOptions(max_turns=3)):
              # Process review feedback
              pass
      except Exception as error:
          # A single-shot query() raises after yielding an error result,
          # so the second query below still runs.
          print(f"Session ended with an error: {error}")

      # Run specific tests
      async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)):
          # Handle test results
          pass


  asyncio.run(main())
  ```
</CodeGroup>

<h2 id="see-also">
  Siehe auch
</h2>

* [Slash Commands](/de/skills) - Vollständige Dokumentation zu Slash Commands
* [Subagenten im SDK](/de/agent-sdk/subagents) - Ähnliche dateisystembasierte Konfiguration für Subagenten
* [TypeScript SDK-Referenz](/de/agent-sdk/typescript) - Vollständige API-Dokumentation
* [SDK-Übersicht](/de/agent-sdk/overview) - Allgemeine SDK-Konzepte
* [CLI-Referenz](/de/cli-reference) - Befehlszeilenschnittstelle
