### Use Git with Claude Code Source: https://docs.claude.com/en/docs/claude-code/quickstart Examples of conversational Git commands supported by Claude Code. Users can inquire about changed files, commit changes, create branches, view commit history, and get help with merge conflicts. ```text > what files have I changed? > commit my changes with a descriptive message > create a new branch called feature/quickstart > show me the last 5 commits > help me resolve merge conflicts ``` -------------------------------- ### Install Claude Code using Windows CMD Source: https://docs.claude.com/en/docs/claude-code/quickstart Installs Claude Code on Windows using the Command Prompt (CMD) by downloading an executable script, running it, and then cleaning up the installer file. This method ensures installation on Windows systems. ```batch curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd ``` -------------------------------- ### Claude Code: Common Development Task Examples Source: https://docs.claude.com/en/docs/claude-code/quickstart Examples of natural language prompts for common development workflows with Claude Code. These prompts guide the AI in tasks such as code refactoring, test generation, documentation updates, and code review. ```natural-language > refactor the authentication module to use async/await instead of callbacks ``` ```natural-language > write unit tests for the calculator functions ``` ```natural-language > update the README with installation instructions ``` ```natural-language > review my changes and suggest improvements ``` -------------------------------- ### Ask Claude Code about the project Source: https://docs.claude.com/en/docs/claude-code/quickstart Examples of natural language queries to understand the project. Claude Code can analyze files to provide summaries, identify technologies, locate entry points, and explain folder structures. ```text > what does this project do? > what technologies does this project use? > where is the main entry point? > explain the folder structure ``` -------------------------------- ### Ask Claude Code about its capabilities Source: https://docs.claude.com/en/docs/claude-code/quickstart Examples of natural language queries to understand Claude Code's features. Users can ask about its general capabilities, usage of slash commands, and compatibility with tools like Docker. ```text > what can Claude Code do? > how do I use slash commands in Claude Code? > can Claude Code work with Docker? ``` -------------------------------- ### Start a Claude Code session Source: https://docs.claude.com/en/docs/claude-code/quickstart Starts an interactive session with Claude Code within a project directory. After logging in, this command activates the AI assistant for coding tasks. ```bash cd /path/to/your/project claude ``` -------------------------------- ### Claude Code: Exploration and Analysis Prompts Source: https://docs.claude.com/en/docs/claude-code/quickstart Examples of prompts for Claude Code to analyze existing codebases or data. These prompts encourage the AI to understand the project's structure and identify patterns before making changes. ```natural-language > analyze the database schema ``` ```natural-language > build a dashboard showing products that are most frequently returned by our UK customers ``` -------------------------------- ### Request code changes with Claude Code Source: https://docs.claude.com/en/docs/claude-code/quickstart Example of a natural language prompt to add a simple function to the main file. Claude Code will identify the file, propose changes, seek approval, and then implement the edit. ```text > add a hello world function to the main file ``` -------------------------------- ### Claude Code: Essential CLI Commands Source: https://docs.claude.com/en/docs/claude-code/quickstart Key command-line interface commands for interacting with Claude Code. These commands cover starting interactive mode, running one-time tasks, continuing conversations, committing code, and accessing help. ```bash claude ``` ```bash claude "task" ``` ```bash claude -p "query" ``` ```bash claude -c ``` ```bash claude -r ``` ```bash claude commit ``` ```bash > /clear ``` ```bash > /help ``` ```bash > exit ``` ```bash Ctrl+C ``` -------------------------------- ### Fix bugs or add features with Claude Code Source: https://docs.claude.com/en/docs/claude-code/quickstart Examples of natural language prompts for debugging and feature implementation. Claude Code can locate relevant code, understand context, implement solutions, and potentially run tests. ```text > add input validation to the user registration form > there's a bug where users can submit empty forms - fix it ``` -------------------------------- ### Start Claude Code in a project Source: https://docs.claude.com/en/docs/claude-code/setup Navigates to a project directory and initiates the Claude Code command-line interface. This command is run after successful installation. ```bash cd your-awesome-project claude ``` -------------------------------- ### Log in to Claude Code Source: https://docs.claude.com/en/docs/claude-code/quickstart Initiates the login process for Claude Code. This command should be run within the terminal, and the user will be prompted to log in via their account on first use. ```bash claude # You'll be prompted to log in on first use ``` -------------------------------- ### Install Claude Agent SDK (Python) Source: https://docs.claude.com/en/docs/claude-code/sdk Command to install the new claude-agent-sdk package for Python projects using pip. ```bash pip install claude-agent-sdk ``` -------------------------------- ### Start Claude Code in a Project Directory Source: https://docs.claude.com/en/docs/claude-code/overview Initiates the Claude Code interactive terminal session within your project directory. After installation, navigate to your project's root folder and run the `claude` command to start interacting with the tool. ```bash cd your-project claude ``` -------------------------------- ### Claude Code: Step-by-Step Task Decomposition Source: https://docs.claude.com/en/docs/claude-code/quickstart Demonstrates breaking down complex tasks into sequential steps for Claude Code. This approach ensures clarity and allows the AI to manage multi-stage development processes effectively. ```natural-language > 1. create a new database table for user profiles ``` ```natural-language > 2. create an API endpoint to get and update user profiles ``` ```natural-language > 3. build a webpage that allows users to see and edit their information ``` -------------------------------- ### Install Claude Agent SDK (TypeScript/JavaScript) Source: https://docs.claude.com/en/docs/claude-code/sdk Command to install the new Claude Agent SDK package for TypeScript/JavaScript projects using npm. ```bash npm install @anthropic-ai/claude-agent-sdk ``` -------------------------------- ### Markdown Formatting Hook Example Reference Source: https://docs.claude.com/en/docs/claude-code/troubleshooting Provides a reference to an example implementation for a markdown formatting hook, which can be used to automatically detect and add missing language tags to code blocks. ```text /en/docs/claude-code/hooks-guide#markdown-formatting-hook ``` -------------------------------- ### Install Claude Code via Shell Script (Bash) Source: https://docs.claude.com/en/docs/claude-code/setup Installs Claude Code using a curl command to download and execute an installation script. Supports installing a specific version number. ```bash curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58 ``` -------------------------------- ### Configure Automatic Dependency Installation with SessionStart Hooks Source: https://docs.claude.com/en/docs/claude-code/claude-code-on-the-web This JSON configuration sets up a 'SessionStart' hook to automatically run a script for installing project dependencies when a new session begins. It specifies a 'startup' matcher and defines the command to execute, pointing to a shell script for package installation. ```json { "hooks": { "SessionStart": [ { "matcher": "startup", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh" } ] } ] } } ``` -------------------------------- ### Install Claude Code via PowerShell Source: https://docs.claude.com/en/docs/claude-code/setup Installs Claude Code on Windows using PowerShell. Supports installing the stable (default), latest, or a specific version number. ```powershell # Install stable version (default) irm https://claude.ai/install.ps1 | iex # Install latest version & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest # Install specific version number & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58 ``` -------------------------------- ### Re-authenticate Claude Code Source: https://docs.claude.com/en/docs/claude-code/quickstart Explicitly triggers the login prompt for Claude Code, allowing users to log in again or switch between accounts. This is useful if credentials change or multiple accounts are used. ```bash /login # Follow the prompts to log in with your account ``` -------------------------------- ### Install Claude Code via Windows CMD Source: https://docs.claude.com/en/docs/claude-code/setup Installs Claude Code on Windows using the Command Prompt (CMD). Downloads the script, executes it, and cleans up the downloaded file. Supports installing the stable, latest, or a specific version number. ```batch REM Install stable version (default) curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd REM Install latest version curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd latest && del install.cmd REM Install specific version number curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 1.0.58 && del install.cmd ``` -------------------------------- ### Install and Test Plugin Locally (Bash) Source: https://docs.claude.com/en/docs/claude-code/plugins These bash commands demonstrate how to install and test a locally developed plugin in Claude Code. It involves starting Claude Code, adding the local marketplace, installing the plugin, and then invoking a custom command. ```bash # Start Claude Code from parent directory cd .. claude # Add the test marketplace /plugin marketplace add ./test-marketplace # Install your plugin /plugin install my-first-plugin@test-marketplace # Try your new command /hello ``` -------------------------------- ### Bash Script for Installing Node.js and Python Packages Source: https://docs.claude.com/en/docs/claude-code/claude-code-on-the-web This bash script, designed to be executed by a SessionStart hook, handles the installation of project dependencies. It first runs 'npm install' for Node.js packages and then 'pip install -r requirements.txt' for Python packages, followed by exiting successfully. ```bash #!/bin/bash npm install pip install -r requirements.txt exit 0 ``` -------------------------------- ### Install a Plugin from a Local Marketplace (Shell) Source: https://docs.claude.com/en/docs/claude-code/plugin-marketplaces This command installs a plugin named 'test-plugin' from a specifically added local marketplace named 'my-local-marketplace'. This allows developers to test plugin installation from their local development environment. ```shell /plugin install test-plugin@my-local-marketplace ``` -------------------------------- ### Install a Specific Plugin in Claude Code Source: https://docs.claude.com/en/docs/claude-code/plugins This command installs a particular plugin directly from a marketplace. It requires the plugin name and optionally the marketplace it belongs to. This is useful for quick installations when the plugin name is known. The `theme={null}` parameter is a placeholder. ```shell /plugin install formatter@your-org ``` -------------------------------- ### Log Bash Commands with jq Hook Source: https://docs.claude.com/en/docs/claude-code/hooks-guide This hook logs the command and its description to a file before tool calls. It requires `jq` to be installed. The input is the tool's command and description, and the output is an appended line in a log file. ```bash jq -r '"(.tool_input.command) - (.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt ``` -------------------------------- ### Install Claude Code via curl script (macOS, Linux, WSL) Source: https://docs.claude.com/en/docs/claude-code/setup Installs Claude Code by downloading and executing an installation script using `curl`. This method is suitable for macOS, Linux, and Windows Subsystem for Linux (WSL) environments. ```bash curl -fsSL https://claude.ai/install.sh | bash ``` ```bash # Install latest version curl -fsSL https://claude.ai/install.sh | bash -s latest ``` -------------------------------- ### Example of Enabled Plugins Configuration in JSON Source: https://docs.claude.com/en/docs/claude-code/settings This JSON configuration snippet provides an example of enabling plugins for different purposes, such as code formatting and deployment tools. It illustrates the format for specifying plugin names, their associated marketplaces, and their activation status (true/false). ```json { "enabledPlugins": { "code-formatter@team-tools": true, "deployment-tools@team-tools": true, "experimental-features@personal": false } } ``` -------------------------------- ### SessionStart Hook Input Example (JSON) Source: https://docs.claude.com/en/docs/claude-code/hooks This JSON object represents the input for the 'SessionStart' hook. It contains session identifiers, the transcript path, permission mode, and the source of the session start. ```json { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "permission_mode": "default", "hook_event_name": "SessionStart", "source": "startup" } ``` -------------------------------- ### Start Claude in Plan Mode (Bash) Source: https://docs.claude.com/en/docs/claude-code/common-workflows This command initiates a new Claude session in Plan Mode, which allows for read-only code analysis and planning without making direct changes. It's useful for exploring codebases or planning complex refactors. Dependencies: Claude CLI installed. ```bash claude --permission-mode plan ``` -------------------------------- ### Multi-turn Legal Assistant with Claude CLI Source: https://docs.claude.com/en/docs/claude-code/headless This example demonstrates a multi-turn legal assistant using the Claude CLI with session persistence. It first starts a session to get a `session_id`, then uses this ID to resume the conversation for subsequent legal review steps, including contract review, compliance checks, and risk summarization. ```bash # Legal document review with session persistence session_id=$(claude -p "Start legal review session" --output-format json | jq -r '.session_id') # Review contract in multiple steps claude -p --resume "$session_id" "Review contract.pdf for liability clauses" claude -p --resume "$session_id" "Check compliance with GDPR requirements" claude -p --resume "$session_id" "Generate executive summary of risks" ``` -------------------------------- ### Command with All Arguments Placeholder ($ARGUMENTS) Source: https://docs.claude.com/en/docs/claude-code/slash-commands Shows how to define a command that captures all arguments passed to it using the $ARGUMENTS placeholder. The example includes the command definition and how the arguments are processed during usage. ```bash # Command definition echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md # Usage > /fix-issue 123 high-priority # $ARGUMENTS becomes: "123 high-priority" ``` -------------------------------- ### Install Test Plugin with Claude CLI Source: https://docs.claude.com/en/docs/claude-code/plugin-marketplaces This command installs a specific test plugin from a marketplace. You need to provide the plugin name and the marketplace name. This is useful for verifying plugin functionality in a controlled environment. ```shell /plugin install test-plugin@marketplace-name ``` -------------------------------- ### Install Plugin from Marketplace Source: https://docs.claude.com/en/docs/claude-code/plugin-marketplaces Installs a specified plugin from any of the configured or known plugin marketplaces. The format 'plugin-name@marketplace-name' allows targeting specific plugins from specific sources. ```shell /plugin install plugin-name@marketplace-name ``` -------------------------------- ### Fix WSL npm and Node.js Path Issues Source: https://docs.claude.com/en/docs/claude-code/troubleshooting Commands to resolve OS/platform detection and Node.js not found errors in WSL. This involves setting npm config for OS and forcing installation without OS checks. It also guides on fixing Node.js path issues by ensuring Linux installations are prioritized over Windows ones. ```bash npm config set os linux npm install -g @anthropic-ai/claude-code --force --no-os-check ``` ```bash # Load nvm if it exists export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion ``` ```bash source ~/.nvm/nvm.sh ``` ```bash export PATH="$HOME/.nvm/versions/node/$(node -v)/bin:$PATH" ``` -------------------------------- ### Example Script for Dynamic OpenTelemetry Headers Source: https://docs.claude.com/en/docs/claude-code/monitoring-usage An example bash script that generates dynamic OpenTelemetry headers in JSON format. This script demonstrates fetching a token and an API key to construct the header object. ```bash #!/bin/bash # Example: Multiple headers echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}" ``` -------------------------------- ### Enterprise MCP Server Configuration (JSON Example) Source: https://docs.claude.com/en/docs/claude-code/mcp An example JSON configuration file (`managed-mcp.json`) for enterprise-level management of MCP servers. This file defines which MCP servers are available, their types (http or stdio), and connection details like URLs, commands, arguments, and environment variables. ```json { "mcpServers": { "github": { "type": "http", "url": "https://api.githubcopilot.com/mcp/" }, "sentry": { "type": "http", "url": "https://mcp.sentry.dev/mcp" }, "company-internal": { "type": "stdio", "command": "/usr/local/bin/company-mcp-server", "args": ["--config", "/etc/company/mcp-config.json"], "env": { "COMPANY_API_URL": "https://internal.company.com" } } } } ``` -------------------------------- ### Browse Available Plugins in Claude Code Source: https://docs.claude.com/en/docs/claude-code/plugins This command opens the plugin management interface or lists available plugins, allowing users to discover and select plugins to install. It's the recommended method for finding new plugins. The `theme={null}` parameter is a placeholder. The output is interactive or a list of plugins. ```shell /plugin ``` -------------------------------- ### SlashCommand permission rule examples Source: https://docs.claude.com/en/docs/claude-code/slash-commands Provides examples of permission rule formats supported by the SlashCommand tool, including exact match and prefix match. These rules define which commands and arguments Claude is allowed to execute. ```text Exact match: `SlashCommand:/commit` (allows only `/commit` with no arguments) Prefix match: `SlashCommand:/review-pr:*` (allows `/review-pr` with any arguments) ``` -------------------------------- ### GitHub Actions Workflow File Example Source: https://docs.claude.com/en/docs/claude-code/github-actions This example demonstrates a basic GitHub Actions workflow file for using Claude Code. It specifies the action to use, its version, and common inputs for configuring Claude's behavior. Ensure you have set up the necessary secrets like ANTHROPIC_API_KEY in your repository. ```yaml name: Claude Code Action Example on: push: branches: [ main ] pull_request: types: [ opened, synchronize, reopened ] jobs: claude-code-job: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Run Claude Code Action uses: anthropics/claude-code-action@v1 with: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} # Example prompt: 'Refactor this code to be more efficient.' prompt: "Refactor this code to be more efficient." # Example: Specify Claude model and other arguments claude_args: >- --model claude-3-opus-20240229 --max-turns 5 --system-prompt "You are a helpful AI assistant that refactors code." ``` -------------------------------- ### Text Output Example with Bash Source: https://docs.claude.com/en/docs/claude-code/headless Illustrates the default text output format when running Claude Code in headless mode. This example queries for an explanation of a specific file. ```bash claude -p "Explain file src/components/Header.tsx" # Output: This is a React component showing... ``` -------------------------------- ### Install Claude Code Natively on macOS, Linux, and WSL Source: https://docs.claude.com/en/docs/claude-code/troubleshooting Commands to install Claude Code using a native installer script. This method avoids npm and Node.js dependencies and works across macOS, Linux, and WSL environments. It supports installing the stable, latest, or a specific version of Claude Code. ```bash # Install stable version (default) curl -fsSL https://claude.ai/install.sh | bash # Install latest version curl -fsSL https://claude.ai/install.sh | bash -s latest # Install specific version number curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58 ``` -------------------------------- ### Install Claude Code via NPM Source: https://docs.claude.com/en/docs/claude-code/overview Installs Claude Code as a global Node.js package using npm. This method requires Node.js version 18 or later to be installed on your system. It makes the `claude` command available in your terminal. ```bash npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Migrate Claude Code to Local Installation Source: https://docs.claude.com/en/docs/claude-code/troubleshooting Command to migrate an existing Claude Code installation to a local directory. This process moves the installation to `~/.claude/local/` and sets up a shell alias, eliminating the need for sudo for future updates. It also includes verification steps for different operating systems. ```bash claude migrate-installer ``` ```bash # On macOS/Linux/WSL: which claude # Should show an alias to ~/.claude/local/claude # On Windows: where claude # Should show path to claude executable ``` ```bash claude doctor # Check installation health ``` -------------------------------- ### Install Claude Code via PowerShell (Windows) Source: https://docs.claude.com/en/docs/claude-code/overview Installs Claude Code on Windows using PowerShell. This command downloads and executes an installation script. Requires PowerShell to be available and execution policies to allow script execution. ```powershell irm https://claude.ai/install.ps1 | iex ``` -------------------------------- ### Example Agent Skill Structure for Code Review Source: https://docs.claude.com/en/docs/claude-code/slash-commands Illustrates the directory structure for an Agent Skill designed for code review. This structure includes a main SKILL.md file, specific checklist files (SECURITY.md, PERFORMANCE.md, STYLE.md), and a directory for scripts like linters. ```shell .claude/skills/code-review/ ├── SKILL.md (overview and workflows) ├── SECURITY.md (security checklist) ├── PERFORMANCE.md (performance patterns) ├── STYLE.md (style guide reference) └── scripts/ └── run-linters.sh ``` -------------------------------- ### Project Memory File Reference Source: https://docs.claude.com/en/docs/claude-code/troubleshooting References the use of project memory files, specifically 'CLAUDE.md', for documenting preferred markdown styling and other project conventions to ensure consistency. ```text /en/docs/claude-code/memory ``` ```markdown CLAUDE.md ``` -------------------------------- ### Persist All Environment Changes with Bash in SessionStart Hook Source: https://docs.claude.com/en/docs/claude-code/hooks This bash script example shows how to capture and persist all environment modifications made by setup commands (like 'nvm use') within a SessionStart hook. It achieves this by diffing the environment before and after the commands are run and appending the differences to the CLAUDE_ENV_FILE. ```bash #!/bin/bash ENV_BEFORE=$(export -p | sort) # Run your setup commands that modify the environment source ~/.nvm/nvm.sh nvm use 20 if [ -n "$CLAUDE_ENV_FILE" ]; then ENV_AFTER=$(export -p | sort) comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE" fi exit 0 ``` -------------------------------- ### Execute Local Stdio MCP Server on Windows Source: https://docs.claude.com/en/docs/claude-code/mcp Example demonstrating how to correctly execute local MCP servers using `npx` on native Windows environments. The `cmd /c` wrapper is necessary to ensure proper command execution and avoid 'Connection closed' errors. ```bash # This creates command="cmd" which Windows can execute claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package ``` -------------------------------- ### Install Claude Code via Homebrew Source: https://docs.claude.com/en/docs/claude-code/overview Installs Claude Code using the Homebrew package manager. This is a convenient method for macOS users who have Homebrew installed. It simplifies the installation and management of the tool. ```bash brew install --cask claude-code ``` -------------------------------- ### Reference MCP Resources in Prompts (Example) Source: https://docs.claude.com/en/docs/claude-code/mcp Demonstrates how to use the '@' mention syntax to reference specific resources hosted on connected MCP servers. These resources can be files, schemas, or other data accessible via a server. The format is `@server:protocol://resource/path`. ```text > Can you analyze @github:issue://123 and suggest a fix? > Please review the API documentation at @docs:file://api/authentication > Compare @postgres:schema://users with @docs:file://database/user-model ``` -------------------------------- ### Install Claude Code via Curl (macOS/Linux) Source: https://docs.claude.com/en/docs/claude-code/overview Installs Claude Code using a curl command to download and execute an installation script. This method is suitable for macOS and Linux systems. Ensure you have internet connectivity and appropriate permissions to execute scripts. ```bash curl -fsSL https://claude.ai/install.sh | bash ``` -------------------------------- ### Claude Code Debug Output Example Source: https://docs.claude.com/en/docs/claude-code/hooks This example demonstrates the detailed output generated when using the `claude --debug` command to inspect hook execution. It shows the process from finding matching hooks to executing a command and its completion status. ```shell [DEBUG] Executing hooks for PostToolUse:Write [DEBUG] Getting matching hook commands for PostToolUse with query: Write [DEBUG] Found 1 hook matchers in settings [DEBUG] Matched 1 hooks for query "Write" [DEBUG] Found 1 hook commands to execute [DEBUG] Executing hook command: with timeout 60000ms [DEBUG] Hook command completed with status 0: ``` -------------------------------- ### SKILL.md Structure Example (YAML/Markdown) Source: https://docs.claude.com/en/docs/claude-code/skills Defines the basic structure of a SKILL.md file, including YAML frontmatter for metadata like 'name' and 'description', followed by Markdown content for instructions and examples. ```yaml --- name: your-skill-name description: Brief description of what this Skill does and when to use it --- # Your Skill Name ## Instructions Provide clear, step-by-step guidance for Claude. ## Examples Show concrete examples of using this Skill. ``` -------------------------------- ### Execute MCP Prompts as Slash Commands (Examples) Source: https://docs.claude.com/en/docs/claude-code/mcp Shows how to invoke MCP server prompts using slash commands within Claude Code. Prompts are formatted as `/mcp__servername__promptname`. Arguments can be passed space-separated after the command. Examples include listing pull requests and creating Jira issues. ```text > /mcp__github__list_prs > /mcp__github__pr_review 456 > /mcp__jira__create_issue "Bug in login flow" high ``` -------------------------------- ### Bash Command Execution with Allowed Tools Source: https://docs.claude.com/en/docs/claude-code/slash-commands Provides an example of executing bash commands before a slash command runs using the '!' prefix. It highlights the necessity of including `allowed-tools` with the `Bash` tool and demonstrates how to capture command output like git status and diff. ```markdown --- allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*) description: Create a git commit --- ## Context - Current git status: !`git status` - Current git diff (staged and unstaged changes): !`git diff HEAD` - Current branch: !`git branch --show-current` - Recent commits: !`git log --oneline -10` ## Your task Based on the above changes, create a single git commit. ``` -------------------------------- ### Claude Code Hooks Configuration (JSON) Source: https://docs.claude.com/en/docs/claude-code/hooks-guide This JSON configuration shows how a 'PreToolUse' hook is registered for 'Bash' commands. It specifies a command to log the tool's input, including its command and description. ```json { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "jq -r '"\(.tool_input.command) - \(.tool_input.description // \"No description\")"' >> ~/.claude/bash-command-log.txt" } ] } ] } } ``` -------------------------------- ### Check Claude Code Version and Installation Details Source: https://docs.claude.com/en/docs/claude-code/costs This command allows you to retrieve information about your current Claude Code installation, including the version number, installation type, and relevant system details. It is useful for troubleshooting and understanding behavior changes between updates. ```bash claude doctor ``` -------------------------------- ### Multi-turn Legal Document Review with Session Persistence (Bash) Source: https://docs.claude.com/en/docs/claude-code/sdk/sdk-headless This example demonstrates how to conduct a multi-turn legal document review using the Claude CLI with session persistence. It first starts a new session, retrieves the session ID, and then uses the session ID to maintain context across multiple review steps. ```bash # Legal document review with session persistence session_id=$(claude -p "Start legal review session" --output-format json | jq -r '.session_id') # Review contract in multiple steps claude -p --resume "$session_id" "Review contract.pdf for liability clauses" claude -p --resume "$session_id" "Check compliance with GDPR requirements" claude -p --resume "$session_id" "Generate executive summary of risks" ``` -------------------------------- ### Example Sandbox Configuration in JSON Source: https://docs.claude.com/en/docs/claude-code/settings This JSON object demonstrates a typical configuration for Claude Code's sandbox settings. It includes enabling the sandbox, auto-approving bash commands, excluding specific commands like 'docker', and configuring network access for Unix sockets and local binding. ```json { "sandbox": { "enabled": true, "autoAllowBashIfSandboxed": true, "excludedCommands": ["docker"], "network": { "allowUnixSockets": [ "/var/run/docker.sock" ], "allowLocalBinding": true } }, "permissions": { "deny": [ "Read(.envrc)", "Read(~/.aws/**)" ] } } ``` -------------------------------- ### Google Vertex AI Job Example with Workload Identity Federation Source: https://docs.claude.com/en/docs/claude-code/gitlab-ci-cd This GitLab CI/CD configuration connects to Google Vertex AI using Workload Identity Federation, eliminating the need for service account key files. It uses the Google Cloud CLI image, installs the Claude Code package, and authenticates to GCP. The job then executes the 'claude' command, allowing for AI-driven code reviews and modifications within the Vertex AI environment. ```yaml claude-vertex: stage: ai image: gcr.io/google.com/cloudsdktool/google-cloud-cli:slim rules: - if: '$CI_PIPELINE_SOURCE == "web"' before_script: - apt-get update && apt-get install -y git nodejs npm && apt-get clean - npm install -g @anthropic-ai/claude-code # Authenticate to Google Cloud via WIF (no downloaded keys) - > gcloud auth login --cred-file=<(cat < CLOUD_ML_REGION="${CLOUD_ML_REGION:-us-east5}" claude -p "${AI_FLOW_INPUT:-'Review and update code as requested'}" --permission-mode acceptEdits --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab" --debug variables: CLOUD_ML_REGION: "us-east5" ``` -------------------------------- ### Update Settings Loading in TypeScript Source: https://docs.claude.com/en/docs/claude-code/sdk Demonstrates how to explicitly load settings sources in the Claude Code SDK (v0.1.0 and later) compared to previous versions (v0.0.x) which loaded them automatically. It shows how to load all default sources or specific ones. ```typescript // BEFORE (v0.0.x) - Loaded all settings automatically const result = query({ prompt: "Hello" }); // Would read from: // - ~/.claude/settings.json (user) // - .claude/settings.json (project) // - .claude/settings.local.json (local) // - CLAUDE.md files // - Custom slash commands // AFTER (v0.1.0) - No settings loaded by default // To get the old behavior: const result = query({ prompt: "Hello", options: { settingSources: ["user", "project", "local"] } }); // Or load only specific sources: const result = query({ prompt: "Hello", options: { settingSources: ["project"] // Only project settings } }); ``` -------------------------------- ### Centralized OpenTelemetry Configuration via Managed Settings (JSON) Source: https://docs.claude.com/en/docs/claude-code/monitoring-usage This JSON configuration file allows administrators to centrally manage OpenTelemetry settings for Claude Code across an organization. It defines environment variables that override user configurations, ensuring consistent telemetry setup. The example shows how to enable telemetry, specify OTLP exporters, set the endpoint, and configure authentication headers. ```json { "env": { "CLAUDE_CODE_ENABLE_TELEMETRY": "1", "OTEL_METRICS_EXPORTER": "otlp", "OTEL_LOGS_EXPORTER": "otlp", "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc", "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.company.com:4317", "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer company-token" } } ``` -------------------------------- ### Desktop Notifications for Input Awaiting Source: https://docs.claude.com/en/docs/claude-code/hooks-guide This hook provides desktop notifications when Claude requires user input. It triggers a command to display a notification, informing the user that their input is needed. This is useful for interactive sessions where timely responses are crucial. ```json { "hooks": { "Notification": [ { "matcher": "", "hooks": [ { "type": "command", "command": "notify-send 'Claude Code' 'Awaiting your input'" } ] } ] } } ``` -------------------------------- ### Install and Test Local Plugin in Claude Code Source: https://docs.claude.com/en/docs/claude-code/plugins These bash commands are used within the Claude Code environment to add a local development marketplace and install a plugin from it. This allows for iterative testing of plugins during development. ```bash cd .. claude ``` ```bash /plugin marketplace add ./dev-marketplace ``` ```bash /plugin install my-plugin@dev-marketplace ``` -------------------------------- ### Plan Subagent Example Scenario Source: https://docs.claude.com/en/docs/claude-code/sub-agents Illustrates how the Plan subagent is automatically invoked in plan mode to research the codebase before Claude presents a plan. It shows a user request for refactoring and Claude's internal delegation to the Plan subagent for gathering information. ```text User: [In plan mode] Help me refactor the authentication module Claude: Let me research your authentication implementation first... [Internally invokes Plan subagent to explore auth-related files] [Plan subagent searches codebase and returns findings] Claude: Based on my research, here's my proposed plan... ``` -------------------------------- ### Explicit System Prompt Configuration (TypeScript) Source: https://docs.claude.com/en/docs/claude-code/sdk Shows how to explicitly set the system prompt in TypeScript when migrating to Claude Agent SDK v0.1.0, including using presets or custom prompts. ```typescript // BEFORE (v0.0.x) - Used Claude Code's system prompt by default const result = query({ prompt: "Hello" }); // AFTER (v0.1.0) - Uses empty system prompt by default // To get the old behavior, explicitly request Claude Code's preset: const result = query({ prompt: "Hello", options: { systemPrompt: { type: "preset", preset: "claude_code" } } }); // Or use a custom system prompt: const result = query({ prompt: "Hello", options: { systemPrompt: "You are a helpful coding assistant" } }); ``` -------------------------------- ### Add and Use GitHub MCP Server Source: https://docs.claude.com/en/docs/claude-code/mcp Guides on adding an HTTP GitHub MCP server and authenticating within Claude Code to manage pull requests, issues, and code reviews using natural language commands. ```bash # 1. Add the GitHub MCP server claude mcp add --transport http github https://api.githubcopilot.com/mcp/ # 2. In Claude Code, authenticate if needed > /mcp # Select "Authenticate" for GitHub # 3. Now you can ask Claude to work with GitHub > "Review PR #456 and suggest improvements" > "Create a new issue for the bug we just found" > "Show me all open PRs assigned to me" ``` -------------------------------- ### Install Python Packages for Claude Source: https://docs.claude.com/en/docs/claude-code/skills This bash command installs the necessary Python packages, 'pypdf' and 'pdfplumber', required for Claude to process PDF documents and extract text. Ensure these packages are installed in your environment before running Claude. ```bash pip install pypdf pdfplumber ``` -------------------------------- ### Claude Code Action CLI Arguments Source: https://docs.claude.com/en/docs/claude-code/github-actions This example demonstrates how to configure advanced arguments for the Claude Code Action using the `claude_args` parameter. It shows common arguments such as specifying the model, setting maximum conversation turns, and providing a path to a configuration file. ```yaml claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929 --mcp-config /path/to/config.json" ``` -------------------------------- ### Basic Claude Code Action v1 Configuration (YAML) Source: https://docs.claude.com/en/docs/claude-code/github-actions This YAML configuration demonstrates the basic setup for the Claude Code Action v1. It specifies the action to use and provides essential parameters like the Anthropic API key and an optional prompt. The `claude_args` parameter allows for passing CLI arguments. ```yaml - uses: anthropics/claude-code-action@v1 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} prompt: "Your instructions here" # Optional claude_args: "--max-turns 5" # Optional CLI arguments ``` -------------------------------- ### Example settings.json for Claude Code Configuration Source: https://docs.claude.com/en/docs/claude-code/settings This JSON configuration file demonstrates how to set permissions for running bash commands and reading files, define environment variables for telemetry and metrics export, and manage company announcements within Claude Code. It is typically located at user or project level. ```JSON { "permissions": { "allow": [ "Bash(npm run lint)", "Bash(npm run test:*)", "Read(~/.zshrc)" ], "deny": [ "Bash(curl:*)", "Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)" ] }, "env": { "CLAUDE_CODE_ENABLE_TELEMETRY": "1", "OTEL_METRICS_EXPORTER": "otlp" }, "companyAnnouncements": [ "Welcome to Acme Corp! Review our code guidelines at docs.acme.com", "Reminder: Code reviews required for all PRs", "New security policy in effect" ] } ``` -------------------------------- ### Install ripgrep for Search and Discovery on Multiple Operating Systems Source: https://docs.claude.com/en/docs/claude-code/troubleshooting Installs the ripgrep tool, a fast grep alternative, required for Claude Code's search and discovery features. It provides package manager commands for macOS, Windows, Ubuntu/Debian, Alpine Linux, and Arch Linux. ```bash # macOS (Homebrew) brew install ripgrep # Windows (winget) winget install BurntSushi.ripgrep.MSVC # Ubuntu/Debian sudo apt install ripgrep # Alpine Linux apk add ripgrep # Arch Linux pacman -S ripgrep ``` -------------------------------- ### Reporting Bugs with /bug Command Source: https://docs.claude.com/en/docs/claude-code/troubleshooting Documents the use of the '/bug' command within Claude Code for directly reporting problems to Anthropic developers, aiding in faster issue resolution. ```text /bug ``` -------------------------------- ### AWS Bedrock Job Example with GitLab OIDC Source: https://docs.claude.com/en/docs/claude-code/gitlab-ci-cd This GitLab CI/CD job integrates with AWS Bedrock using OpenID Connect (OIDC) for authentication, avoiding the need for static AWS credentials. It requires specific CI/CD variables for role assumption and region. The job installs AWS CLI and the Claude Code package, then exchanges the GitLab OIDC token for temporary AWS credentials before running the 'claude' command. ```yaml claude-bedrock: stage: ai image: node:24-alpine3.21 rules: - if: '$CI_PIPELINE_SOURCE == "web"' before_script: - apk add --no-cache bash curl jq git python3 py3-pip - pip install --no-cache-dir awscli - npm install -g @anthropic-ai/claude-code # Exchange GitLab OIDC token for AWS credentials - export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}" - if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi - > aws sts assume-role-with-web-identity --role-arn "$AWS_ROLE_TO_ASSUME" --role-session-name "gitlab-claude-$(date +%s)" --web-identity-token "file://$AWS_WEB_IDENTITY_TOKEN_FILE" --duration-seconds 3600 > /tmp/aws_creds.json - export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId /tmp/aws_creds.json)" - export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey /tmp/aws_creds.json)" - export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken /tmp/aws_creds.json)" script: - /bin/gitlab-mcp-server || true - > claude -p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}" --permission-mode acceptEdits --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab" --debug variables: AWS_REGION: "us-west-2" ``` -------------------------------- ### Example Slash Command for Code Review Source: https://docs.claude.com/en/docs/claude-code/slash-commands Demonstrates a basic slash command written in Markdown for reviewing code. This command is designed for manual invocation and focuses on specific review criteria like security, performance, and style. ```markdown # .claude/commands/review.md Review this code for: - Security vulnerabilities - Performance issues - Code style violations ``` -------------------------------- ### Read & Edit File Permissions in Claude Code Source: https://docs.claude.com/en/docs/claude-code/iam Explains the Read and Edit permission rules for file operations in Claude Code, which follow gitignore specifications. It details four pattern types: absolute paths, home directory paths, settings file relative paths, and current directory relative paths, providing examples for each. It also clarifies that patterns starting with '/' are relative to the settings file, not the filesystem root, unless double slashes '//' are used for absolute paths. ```text //path ~/path /path path or ./path ``` ```text Read(//Users/alice/secrets/**) Read(~/Documents/*.pdf) Edit(/src/**/*.ts) Read(*.env) ``` ```text Edit(/docs/**) Read(~/.zshrc) Edit(//tmp/scratch.txt) Read(src/**) ``` -------------------------------- ### YAML Skill Description Example Source: https://docs.claude.com/en/docs/claude-code/skills This YAML snippet demonstrates how to define a Skill's description. A good description is specific, outlining what the Skill does and when it should be used, improving Claude's ability to autonomously activate the Skill. ```yaml description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. ``` -------------------------------- ### Marketplace JSON File Structure Source: https://docs.claude.com/en/docs/claude-code/plugin-marketplaces An example of a `.claude-plugin/marketplace.json` file used to define a plugin marketplace. It includes essential information like the marketplace name, owner details, and a list of plugins with their sources and versions. ```json { "name": "company-tools", "owner": { "name": "DevTools Team", "email": "devtools@company.com" }, "plugins": [ { "name": "code-formatter', "source": "./plugins/formatter", "description": "Automatic code formatting on save", "version": "2.1.0", "author": { "name": "DevTools Team" } }, { "name": "deployment-tools", "source": { "source": "github", "repo": "company/deploy-plugin" }, "description": "Deployment automation tools" } ] } ``` -------------------------------- ### Valid OTEL_RESOURCE_ATTRIBUTES Examples (Bash) Source: https://docs.claude.com/en/docs/claude-code/monitoring-usage These examples demonstrate valid formats for the OTEL_RESOURCE_ATTRIBUTES environment variable. They show how to replace spaces with underscores or use camelCase, and how to percent-encode special characters like apostrophes and spaces if necessary, adhering to the W3C Baggage specification. ```bash # ✅ Valid - use underscores or camelCase instead export OTEL_RESOURCE_ATTRIBUTES="org.name=Johns_Organization" export OTEL_RESOURCE_ATTRIBUTES="org.name=JohnsOrganization" # ✅ Valid - percent-encode special characters if needed export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization" ``` -------------------------------- ### Example Project-Scoped MCP Server Configuration Source: https://docs.claude.com/en/docs/claude-code/mcp Illustrates the JSON structure for defining MCP servers within a project's .mcp.json file. This format is used for project-scoped servers shared among team members and checked into version control. ```json { "mcpServers": { "shared-server": { "command": "/path/to/server", "args": [], "env": {} } } } ``` -------------------------------- ### Example of triggering SlashCommand tool Source: https://docs.claude.com/en/docs/claude-code/slash-commands Demonstrates how to prompt Claude to trigger the SlashCommand tool by referencing a command with its slash. This encourages Claude to invoke custom commands programmatically when appropriate during a conversation. ```markdown > Run /write-unit-test when you are about to start writing tests. ``` -------------------------------- ### SessionStart Hook for Initial Context Source: https://docs.claude.com/en/docs/claude-code/hooks Allows loading context at the start of a session. The 'additionalContext' from multiple 'SessionStart' hooks are concatenated and added to the session's context. ```json { "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": "My additional context here" } } ``` -------------------------------- ### Create Plugin Directory Structure (Bash) Source: https://docs.claude.com/en/docs/claude-code/plugins This snippet shows the bash commands to create the necessary directory structure for a new Claude Code plugin, starting with a marketplace and then the plugin itself. ```bash mkdir test-marketplace cd test-marketplace mkdir my-first-plugin cd my-first-plugin ``` -------------------------------- ### Example Claude Code Prompt in Issue Comment Source: https://docs.claude.com/en/docs/claude-code/gitlab-ci-cd An example of how to use Claude Code within an issue comment to automate feature implementation. By mentioning '@claude' and providing a clear instruction, Claude can analyze the issue description and codebase, create a new branch with the changes, and open a merge request for review. ```text @claude implement this feature based on the issue description ``` -------------------------------- ### Intelligent Stop Hook Example Source: https://docs.claude.com/en/docs/claude-code/hooks An example configuration for an 'Stop' hook that uses a detailed prompt to instruct the LLM on how to evaluate whether Claude should stop. It includes specific criteria for the LLM to consider and specifies a timeout. ```json { "hooks": { "Stop": [ { "hooks": [ { "type": "prompt", "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"decision\": \"approve\" or \"block\", \"reason\": \"your explanation\"}", "timeout": 30 } ] } ] } } ``` -------------------------------- ### SubagentStop Hook with Custom Logic Example Source: https://docs.claude.com/en/docs/claude-code/hooks This example demonstrates configuring a 'SubagentStop' hook. It provides a prompt for the LLM to evaluate if a subagent has completed its task, if errors need fixing, or if more context is required, returning a decision and reason. ```json { "hooks": { "SubagentStop": [ { "hooks": [ { "type": "prompt", "prompt": "Evaluate if this subagent should stop. Input: $ARGUMENTS\n\nCheck if:\n- The subagent completed its assigned task\n- Any errors occurred that need fixing\n- Additional context gathering is needed\n\nReturn: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}" } ] } ] } } ```