Initial commit to new repository

This commit is contained in:
2026-04-03 18:23:52 +09:00
commit deffb33cf9
5248 changed files with 267762 additions and 0 deletions

View File

@@ -0,0 +1,517 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# CLI flags
> All options you can pass when launching Claude Code from the terminal. Run claude --help to see the full list.
Pass CLI flags when you launch Claude Code:
```bash theme={null}
claude [flags] [prompt]
```
Run `claude --help` to see all available flags in your installed version.
<Tip>
Flags that configure session behavior (like `--model` and `--permission-mode`) can also be changed mid-session with the corresponding slash commands: `/model` and `/permissions`.
</Tip>
***
## Core flags
<AccordionGroup>
<Accordion title="-p, --print">
Run Claude non-interactively. Claude processes the prompt (from the argument or stdin), prints the response, and exits. No REPL is started.
```bash theme={null}
claude -p "explain the main function in src/index.ts"
echo "what does this do?" | claude -p
```
<Warning>
The workspace trust dialog is skipped in `--print` mode. Only use this flag in directories you trust.
</Warning>
Works with: `--output-format`, `--model`, `--system-prompt`, `--permission-mode`, `--max-turns`, `--allowed-tools`.
</Accordion>
<Accordion title="--output-format <format>">
Set the output format. Only works with `--print`.
| Value | Description |
| ------------- | --------------------------------------------------- |
| `text` | Plain text output (default) |
| `json` | Single JSON object with the complete result |
| `stream-json` | Newline-delimited JSON stream with real-time events |
```bash theme={null}
claude -p "list the exported functions" --output-format json
claude -p "refactor this file" --output-format stream-json
```
Use `stream-json` when you want to process Claude's output incrementally as it arrives (useful for long-running tasks or piping into other tools).
</Accordion>
<Accordion title="--input-format <format>">
Set the input format for stdin. Only works with `--print`.
| Value | Description |
| ------------- | ----------------------------------- |
| `text` | Plain text input (default) |
| `stream-json` | Newline-delimited JSON stream input |
`stream-json` input requires `--output-format stream-json`.
```bash theme={null}
cat messages.jsonl | claude -p --input-format stream-json --output-format stream-json
```
</Accordion>
<Accordion title="--verbose">
Enable verbose output. Overrides the `verbose` setting in your config file.
```bash theme={null}
claude --verbose
claude -p "debug this" --verbose
```
</Accordion>
<Accordion title="-v, --version">
Print the version number and exit.
```bash theme={null}
claude --version
claude -v
```
</Accordion>
<Accordion title="-h, --help">
Display help for the command and exit.
```bash theme={null}
claude --help
claude mcp --help
```
</Accordion>
</AccordionGroup>
***
## Session continuation flags
<AccordionGroup>
<Accordion title="-c, --continue">
Resume the most recent conversation in the current directory without prompting for a session to resume.
```bash theme={null}
claude --continue
claude -c "now add tests for that"
```
</Accordion>
<Accordion title="-r, --resume [session-id]">
Resume a conversation by session ID. Without a value, opens an interactive picker where you can search through past sessions. Accepts an optional search term to filter the list.
```bash theme={null}
# Open interactive picker
claude --resume
# Resume by session ID
claude --resume 550e8400-e29b-41d4-a716-446655440000
# Open picker filtered by search term
claude --resume "auth refactor"
```
</Accordion>
<Accordion title="--fork-session">
When used with `--continue` or `--resume`, creates a new session branched from the resumed conversation rather than continuing it in place.
```bash theme={null}
claude --resume <session-id> --fork-session
```
</Accordion>
<Accordion title="-n, --name <name>">
Set a display name for the session. The name appears in `/resume` and in the terminal title.
```bash theme={null}
claude --name "auth-refactor"
```
</Accordion>
<Accordion title="--session-id <uuid>">
Use a specific UUID as the session ID instead of a generated one. Must be a valid UUID. Cannot be used with `--continue` or `--resume` unless `--fork-session` is also specified.
```bash theme={null}
claude --session-id 550e8400-e29b-41d4-a716-446655440000
```
</Accordion>
<Accordion title="--no-session-persistence">
Disable session persistence. The session will not be saved to disk and cannot be resumed. Only works with `--print`.
```bash theme={null}
claude -p "one-off task" --no-session-persistence
```
</Accordion>
</AccordionGroup>
***
## Model and capability flags
<AccordionGroup>
<Accordion title="--model <model>">
Set the model for the session. Accepts an alias (e.g. `sonnet`, `opus`, `haiku`) or a full model ID (e.g. `claude-sonnet-4-6`).
```bash theme={null}
claude --model sonnet
claude --model opus
claude --model claude-sonnet-4-6
```
You can also change the model mid-session with `/model`.
</Accordion>
<Accordion title="--effort <level>">
Set the effort level for the session. Controls how much computation Claude applies to each response.
| Value | Description |
| -------- | ------------------------- |
| `low` | Faster, lighter responses |
| `medium` | Balanced (default) |
| `high` | More thorough reasoning |
| `max` | Maximum effort |
```bash theme={null}
claude --effort high "review this architecture"
```
</Accordion>
<Accordion title="--fallback-model <model>">
Enable automatic fallback to a different model when the primary model is overloaded. Only works with `--print`.
```bash theme={null}
claude -p "analyze this" --model opus --fallback-model sonnet
```
</Accordion>
</AccordionGroup>
***
## Permission and safety flags
<AccordionGroup>
<Accordion title="--permission-mode <mode>">
Set the permission mode for the session.
| Mode | Behavior |
| ------------------- | ------------------------------------------------------------------------------------ |
| `default` | Claude prompts before running commands and making edits |
| `acceptEdits` | File edits are applied automatically; shell commands still require approval |
| `plan` | Claude proposes a plan and waits for your approval before acting |
| `bypassPermissions` | All actions run without prompts — intended for sandboxed automated environments only |
```bash theme={null}
claude --permission-mode acceptEdits
claude --permission-mode plan "refactor the payment module"
claude --permission-mode bypassPermissions # only in isolated sandboxes
```
<Warning>
`bypassPermissions` disables all confirmation prompts. Only use it inside Docker containers, CI sandboxes, or other isolated environments with no internet access.
</Warning>
</Accordion>
<Accordion title="--dangerously-skip-permissions">
Bypass all permission checks. Claude takes all actions (file edits, shell commands) without asking. Equivalent to `--permission-mode bypassPermissions`.
```bash theme={null}
claude --dangerously-skip-permissions -p "run the full test suite and fix failures"
```
<Warning>
Only use this in sandboxed environments with no internet access. Claude Code enforces this: the flag is rejected when running with root/sudo privileges, or outside a Docker or bubblewrap container.
</Warning>
</Accordion>
<Accordion title="--allow-dangerously-skip-permissions">
Make bypassing all permission checks available as an option during the session, without enabling it by default. Useful for automated pipelines that may need to escalate mid-session.
```bash theme={null}
claude --allow-dangerously-skip-permissions -p "..."
```
</Accordion>
<Accordion title="--allowed-tools <tools...>">
**Aliases:** `--allowedTools`
Comma- or space-separated list of tools Claude is allowed to use. Tools not in this list are blocked.
```bash theme={null}
claude --allowed-tools "Bash(git:*) Edit Read"
claude --allowed-tools Bash,Edit,Read
```
Tool patterns support glob-style matching: `Bash(git:*)` permits any git command; `Edit(src/**)` permits edits under `src/`.
</Accordion>
<Accordion title="--disallowed-tools <tools...>">
**Aliases:** `--disallowedTools`
Comma- or space-separated list of tools Claude is not allowed to use.
```bash theme={null}
claude --disallowed-tools "Bash(rm:*)"
```
</Accordion>
<Accordion title="--tools <tools...>">
Specify the exact set of built-in tools available for the session. Use `""` to disable all tools, `default` to enable all tools, or name specific tools.
```bash theme={null}
# Disable all tools
claude --tools ""
# Enable only Bash and Read
claude --tools "Bash Read"
# Enable the default set
claude --tools default
```
</Accordion>
</AccordionGroup>
***
## Context and prompt flags
<AccordionGroup>
<Accordion title="--add-dir <directories...>">
Add one or more directories to the tool access context. Claude will be able to read and edit files in these directories in addition to the current working directory.
```bash theme={null}
claude --add-dir /shared/libs --add-dir /shared/config
```
Useful for monorepos or projects where related code lives outside the current directory.
</Accordion>
<Accordion title="--system-prompt <prompt>">
Override the default system prompt with a custom prompt. Cannot be used with `--system-prompt-file`.
```bash theme={null}
claude --system-prompt "You are a security auditor. Focus only on vulnerabilities."
```
</Accordion>
<Accordion title="--append-system-prompt <text>">
Append text to the default system prompt. Unlike `--system-prompt`, this preserves Claude's built-in instructions and adds to them.
```bash theme={null}
claude --append-system-prompt "Always suggest test cases for every function you write."
```
</Accordion>
<Accordion title="--mcp-config <configs...>">
Load MCP servers from one or more JSON config files or inline JSON strings. Multiple values are space-separated.
```bash theme={null}
# Load from a file
claude --mcp-config ./mcp-servers.json
# Load from multiple files
claude --mcp-config ./local-tools.json ./db-tools.json
# Pass inline JSON
claude --mcp-config '{"mcpServers":{"filesystem":{"command":"npx","args":["@modelcontextprotocol/server-filesystem","/tmp"]}}}'
```
See the [MCP servers guide](/guides/mcp-servers) for the config file format.
</Accordion>
<Accordion title="--strict-mcp-config">
Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations (user config, project config, etc.).
```bash theme={null}
claude --mcp-config ./ci-tools.json --strict-mcp-config
```
</Accordion>
<Accordion title="--settings <file-or-json>">
Load additional settings from a JSON file path or an inline JSON string.
```bash theme={null}
# From a file
claude --settings ./team-settings.json
# Inline JSON
claude --settings '{"model":"claude-sonnet-4-6","verbose":true}'
```
</Accordion>
<Accordion title="--setting-sources <sources>">
Comma-separated list of settings sources to load. Controls which settings files are read at startup.
| Value | Description |
| --------- | ----------------------------------------------------------- |
| `user` | Load `~/.claude/settings.json` |
| `project` | Load `.claude/settings.json` in the current directory |
| `local` | Load `.claude/settings.local.json` in the current directory |
```bash theme={null}
# Load only user-level settings (ignore project settings)
claude --setting-sources user
# Load user and project settings
claude --setting-sources user,project
```
</Accordion>
<Accordion title="--agents <json>">
Define custom agents inline as a JSON object. Each key is the agent name; the value is an object with `description` and `prompt`.
```bash theme={null}
claude --agents '{"reviewer":{"description":"Reviews code for security issues","prompt":"You are a security-focused code reviewer."}}'
```
</Accordion>
</AccordionGroup>
***
## Output control flags
<AccordionGroup>
<Accordion title="--include-hook-events">
Include all hook lifecycle events in the output stream. Only works with `--output-format stream-json`.
```bash theme={null}
claude -p "run task" --output-format stream-json --include-hook-events
```
</Accordion>
<Accordion title="--max-turns <n>">
Limit the number of agentic turns in non-interactive mode. Claude stops after this many turns even if the task is incomplete. Only works with `--print`.
```bash theme={null}
claude -p "refactor this module" --max-turns 10
```
</Accordion>
<Accordion title="--max-budget-usd <amount>">
Set a maximum dollar amount to spend on API calls. Claude stops when the budget is reached. Only works with `--print`.
```bash theme={null}
claude -p "large analysis task" --max-budget-usd 2.50
```
</Accordion>
<Accordion title="--json-schema <schema>">
Provide a JSON Schema for structured output validation. Claude's response will be validated against this schema.
```bash theme={null}
claude -p "extract the function names" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
```
</Accordion>
</AccordionGroup>
***
## Worktree flags
<AccordionGroup>
<Accordion title="-w, --worktree [name]">
Create a new git worktree for this session. Optionally specify a name for the worktree branch. Accepts a PR number or GitHub PR URL to create a worktree from that PR.
```bash theme={null}
claude --worktree
claude --worktree feature-auth
claude --worktree "#142"
```
</Accordion>
<Accordion title="--tmux">
Create a tmux session alongside the worktree. Requires `--worktree`. Uses iTerm2 native panes when available; pass `--tmux=classic` to force standard tmux behavior.
```bash theme={null}
claude --worktree feature-auth --tmux
```
</Accordion>
</AccordionGroup>
***
## Debug flags
<AccordionGroup>
<Accordion title="-d, --debug [filter]">
Enable debug mode. Optionally pass a filter to restrict which debug categories are shown.
```bash theme={null}
# Show all debug output
claude --debug
# Show only api and hooks categories
claude --debug "api,hooks"
# Exclude specific categories
claude --debug "!file,!1p"
```
</Accordion>
<Accordion title="--debug-file <path>">
Write debug logs to a specific file path instead of displaying them inline. Implicitly enables debug mode.
```bash theme={null}
claude --debug-file /tmp/claude-debug.log
```
</Accordion>
<Accordion title="--bare">
Minimal mode. Skips hooks, LSP, plugin sync, attribution, auto-memory, background prefetches, keychain reads, and `CLAUDE.md` auto-discovery. Sets `CLAUDE_CODE_SIMPLE=1`.
Authentication is limited to `ANTHROPIC_API_KEY` or `apiKeyHelper` via `--settings` (OAuth and keychain are not used).
Use `--bare` in scripted pipelines where startup latency matters and the features it disables are not needed. You can still provide context explicitly:
```bash theme={null}
claude --bare \
--system-prompt "$(cat context.md)" \
--add-dir /project/libs \
--mcp-config ./tools.json \
-p "perform the analysis"
```
</Accordion>
</AccordionGroup>
***
## Flag combinations
Common flag patterns for scripting and automation:
```bash theme={null}
# Non-interactive with JSON output
claude -p "list all exported types" --output-format json
# Bypass permissions in CI (sandboxed environment only)
claude -p "run full test suite and fix failures" --dangerously-skip-permissions
# Resume last session and continue non-interactively
claude --continue -p "now write the tests for that"
# Use a custom MCP config with strict isolation
claude --mcp-config ./ci-mcp.json --strict-mcp-config -p "analyze the schema"
# Append to system prompt without replacing it
claude --append-system-prompt "Always output TypeScript, not JavaScript."
```
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,106 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# Commands overview
> Claude Code accepts two categories of commands: CLI flags you pass at launch, and slash commands you type during a session.
Claude Code has two categories of commands:
* **CLI flags** — options you pass when starting Claude from your terminal (e.g. `claude --model sonnet`). They configure the session before it starts.
* **Slash commands** — text commands you type inside an active session (e.g. `/help`). They control Claude's behavior while the session is running.
## Getting help
```bash theme={null}
# Show all CLI flags
claude --help
# Inside a session, list slash commands
/help
```
`/help` lists every slash command available in the current session, including commands added by plugins and skills.
## Two types of commands
| Type | When to use | Example |
| -------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------ |
| CLI flags | Configure a session at launch — set the model, output format, permission mode | `claude --permission-mode acceptEdits "fix the tests"` |
| Slash commands | Interact with a running session — manage memory, switch models, commit code | `/commit` |
CLI flags are consumed once and cannot be changed mid-session (with the exception of `/model` and `/permissions`, which change the running configuration in place).
## CLI flags
Pass flags directly after `claude`:
```bash theme={null}
claude [flags] [prompt]
```
```bash theme={null}
# Non-interactive: print response and exit
claude -p "summarize this file" < README.md
# Set model for the session
claude --model opus
# Accept all file edits automatically
claude --permission-mode acceptEdits
```
See [CLI flags](/reference/commands/cli-flags) for the full list.
## Slash commands
Type a slash command at the input prompt inside any session:
```
/command [arguments]
```
```
/init
/compact summarize only the last three tasks
/model claude-opus-4-5
```
See [Slash commands](/reference/commands/slash-commands) for the full list.
## Keyboard shortcuts
These shortcuts work inside any interactive Claude Code session:
| Key | Action |
| ------------- | ---------------------------------------------------------------- |
| `Ctrl+C` | Interrupt the current response (Claude stops mid-turn) |
| `Ctrl+D` | Exit Claude Code |
| `Ctrl+L` | Clear the terminal display (does not clear conversation history) |
| `Up` / `Down` | Navigate input history |
| `Tab` | Autocomplete slash command names |
| `Escape` | Cancel an in-progress permission prompt |
<Note>
`Ctrl+C` interrupts the current response but keeps the conversation alive. Use `Ctrl+D` or `/exit` to end the session entirely.
</Note>
## Subcommands
In addition to the main `claude` command, a few subcommands are available in your terminal:
| Subcommand | Description |
| ------------------ | ---------------------------------------------- |
| `claude mcp` | Configure and manage MCP servers |
| `claude mcp serve` | Start Claude Code as an MCP server |
| `claude doctor` | Diagnose installation and configuration issues |
| `claude update` | Update Claude Code to the latest version |
```bash theme={null}
claude mcp --help
claude doctor
```
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,381 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# Slash commands
> Commands you type inside a running Claude Code session. Type / at the input prompt to activate them.
Slash commands are typed at the Claude Code input prompt during an active session. Every command starts with `/`.
```
/command [arguments]
```
<Tip>
Type `/help` at any time to see all commands available in the current session, including any added by plugins and skills.
</Tip>
## Quick reference
| Command | Description |
| ------------------------------ | -------------------------------------------------------------------- |
| [`/init`](#init) | Generate `CLAUDE.md` files and optional skills/hooks for the project |
| [`/memory`](#memory) | Edit Claude memory files (global, project, local) |
| [`/config`](#config) | Open the settings panel |
| [`/hooks`](#hooks) | View hook configurations for tool events |
| [`/mcp`](#mcp) | Manage MCP servers — enable, disable, reconnect |
| [`/permissions`](#permissions) | Manage allow and deny rules for tools |
| [`/plan`](#plan) | Enable plan mode or open/describe the current session plan |
| [`/model`](#model) | Set the AI model for the current session |
| [`/commit`](#commit) | Create a git commit with an AI-generated message |
| [`/review`](#review) | Review a pull request |
| [`/skills`](#skills) | List available skills |
| [`/compact`](#compact) | Summarize conversation history to reduce context usage |
| [`/clear`](#clear) | Clear conversation history and free up context |
| [`/help`](#help) | Show help and available commands |
| [`/login`](#login) | Sign in or switch Anthropic accounts |
| [`/logout`](#logout) | Sign out from your Anthropic account |
***
## Project and memory commands
<AccordionGroup>
<Accordion title="/init">
**Syntax:** `/init`
Analyzes your codebase and sets up `CLAUDE.md` file(s), and optionally skills and hooks. Claude surveys key project files — manifests, CI config, build scripts, README — then interviews you to fill in any gaps before writing the output files.
What it sets up, depending on your choices:
* **Project `CLAUDE.md`** — team-shared instructions checked into source control. Covers build/test/lint commands, coding conventions, architecture notes, and non-obvious gotchas.
* **Personal `CLAUDE.local.md`** — your private preferences for this project (gitignored). Covers your role, sandbox URLs, communication preferences.
* **Skills** (`.claude/skills/<name>/SKILL.md`) — on-demand workflows you or Claude invoke with `/<skill-name>`.
* **Hooks** (`.claude/settings.json`) — deterministic shell commands that run automatically on tool events (e.g. format on every edit).
**Example:**
```
/init
```
<Tip>
Run `/init` again at any time. If `CLAUDE.md` already exists, Claude will propose specific changes rather than overwriting the file.
</Tip>
</Accordion>
<Accordion title="/memory">
**Syntax:** `/memory`
Opens an interactive editor for Claude's memory files. Memory files are loaded into every session and persist across conversations.
The three memory scopes are:
| Scope | File | Who it applies to |
| ------- | --------------------------------- | --------------------------------------- |
| Global | `~/.claude/CLAUDE.md` | You, across all projects |
| Project | `CLAUDE.md` at project root | Everyone on the team |
| Local | `CLAUDE.local.md` at project root | You, for this project only (gitignored) |
**Example:**
```
/memory
```
</Accordion>
</AccordionGroup>
***
## Configuration commands
<AccordionGroup>
<Accordion title="/config">
**Syntax:** `/config`
**Alias:** `/settings`
Opens the configuration panel where you can view and edit Claude Code settings, including model preferences, theme, verbose mode, and more.
**Example:**
```
/config
```
</Accordion>
<Accordion title="/hooks">
**Syntax:** `/hooks`
Displays the hook configurations currently active for this session. Hooks are shell commands that run automatically when tool events occur (e.g. after every file edit, before a Bash command).
**Example:**
```
/hooks
```
<Note>
To create or edit hooks, use `/init` or edit `.claude/settings.json` directly. See the [hooks guide](/guides/hooks) for the full schema.
</Note>
</Accordion>
<Accordion title="/mcp">
**Syntax:** `/mcp [enable|disable [server-name]]`
Manages MCP (Model Context Protocol) servers for the current session. Without arguments, opens the MCP management panel. With arguments, enables or disables specific servers.
| Argument | Effect |
| ------------------------- | --------------------------------- |
| *(none)* | Open the MCP management panel |
| `enable` | Enable all disabled MCP servers |
| `enable <server-name>` | Enable a specific server by name |
| `disable` | Disable all active MCP servers |
| `disable <server-name>` | Disable a specific server by name |
| `reconnect <server-name>` | Reconnect to a specific server |
**Examples:**
```
/mcp
/mcp enable
/mcp enable my-database-server
/mcp disable analytics-server
/mcp reconnect filesystem
```
<Note>
To add or remove MCP servers permanently, use the `claude mcp` CLI subcommand or edit your MCP config file. Changes made with `/mcp enable`/`disable` apply for the current session only.
</Note>
</Accordion>
<Accordion title="/permissions">
**Syntax:** `/permissions`
**Alias:** `/allowed-tools`
Opens the permissions panel where you can view and manage allow and deny rules for tools. Rules control which tools Claude can use without prompting (allow rules) and which are blocked entirely (deny rules).
**Example:**
```
/permissions
```
Rules use glob-style patterns:
```
Bash(git:*) # allow all git commands
Bash(npm:*) # allow all npm commands
Edit(src/**/*.ts) # allow edits to TypeScript files in src/
```
See [permissions](/concepts/permissions) for the full rule syntax.
</Accordion>
<Accordion title="/model">
**Syntax:** `/model [model]`
Sets the AI model used for the rest of the session. Without an argument, opens an interactive model picker. With a model name or alias, switches immediately.
| Argument | Effect |
| ------------------- | ------------------------------------- |
| *(none)* | Open the interactive model picker |
| `sonnet` | Switch to the latest Claude Sonnet |
| `opus` | Switch to the latest Claude Opus |
| `haiku` | Switch to the latest Claude Haiku |
| `claude-sonnet-4-6` | Switch to a specific model by full ID |
**Examples:**
```
/model
/model sonnet
/model claude-opus-4-5
```
</Accordion>
</AccordionGroup>
***
## Session management commands
<AccordionGroup>
<Accordion title="/plan">
**Syntax:** `/plan [open|<description>]`
Enables plan mode or manages the current session plan. In plan mode, Claude produces a written plan before taking any action and waits for your approval.
| Argument | Effect |
| --------------- | -------------------------------------------- |
| *(none)* | Toggle plan mode on/off |
| `open` | Open and display the current plan |
| `<description>` | Create a new plan with the given description |
**Examples:**
```
/plan
/plan open
/plan refactor the auth module to use JWT
```
<Tip>
Plan mode is equivalent to `--permission-mode plan` at launch. Use it when you want to review what Claude intends to do before any files are touched.
</Tip>
</Accordion>
<Accordion title="/compact">
**Syntax:** `/compact [instructions]`
Summarizes the conversation history and replaces it with a condensed version in context. Use this when the context window is filling up and you want to continue working without starting a new session.
An optional argument lets you give Claude specific instructions for how to summarize.
**Examples:**
```
/compact
/compact focus only on the database schema changes
/compact summarize the last three completed tasks
```
</Accordion>
<Accordion title="/clear">
**Syntax:** `/clear`
**Aliases:** `/reset`, `/new`
Clears the entire conversation history and frees up context, starting a fresh session in the same working directory. Unlike `/compact`, this removes all history rather than summarizing it.
**Example:**
```
/clear
```
</Accordion>
<Accordion title="/skills">
**Syntax:** `/skills`
Lists all skills available in the current session. Skills are on-demand capabilities defined in `.claude/skills/` that you or Claude can invoke with `/<skill-name>`.
**Example:**
```
/skills
```
</Accordion>
</AccordionGroup>
***
## Git commands
<AccordionGroup>
<Accordion title="/commit">
**Syntax:** `/commit`
Creates a git commit using AI-generated commit message. Claude reads the current git status and diff, analyzes staged and unstaged changes, and drafts a concise commit message that focuses on the "why" rather than the "what". It then stages the relevant files and creates the commit.
Claude follows the existing commit message style in the repository and applies these safety rules:
* Never amends existing commits (always creates a new commit)
* Never skips hooks (`--no-verify`)
* Never commits files that likely contain secrets (`.env`, credentials files)
* Does not create empty commits when there are no changes
**Example:**
```
/commit
```
<Note>
`/commit` only has access to `git add`, `git status`, and `git commit`. It cannot push, rebase, or run other git operations.
</Note>
</Accordion>
<Accordion title="/review">
**Syntax:** `/review [PR-number]`
Runs an AI code review on a pull request using the GitHub CLI (`gh`). Without a PR number, Claude runs `gh pr list` to show open PRs. With a PR number, it fetches the PR details and diff, then provides a structured review covering:
* Overview of what the PR does
* Code quality and style analysis
* Specific improvement suggestions
* Potential issues or risks
* Performance, test coverage, and security considerations
**Examples:**
```
/review
/review 142
```
<Note>
`/review` requires the [GitHub CLI](https://cli.github.com/) (`gh`) to be installed and authenticated.
</Note>
</Accordion>
</AccordionGroup>
***
## Account and help commands
<AccordionGroup>
<Accordion title="/help">
**Syntax:** `/help`
Shows help and lists all slash commands available in the current session, including built-in commands, skill commands, and any commands added by installed plugins.
**Example:**
```
/help
```
</Accordion>
<Accordion title="/login">
**Syntax:** `/login`
Signs in to your Anthropic account or switches between accounts. Opens a browser-based OAuth flow if not already authenticated, or presents the account switcher if you are.
**Example:**
```
/login
```
</Accordion>
<Accordion title="/logout">
**Syntax:** `/logout`
Signs out from your Anthropic account. After logging out, Claude Code will prompt you to authenticate again on the next session.
**Example:**
```
/logout
```
</Accordion>
</AccordionGroup>
***
## Custom skill commands
When you or a plugin author creates a skill in `.claude/skills/<skill-name>/SKILL.md`, it becomes available as `/<skill-name>` in any session where that skill is loaded.
```
/verify
/deploy staging
/fix-issue 123
```
Run `/skills` to see all loaded skills and their descriptions. See the [skills guide](/guides/skills) for how to create your own.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,935 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# Hooks reference
> Full reference for every hook event, its input payload, output schema, and the effect each exit code has on Claude's behavior.
Hooks are shell commands, HTTP endpoints, LLM prompts, or in-process callbacks that fire at defined points in Claude's agentic loop. They let you inject logic before or after tool calls, intercept permission requests, react to session lifecycle events, and more.
## Configuration
Hooks are configured in any Claude Code settings file. The top-level `hooks` key maps event names to an array of matcher objects.
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo 'About to run bash command' >&2"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "/usr/local/bin/lint-changed-file '$TOOL_INPUT'"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "notify-send 'Claude finished'"
}
]
}
]
}
}
```
### Settings file locations
| Scope | Path | Priority |
| ------- | ----------------------------- | -------- |
| User | `~/.claude/settings.json` | Low |
| Project | `.claude/settings.json` | Medium |
| Local | `.claude/settings.local.json` | High |
Higher-priority settings files take precedence. All hooks across all files run; they are not overridden.
### Matcher configuration
<ResponseField name="matcher" type="string">
A string pattern that filters when these hooks run. The field matched depends on the event:
* `PreToolUse` / `PostToolUse` / `PostToolUseFailure` / `PermissionRequest` / `PermissionDenied` — matched against `tool_name`
* `Notification` — matched against `notification_type`
* `SessionStart` — matched against `source` (`startup`, `resume`, `clear`, `compact`)
* `Setup` — matched against `trigger` (`init`, `maintenance`)
* `SubagentStart` / `SubagentStop` — matched against `agent_type`
* `PreCompact` / `PostCompact` — matched against `trigger` (`manual`, `auto`)
* `StopFailure` — matched against `error`
* `ConfigChange` — matched against `source`
* `InstructionsLoaded` — matched against `load_reason`
* `Elicitation` / `ElicitationResult` — matched against `mcp_server_name`
* `FileChanged` — matched against filenames (e.g., `".envrc|.env"`)
Omit `matcher` to run the hook for all instances of the event.
</ResponseField>
<ResponseField name="hooks" type="HookCommand[]" required>
One or more hook definitions to execute when the matcher fires.
</ResponseField>
***
## Hook types
### `command` — shell command
```json theme={null}
{
"type": "command",
"command": "jq '.tool_name' && my-validator",
"timeout": 30,
"shell": "bash",
"async": false,
"once": false,
"if": "Bash(git *)",
"statusMessage": "Validating command..."
}
```
The hook input JSON is piped to the command's stdin. The `CLAUDE_ENV_FILE` environment variable is set for `CwdChanged` and `FileChanged` hooks — write `export KEY=value` lines there to inject environment variables into subsequent Bash tool calls.
<ResponseField name="command" type="string" required>
Shell command to execute.
</ResponseField>
<ResponseField name="timeout" type="number">
Timeout in seconds. Defaults to the global hook timeout (60 s).
</ResponseField>
<ResponseField name="shell" type="'bash' | 'powershell'">
Shell interpreter. `bash` uses your `$SHELL` (bash/zsh/sh). Defaults to `bash`.
</ResponseField>
<ResponseField name="async" type="boolean">
When `true`, the hook runs in the background without blocking Claude. Output is ignored.
</ResponseField>
<ResponseField name="asyncRewake" type="boolean">
When `true`, the hook runs in the background but wakes the model if it exits with code 2. Implies `async: true`.
</ResponseField>
<ResponseField name="once" type="boolean">
When `true`, the hook runs once and is removed from the configuration after execution.
</ResponseField>
<ResponseField name="if" type="string">
Permission rule syntax (e.g., `"Bash(git *)"`) evaluated against the hook input. The hook is skipped if the condition does not match. Avoids spawning processes for non-matching tool calls.
</ResponseField>
<ResponseField name="statusMessage" type="string">
Custom message shown in the spinner while the hook runs.
</ResponseField>
### `prompt` — LLM evaluation
```json theme={null}
{
"type": "prompt",
"prompt": "Check whether this bash command is safe: $ARGUMENTS",
"model": "claude-haiku-4-5",
"timeout": 30
}
```
The `$ARGUMENTS` placeholder is replaced with the hook input JSON. The model's response is treated as the hook output.
<ResponseField name="prompt" type="string" required>
Prompt sent to the model. Use `$ARGUMENTS` to embed the hook input.
</ResponseField>
<ResponseField name="model" type="string">
Model to use. Defaults to the small fast model.
</ResponseField>
### `agent` — agentic verifier
```json theme={null}
{
"type": "agent",
"prompt": "Verify that unit tests ran and passed.",
"model": "claude-haiku-4-5",
"timeout": 120
}
```
Runs a short agentic loop that can call tools to verify the action. Use for `PostToolUse` hooks where you want the verifier to read files or run commands.
<ResponseField name="prompt" type="string" required>
Verification prompt. Use `$ARGUMENTS` to embed the hook input.
</ResponseField>
### `http` — HTTP endpoint
```json theme={null}
{
"type": "http",
"url": "https://my-server.example.com/hook",
"headers": {
"Authorization": "Bearer $MY_TOKEN"
},
"allowedEnvVars": ["MY_TOKEN"],
"timeout": 10
}
```
POSTs the hook input JSON to the given URL. Header values can reference environment variables using `$VAR_NAME` syntax, but only variables listed in `allowedEnvVars` are interpolated.
<ResponseField name="url" type="string" required>
URL to POST the hook input JSON to.
</ResponseField>
<ResponseField name="headers" type="Record<string, string>">
Additional request headers.
</ResponseField>
<ResponseField name="allowedEnvVars" type="string[]">
Environment variable names that may be interpolated in header values.
</ResponseField>
***
## Base hook input
Every hook receives a JSON object on stdin with these fields present for all event types.
<ResponseField name="hook_event_name" type="string" required>
The event that fired (e.g., `"PreToolUse"`).
</ResponseField>
<ResponseField name="session_id" type="string" required>
Current session identifier.
</ResponseField>
<ResponseField name="transcript_path" type="string" required>
Absolute path to the JSONL transcript file for this session.
</ResponseField>
<ResponseField name="cwd" type="string" required>
Current working directory at the time the hook fired.
</ResponseField>
<ResponseField name="permission_mode" type="string">
Active permission mode (`"default"`, `"acceptEdits"`, `"bypassPermissions"`, `"plan"`, `"dontAsk"`).
</ResponseField>
<ResponseField name="agent_id" type="string">
Subagent identifier. Present only when the hook fires from within a subagent. Use this field to distinguish subagent calls from main-thread calls.
</ResponseField>
<ResponseField name="agent_type" type="string">
Agent type name (e.g., `"general-purpose"`, `"code-reviewer"`). Present when the hook fires from a subagent, or on the main thread of a session started with `--agent`.
</ResponseField>
***
## Sync hook output (JSON on stdout)
For blocking hooks, write a JSON object to stdout before exiting. The schema is the same for all events, with event-specific fields nested under `hookSpecificOutput`.
```json theme={null}
{
"continue": true,
"suppressOutput": false,
"decision": "approve",
"reason": "Command looks safe",
"systemMessage": "The hook approved this action.",
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"additionalContext": "Verified by security scanner."
}
}
```
<ResponseField name="continue" type="boolean">
When `false`, Claude stops the current turn immediately.
</ResponseField>
<ResponseField name="suppressOutput" type="boolean">
When `true`, the hook's stdout is not shown in transcript mode.
</ResponseField>
<ResponseField name="decision" type="'approve' | 'block'">
Explicit approve/block decision. Takes effect only when the CLI reads it.
</ResponseField>
<ResponseField name="systemMessage" type="string">
Message injected into Claude's context as a system turn.
</ResponseField>
<ResponseField name="reason" type="string">
Human-readable reason for the decision. Shown to the user when a hook blocks an action.
</ResponseField>
<ResponseField name="hookSpecificOutput" type="object">
Event-specific output. See each event section below for the allowed fields.
</ResponseField>
***
## Hook events
### `PreToolUse`
Fires immediately before a tool executes. You can inspect the tool input, approve or block the call, or modify the input before it reaches the tool.
**When it fires:** Before every tool invocation.
**Input fields:**
<ResponseField name="tool_name" type="string">
Name of the tool about to run (e.g., `"Bash"`, `"Write"`, `"mcp__myserver__my_tool"`).
</ResponseField>
<ResponseField name="tool_input" type="unknown">
The raw tool input object as Claude submitted it.
</ResponseField>
<ResponseField name="tool_use_id" type="string">
Unique ID for this tool invocation.
</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | ----------------------------------------------------------- |
| `0` | Stdout/stderr not shown. Hook output JSON applied if valid. |
| `2` | Stderr shown to Claude; tool call is **blocked**. |
| Other | Stderr shown to user only; tool call continues. |
**`hookSpecificOutput` fields:**
<ResponseField name="hookEventName" type="literal: 'PreToolUse'" required>
Must be `"PreToolUse"`.
</ResponseField>
<ResponseField name="permissionDecision" type="'allow' | 'deny' | 'ask'">
Override the permission decision for this tool call. `"allow"` approves the call; `"deny"` blocks it; `"ask"` forces the permission dialog.
</ResponseField>
<ResponseField name="permissionDecisionReason" type="string">
Reason string shown to the user when the decision is `"deny"` or `"ask"`.
</ResponseField>
<ResponseField name="updatedInput" type="Record<string, unknown>">
Replacement tool input. When provided, the tool receives this object instead of Claude's original input.
</ResponseField>
<ResponseField name="additionalContext" type="string">
Text injected into Claude's context for this turn.
</ResponseField>
***
### `PostToolUse`
Fires after a tool completes successfully. You can observe the tool output or inject context for Claude to act on.
**When it fires:** After every successful tool execution.
**Input fields:**
<ResponseField name="tool_name" type="string">Tool that ran.</ResponseField>
<ResponseField name="tool_input" type="unknown">Input that was passed to the tool.</ResponseField>
<ResponseField name="tool_response" type="unknown">The tool's output.</ResponseField>
<ResponseField name="tool_use_id" type="string">Unique ID for this invocation.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | ------------------------------------------------------- |
| `0` | Stdout shown in transcript mode (Ctrl+O). |
| `2` | Stderr shown to Claude immediately as a system message. |
| Other | Stderr shown to user only. |
**`hookSpecificOutput` fields:**
<ResponseField name="additionalContext" type="string">
Context injected into Claude's conversation after the tool result.
</ResponseField>
<ResponseField name="updatedMCPToolOutput" type="unknown">
Replacement for the MCP tool's output. Only effective for MCP tool calls.
</ResponseField>
***
### `PostToolUseFailure`
Fires when a tool call ends in an error or is interrupted.
**When it fires:** When a tool throws or is aborted.
**Input fields:**
<ResponseField name="tool_name" type="string">Tool that failed.</ResponseField>
<ResponseField name="tool_input" type="unknown">Input that was passed to the tool.</ResponseField>
<ResponseField name="tool_use_id" type="string">Unique ID for this invocation.</ResponseField>
<ResponseField name="error" type="string">Error message from the tool.</ResponseField>
<ResponseField name="is_interrupt" type="boolean">Whether the failure was caused by an interrupt signal.</ResponseField>
**Exit codes:** Same as `PostToolUse`. Hook output and exit codes are logged but do not affect the failed tool result.
***
### `PermissionRequest`
Fires when a permission dialog would be shown to the user. Hooks can programmatically approve or deny without showing any UI.
**When it fires:** When Claude requests permission for a tool call and the default behavior is to prompt.
**Input fields:**
<ResponseField name="tool_name" type="string">Tool requesting permission.</ResponseField>
<ResponseField name="tool_input" type="unknown">Input the tool would receive if approved.</ResponseField>
<ResponseField name="permission_suggestions" type="PermissionUpdate[]">Suggested permission rules (allow/deny) that the UI would offer.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | -------------------------------------------------------------------------------------------------------- |
| `0` | Hook decision applied if `hookSpecificOutput.decision` is set; otherwise falls through to normal dialog. |
| Other | Stderr shown to user; falls through to normal dialog. |
**`hookSpecificOutput` fields:**
<ResponseField name="hookEventName" type="literal: 'PermissionRequest'" required>
Must be `"PermissionRequest"`.
</ResponseField>
<ResponseField name="decision" type="object">
The approval or denial decision.
<Expandable title="Allow decision">
```json theme={null}
{
"behavior": "allow",
"updatedInput": { ... },
"updatedPermissions": [...]
}
```
</Expandable>
<Expandable title="Deny decision">
```json theme={null}
{
"behavior": "deny",
"message": "Blocked by security policy.",
"interrupt": false
}
```
When `interrupt` is `true`, the current turn is aborted after denial.
</Expandable>
</ResponseField>
***
### `PermissionDenied`
Fires when a tool call is denied (by rules, mode, or classifier). You can instruct Claude to retry the action.
**When it fires:** After every permission denial.
**Input fields:**
<ResponseField name="tool_name" type="string">Denied tool.</ResponseField>
<ResponseField name="tool_input" type="unknown">Input that was denied.</ResponseField>
<ResponseField name="tool_use_id" type="string">Unique ID for this invocation.</ResponseField>
<ResponseField name="reason" type="string">Human-readable denial reason.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | -------------------------------- |
| `0` | Stdout shown in transcript mode. |
| Other | Stderr shown to user only. |
**`hookSpecificOutput` fields:**
<ResponseField name="retry" type="boolean">
When `true`, Claude is told it may retry the denied action.
</ResponseField>
***
### `Stop`
Fires just before Claude concludes its response for the current turn.
**When it fires:** When the model is about to stop and return control to the user.
**Input fields:**
<ResponseField name="stop_hook_active" type="boolean">
Whether a Stop hook is currently running (prevents infinite loops if your Stop hook itself would trigger a Stop).
</ResponseField>
<ResponseField name="last_assistant_message" type="string">
Text content of the last assistant message before stopping. Saves you from parsing the transcript file.
</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | --------------------------------------------------------------------------- |
| `0` | Stdout/stderr not shown. |
| `2` | Stderr injected as a system message; Claude **continues** the conversation. |
| Other | Stderr shown to user only; Claude stops. |
<Tip>
Use exit code 2 from a Stop hook to check Claude's output and keep the conversation going if a condition is unmet — for example, if tests are still failing.
</Tip>
***
### `StopFailure`
Fires instead of `Stop` when the turn ends due to an API error.
**When it fires:** When a rate limit, authentication failure, or other API error ends the turn.
**Input fields:**
<ResponseField name="error" type="'authentication_failed' | 'billing_error' | 'rate_limit' | 'invalid_request' | 'server_error' | 'unknown' | 'max_output_tokens'">
The error category.
</ResponseField>
<ResponseField name="error_details" type="string">
Detailed error message.
</ResponseField>
<ResponseField name="last_assistant_message" type="string">
Last assistant message text, if any was produced before the error.
</ResponseField>
**Behavior:** Fire-and-forget. Hook output and exit codes are ignored.
***
### `SubagentStart`
Fires when Claude spawns a subagent via the `Agent` tool.
**When it fires:** When an Agent tool call begins.
**Input fields:**
<ResponseField name="agent_id" type="string">Unique ID for this subagent instance.</ResponseField>
<ResponseField name="agent_type" type="string">Agent type name (e.g., `"general-purpose"`).</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | ---------------------------------------- |
| `0` | Stdout shown to the subagent as context. |
| Other | Stderr shown to user only. |
**`hookSpecificOutput` fields:**
<ResponseField name="additionalContext" type="string">
Context injected into the subagent's conversation at the start.
</ResponseField>
***
### `SubagentStop`
Fires just before a subagent concludes its response. Mirrors `Stop` but for subagents.
**When it fires:** When a subagent is about to return its result to the parent.
**Input fields:**
<ResponseField name="agent_id" type="string">Subagent instance ID.</ResponseField>
<ResponseField name="agent_type" type="string">Agent type name.</ResponseField>
<ResponseField name="agent_transcript_path" type="string">Path to the subagent's JSONL transcript.</ResponseField>
<ResponseField name="stop_hook_active" type="boolean">Whether a SubagentStop hook is already running.</ResponseField>
<ResponseField name="last_assistant_message" type="string">Last message from the subagent.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | --------------------------------------------------------- |
| `0` | Stdout/stderr not shown. |
| `2` | Stderr shown to subagent; subagent **continues** running. |
| Other | Stderr shown to user only; subagent stops. |
***
### `SessionStart`
Fires when a session begins. Use this to inject initial context or set up the environment.
**When it fires:** On session startup, resume, clear (`/clear`), or after compaction.
**Input fields:**
<ResponseField name="source" type="'startup' | 'resume' | 'clear' | 'compact'">
What triggered the session start.
</ResponseField>
<ResponseField name="model" type="string">Active model for the session.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | ------------------------------------------ |
| `0` | Stdout shown to Claude as initial context. |
| Other | Stderr shown to user only. |
**`hookSpecificOutput` fields:**
<ResponseField name="additionalContext" type="string">
Context injected into Claude's system prompt for this session.
</ResponseField>
<ResponseField name="initialUserMessage" type="string">
Auto-submitted as the first user message of the session.
</ResponseField>
<ResponseField name="watchPaths" type="string[]">
Absolute file paths to register with the `FileChanged` watcher.
</ResponseField>
***
### `SessionEnd`
Fires when a session is about to end.
**When it fires:** On clear, logout, prompt-input exit, or other termination reasons.
**Input fields:**
<ResponseField name="reason" type="'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other' | 'bypass_permissions_disabled'">
The reason the session is ending.
</ResponseField>
**Exit codes:** Exit code 0 completes successfully. Other exit codes show stderr to the user.
***
### `Setup`
Fires during repository initialization and maintenance checks.
**When it fires:** On `init` (first time Claude Code runs in a directory) or `maintenance` (periodic checks).
**Input fields:**
<ResponseField name="trigger" type="'init' | 'maintenance'">
What triggered the setup hook.
</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | ------------------------------------------------------- |
| `0` | Stdout shown to Claude. |
| Other | Stderr shown to user only. Blocking errors are ignored. |
**`hookSpecificOutput` fields:**
<ResponseField name="additionalContext" type="string">
Context provided to Claude for the setup phase.
</ResponseField>
***
### `PreCompact`
Fires before context compaction begins.
**When it fires:** Before the compaction summary is generated, whether triggered manually (`/compact`) or automatically.
**Input fields:**
<ResponseField name="trigger" type="'manual' | 'auto'">Whether compaction was requested by the user or triggered automatically.</ResponseField>
<ResponseField name="custom_instructions" type="string | null">Any custom compaction instructions already configured.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | -------------------------------------------------- |
| `0` | Stdout appended as custom compaction instructions. |
| `2` | Compaction is **blocked**. |
| Other | Stderr shown to user; compaction continues. |
***
### `PostCompact`
Fires after compaction completes.
**When it fires:** After the compaction summary has been generated and applied.
**Input fields:**
<ResponseField name="trigger" type="'manual' | 'auto'">How compaction was triggered.</ResponseField>
<ResponseField name="compact_summary" type="string">The summary produced by compaction.</ResponseField>
**Exit codes:** Exit code 0 shows stdout to the user. Other exit codes show stderr to the user.
***
### `UserPromptSubmit`
Fires when the user submits a prompt, before Claude processes it.
**When it fires:** Each time you press Enter with a message in the terminal.
**Input fields:**
<ResponseField name="prompt" type="string">The raw prompt text the user submitted.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | --------------------------------------------------------------------- |
| `0` | Stdout shown to Claude as additional context. |
| `2` | Processing **blocked**; original prompt erased; stderr shown to user. |
| Other | Stderr shown to user only. |
**`hookSpecificOutput` fields:**
<ResponseField name="additionalContext" type="string">
Context appended to Claude's view of the user message.
</ResponseField>
***
### `Notification`
Fires when Claude Code sends a notification (e.g., permission prompts, idle alerts).
**When it fires:** When a notification event is raised internally.
**Input fields:**
<ResponseField name="message" type="string">Notification message text.</ResponseField>
<ResponseField name="title" type="string">Notification title.</ResponseField>
<ResponseField name="notification_type" type="'permission_prompt' | 'idle_prompt' | 'auth_success' | 'elicitation_dialog' | 'elicitation_complete' | 'elicitation_response'">
The type of notification.
</ResponseField>
**Exit codes:** Exit code 0 produces no output. Other exit codes show stderr to the user.
***
### `Elicitation`
Fires when an MCP server requests user input. Hooks can auto-respond without showing the dialog.
**When it fires:** When an MCP server sends an elicitation request (a structured input form or URL).
**Input fields:**
<ResponseField name="mcp_server_name" type="string">Name of the MCP server requesting input.</ResponseField>
<ResponseField name="message" type="string">The prompt message from the server.</ResponseField>
<ResponseField name="mode" type="'form' | 'url'">Input mode.</ResponseField>
<ResponseField name="elicitation_id" type="string">Request identifier.</ResponseField>
<ResponseField name="requested_schema" type="Record<string, unknown>">JSON schema describing the expected input structure.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | ----------------------------------------------------------------------------- |
| `0` | Use hook response if `hookSpecificOutput` is provided; otherwise show dialog. |
| `2` | Deny the elicitation. |
| Other | Stderr shown to user only. |
**`hookSpecificOutput` fields:**
<ResponseField name="action" type="'accept' | 'decline' | 'cancel'">
The programmatic response to the elicitation.
</ResponseField>
<ResponseField name="content" type="Record<string, unknown>">
Form data to submit when `action` is `"accept"`.
</ResponseField>
***
### `ElicitationResult`
Fires after a user responds to an MCP elicitation. Hooks can observe or override the response.
**When it fires:** After the user (or an Elicitation hook) responds to the elicitation.
**Input fields:**
<ResponseField name="mcp_server_name" type="string">Name of the MCP server.</ResponseField>
<ResponseField name="elicitation_id" type="string">Request identifier.</ResponseField>
<ResponseField name="action" type="'accept' | 'decline' | 'cancel'">How the user responded.</ResponseField>
<ResponseField name="content" type="Record<string, unknown>">Submitted form data, if accepted.</ResponseField>
**`hookSpecificOutput` fields:**
<ResponseField name="action" type="'accept' | 'decline' | 'cancel'">
Override the user's action before it is sent to the server.
</ResponseField>
<ResponseField name="content" type="Record<string, unknown>">
Override the submitted content.
</ResponseField>
***
### `ConfigChange`
Fires when a settings file changes during a session.
**When it fires:** When `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills` files are modified on disk.
**Input fields:**
<ResponseField name="source" type="'user_settings' | 'project_settings' | 'local_settings' | 'policy_settings' | 'skills'">
Which settings source changed.
</ResponseField>
<ResponseField name="file_path" type="string">Absolute path to the changed file.</ResponseField>
**Exit codes:**
| Exit code | Effect |
| --------- | ------------------------------------------------------- |
| `0` | Allow the change to be applied. |
| `2` | **Block** the change from being applied to the session. |
| Other | Stderr shown to user only. |
***
### `InstructionsLoaded`
Fires when a CLAUDE.md or instruction rule file is loaded. This event is observability-only.
**When it fires:** When any instruction file is loaded into context.
**Input fields:**
<ResponseField name="file_path" type="string">Path to the loaded file.</ResponseField>
<ResponseField name="memory_type" type="'User' | 'Project' | 'Local' | 'Managed'">The memory scope of the file.</ResponseField>
<ResponseField name="load_reason" type="'session_start' | 'nested_traversal' | 'path_glob_match' | 'include' | 'compact'">Why the file was loaded.</ResponseField>
<ResponseField name="globs" type="string[]">The `paths:` frontmatter patterns that matched (if `load_reason` is `path_glob_match`).</ResponseField>
<ResponseField name="trigger_file_path" type="string">The file Claude accessed that caused this load (for `path_glob_match`).</ResponseField>
<ResponseField name="parent_file_path" type="string">The file that `@include`d this one (for `include`).</ResponseField>
**Behavior:** Blocking not supported. Exit code 0 completes normally. Other exit codes show stderr to the user.
***
### `WorktreeCreate`
Fires when Claude Code needs to create an isolated worktree. The hook is responsible for actually creating the worktree and reporting its path.
**When it fires:** When worktree isolation is requested for a task.
**Input fields:**
<ResponseField name="name" type="string">Suggested slug for the worktree directory.</ResponseField>
**Behavior:** Write the absolute path of the created worktree directory to stdout and exit with code 0. Any other exit code signals a failure.
***
### `WorktreeRemove`
Fires when Claude Code needs to remove a previously created worktree.
**When it fires:** When a worktree task completes and the worktree should be cleaned up.
**Input fields:**
<ResponseField name="worktree_path" type="string">Absolute path of the worktree to remove.</ResponseField>
**Behavior:** Exit code 0 means success. Other exit codes show stderr to the user.
***
### `CwdChanged`
Fires after the working directory changes.
**When it fires:** When Claude changes directories during a session.
**Input fields:**
<ResponseField name="old_cwd" type="string">Previous working directory.</ResponseField>
<ResponseField name="new_cwd" type="string">New working directory.</ResponseField>
**`hookSpecificOutput` fields:**
<ResponseField name="watchPaths" type="string[]">
Absolute paths to add to the `FileChanged` watcher. Return this to start watching files in the new directory.
</ResponseField>
The `CLAUDE_ENV_FILE` environment variable is set — write `export KEY=value` lines to apply environment variables to subsequent Bash tool commands.
***
### `FileChanged`
Fires when a watched file is modified, added, or removed.
**When it fires:** When a file registered via `SessionStart.watchPaths` or `CwdChanged.watchPaths` changes on disk.
**Input fields:**
<ResponseField name="file_path" type="string">Absolute path of the changed file.</ResponseField>
<ResponseField name="event" type="'change' | 'add' | 'unlink'">The type of filesystem event.</ResponseField>
**`hookSpecificOutput` fields:**
<ResponseField name="watchPaths" type="string[]">
Update the watch list with these absolute paths.
</ResponseField>
The `CLAUDE_ENV_FILE` environment variable is set for this hook as well.
***
## Async hooks
For hooks that need to run in the background without delaying Claude, output an async acknowledgment on stdout instead of the normal sync output:
```json theme={null}
{
"async": true,
"asyncTimeout": 30
}
```
<ResponseField name="async" type="literal: true" required>
Signals that this hook is running asynchronously.
</ResponseField>
<ResponseField name="asyncTimeout" type="number">
How long (in seconds) the async hook is allowed to run before it is cancelled.
</ResponseField>
<Warning>
Async hooks cannot block tool execution or inject context. Use them for side effects like notifications, logging, or metrics that must not slow down the agentic loop.
</Warning>
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,517 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# SDK overview
> Embed Claude Code in your own tools using the stdin/stdout control protocol. Reference for the SDK session API, message types, and output formats.
The Claude Code SDK is a control protocol for embedding Claude Code in other applications — IDEs, automation scripts, CI/CD pipelines, or any host that can spawn a subprocess and communicate over stdin/stdout.
Rather than exposing a library API directly, the SDK communicates with a running `claude` process over a structured JSON message stream. The host process sends user messages and control requests; the CLI process streams back assistant messages, tool progress events, and result payloads.
<Note>
The TypeScript types described on this page are exported from `@anthropic-ai/claude-code` under the `agentSdkTypes` entry point. Control protocol types (prefixed `SDKControl`) are `@alpha` and subject to change.
</Note>
## How it works
<Steps>
<Step title="Spawn a Claude Code process">
Start `claude` with `--output-format stream-json` and `--print` (non-interactive mode). Pipe its stdin and stdout into your host process.
```bash theme={null}
claude --output-format stream-json --print --verbose
```
For a persistent session that accepts multiple prompts over time, omit `--print` and instead send `SDKUserMessage` objects to stdin after the session initializes.
</Step>
<Step title="Send an initialize request">
Write a `control_request` with `subtype: "initialize"` to stdin. The CLI responds with an `SDKControlInitializeResponse` containing available commands, models, agents, and account information.
```json theme={null}
{
"type": "control_request",
"request_id": "init-1",
"request": {
"subtype": "initialize",
"systemPrompt": "You are a code reviewer.",
"appendSystemPrompt": "Always suggest tests."
}
}
```
</Step>
<Step title="Stream messages from stdout">
Read newline-delimited JSON from stdout. Each line is one of the `SDKMessage` union types — assistant turns, tool progress, system events, and result summaries.
</Step>
<Step title="Send user messages">
Write `SDKUserMessage` objects to stdin to continue the conversation. Each message contains an Anthropic API-compatible `message` payload.
</Step>
</Steps>
## Output formats
Pass `--output-format` to control what Claude Code writes to stdout.
| Format | Description |
| ------------- | --------------------------------------------------------------------------------------------------- |
| `text` | Plain text responses only. Default for interactive mode. |
| `json` | Single JSON object written at completion. Suitable for one-shot scripts. |
| `stream-json` | Newline-delimited JSON stream. One message per line, emitted as events occur. Required for SDK use. |
<Tip>
Use `stream-json` when you need to render progress incrementally or handle tool events. Use `json` when you only care about the final result.
</Tip>
## Control protocol messages
The control protocol uses two top-level envelope types that flow bidirectionally over stdin/stdout.
### `SDKControlRequest`
Sent **to** the CLI process to configure the session or issue commands.
```json theme={null}
{
"type": "control_request",
"request_id": "<unique-string>",
"request": { "subtype": "...", ...payload }
}
```
<ResponseField name="type" type="literal: 'control_request'" required>
Always `"control_request"`.
</ResponseField>
<ResponseField name="request_id" type="string" required>
Unique identifier for this request. The CLI echoes it back in the corresponding `control_response`.
</ResponseField>
<ResponseField name="request" type="SDKControlRequestInner" required>
The request payload. `subtype` identifies which operation to perform.
</ResponseField>
### `SDKControlResponse`
Emitted **from** the CLI process in response to a `control_request`.
```json theme={null}
{
"type": "control_response",
"response": {
"subtype": "success",
"request_id": "<echoed-id>",
"response": { ...payload }
}
}
```
On error, `subtype` is `"error"` and the `error` field contains a human-readable message.
***
## Initialize request and response
The `initialize` request is the first control message you must send. It configures the session and returns available capabilities.
### `SDKControlInitializeRequest`
```json theme={null}
{
"type": "control_request",
"request_id": "init-1",
"request": {
"subtype": "initialize",
"systemPrompt": "You are a CI automation agent.",
"appendSystemPrompt": "Always add test coverage.",
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hookCallbackIds": ["my-hook-id"]
}
]
},
"agents": {
"CodeReviewer": {
"description": "Reviews code for quality and security.",
"prompt": "You are an expert code reviewer...",
"model": "opus"
}
}
}
}
```
<ResponseField name="subtype" type="literal: 'initialize'" required>
Identifies this as an initialize request.
</ResponseField>
<ResponseField name="systemPrompt" type="string">
Replaces the default system prompt for this session.
</ResponseField>
<ResponseField name="appendSystemPrompt" type="string">
Appended to the system prompt without replacing it. Use this to add context while keeping the default behavior.
</ResponseField>
<ResponseField name="hooks" type="Record<HookEvent, SDKHookCallbackMatcher[]>">
Registers SDK-side hook callbacks. The CLI calls back into the SDK process when hook events fire. See [Hooks reference](/reference/sdk/hooks-reference).
</ResponseField>
<ResponseField name="sdkMcpServers" type="string[]">
Names of in-process SDK MCP servers (created with `createSdkMcpServer`) to connect to this session.
</ResponseField>
<ResponseField name="agents" type="Record<string, AgentDefinition>">
Custom subagent definitions available to the `Agent` tool during this session.
<Expandable title="AgentDefinition fields">
<ResponseField name="description" type="string" required>
Natural language description of when Claude should invoke this agent.
</ResponseField>
<ResponseField name="prompt" type="string" required>
System prompt for this agent.
</ResponseField>
<ResponseField name="model" type="string">
Model alias (`"sonnet"`, `"opus"`, `"haiku"`) or full model ID. Defaults to inheriting the parent model.
</ResponseField>
<ResponseField name="tools" type="string[]">
Allow-list of tool names. When omitted, the agent inherits all tools.
</ResponseField>
<ResponseField name="disallowedTools" type="string[]">
Tools explicitly blocked for this agent.
</ResponseField>
<ResponseField name="maxTurns" type="number">
Maximum agentic turns before the agent stops.
</ResponseField>
<ResponseField name="permissionMode" type="PermissionMode">
Override permission mode for this agent. See [Permissions API](/reference/sdk/permissions-api).
</ResponseField>
</Expandable>
</ResponseField>
### `SDKControlInitializeResponse`
The CLI responds with the session's current capabilities.
```json theme={null}
{
"type": "control_response",
"response": {
"subtype": "success",
"request_id": "init-1",
"response": {
"commands": [...],
"agents": [...],
"output_style": "stream-json",
"available_output_styles": ["text", "json", "stream-json"],
"models": [...],
"account": {
"email": "user@example.com",
"organization": "Acme Corp",
"apiProvider": "firstParty"
}
}
}
}
```
<ResponseField name="commands" type="SlashCommand[]">
Available slash commands (e.g., `/compact`, `/cost`). Each entry has `name`, `description`, and `argumentHint`.
</ResponseField>
<ResponseField name="agents" type="AgentInfo[]">
Available subagent types. Each has `name`, `description`, and an optional `model`.
</ResponseField>
<ResponseField name="output_style" type="string">
The active output format (`"stream-json"`, `"json"`, `"text"`).
</ResponseField>
<ResponseField name="models" type="ModelInfo[]">
Available models for this account.
<Expandable title="ModelInfo fields">
<ResponseField name="value" type="string">
Model identifier for API calls (e.g., `"claude-sonnet-4-6"`).
</ResponseField>
<ResponseField name="displayName" type="string">
Human-readable name (e.g., `"Claude Sonnet 4.6"`).
</ResponseField>
<ResponseField name="supportsEffort" type="boolean">
Whether this model supports effort levels.
</ResponseField>
<ResponseField name="supportsAdaptiveThinking" type="boolean">
Whether this model supports adaptive thinking (Claude decides when and how much to think).
</ResponseField>
</Expandable>
</ResponseField>
<ResponseField name="account" type="AccountInfo">
Logged-in account details.
<Expandable title="AccountInfo fields">
<ResponseField name="email" type="string">
Account email address.
</ResponseField>
<ResponseField name="organization" type="string">
Organization name.
</ResponseField>
<ResponseField name="subscriptionType" type="string">
Subscription tier.
</ResponseField>
<ResponseField name="apiProvider" type="'firstParty' | 'bedrock' | 'vertex' | 'foundry'">
Active API backend. Anthropic OAuth only applies when `"firstParty"`.
</ResponseField>
</Expandable>
</ResponseField>
***
## User messages
Send user messages to stdin to drive the conversation forward.
### `SDKUserMessage`
```json theme={null}
{
"type": "user",
"message": {
"role": "user",
"content": "Refactor this function to use async/await."
},
"parent_tool_use_id": null
}
```
<ResponseField name="type" type="literal: 'user'" required>
Always `"user"`.
</ResponseField>
<ResponseField name="message" type="APIUserMessage" required>
An Anthropic API-compatible user message. `content` can be a string or a content block array (for images and other media).
</ResponseField>
<ResponseField name="parent_tool_use_id" type="string | null" required>
Tool use ID this message is responding to, or `null` for top-level user messages.
</ResponseField>
<ResponseField name="uuid" type="string">
Optional UUID to track this message. Echoed back in related events.
</ResponseField>
<ResponseField name="priority" type="'now' | 'next' | 'later'">
Scheduling hint for async message queuing.
</ResponseField>
***
## SDK message stream types
Claude Code emits a stream of JSON messages to stdout. The `type` field identifies each message.
<AccordionGroup>
<Accordion title="system — session initialization">
Emitted once at session start with `subtype: "init"`. Contains the active model, tool list, MCP server statuses, permission mode, and session ID.
```json theme={null}
{
"type": "system",
"subtype": "init",
"model": "claude-sonnet-4-6",
"tools": ["Bash", "Read", "Write", "Edit", "Glob", "Grep"],
"mcp_servers": [],
"permissionMode": "default",
"session_id": "abc123",
"uuid": "..."
}
```
</Accordion>
<Accordion title="assistant — model response">
Emitted when the model produces a turn. Contains the full Anthropic API response object, including any `tool_use` blocks.
```json theme={null}
{
"type": "assistant",
"message": { "role": "assistant", "content": [...] },
"parent_tool_use_id": null,
"uuid": "...",
"session_id": "abc123"
}
```
</Accordion>
<Accordion title="stream_event — partial streaming tokens">
Emitted during streaming with `RawMessageStreamEvent` payloads. Use these to render incremental output.
</Accordion>
<Accordion title="tool_progress — long-running tool status">
Emitted periodically for tools that take more than a few seconds (e.g., Bash commands). Contains `tool_name`, `tool_use_id`, and elapsed time.
</Accordion>
<Accordion title="result — final turn summary">
Emitted at the end of each turn. `subtype` is `"success"` or one of the error subtypes.
```json theme={null}
{
"type": "result",
"subtype": "success",
"result": "The function has been refactored.",
"duration_ms": 4200,
"total_cost_usd": 0.0042,
"num_turns": 3,
"is_error": false,
"stop_reason": "end_turn",
"session_id": "abc123",
"uuid": "..."
}
```
Error subtypes: `"error_during_execution"`, `"error_max_turns"`, `"error_max_budget_usd"`, `"error_max_structured_output_retries"`.
</Accordion>
<Accordion title="system — status updates">
Emitted with `subtype: "status"` when the permission mode or session status changes (e.g., `"compacting"`).
</Accordion>
</AccordionGroup>
***
## Other control requests
Beyond `initialize`, the control protocol exposes these operations.
| `subtype` | Direction | Description |
| --------------------- | ---------- | --------------------------------------------------------------------- |
| `interrupt` | host → CLI | Interrupt the current turn. |
| `set_permission_mode` | host → CLI | Change the active permission mode. |
| `set_model` | host → CLI | Switch to a different model mid-session. |
| `can_use_tool` | CLI → host | Permission request for a tool call (requires SDK permission handler). |
| `mcp_status` | host → CLI | Get MCP server connection statuses. |
| `mcp_set_servers` | host → CLI | Replace dynamically managed MCP servers. |
| `get_context_usage` | host → CLI | Get context window usage breakdown. |
| `get_settings` | host → CLI | Read the effective merged settings. |
| `apply_flag_settings` | host → CLI | Merge settings into the flag settings layer. |
| `rewind_files` | host → CLI | Revert file changes made since a given message. |
| `hook_callback` | CLI → host | Deliver a hook event for an SDK-registered hook callback. |
| `reload_plugins` | host → CLI | Reload plugins from disk. |
***
## Session management API
For scripting scenarios, the SDK exports functions that operate on saved session transcripts stored in `~/.claude/`.
```typescript theme={null}
import {
query,
listSessions,
getSessionInfo,
getSessionMessages,
forkSession,
renameSession,
tagSession,
} from '@anthropic-ai/claude-code'
```
<AccordionGroup>
<Accordion title="query — run a prompt">
The primary SDK entry point. Accepts a `prompt` string or `AsyncIterable<SDKUserMessage>` and returns an async iterable of `SDKMessage`.
```typescript theme={null}
for await (const message of query({
prompt: 'What files are in this directory?',
options: { cwd: '/my/project' }
})) {
if (message.type === 'result') {
console.log(message.result)
}
}
```
</Accordion>
<Accordion title="listSessions — list saved sessions">
Returns session metadata for a project directory. Pass `dir` to scope to a specific project, or omit to list all sessions.
```typescript theme={null}
const sessions = await listSessions({ dir: '/my/project', limit: 50 })
```
</Accordion>
<Accordion title="getSessionMessages — read a transcript">
Parses the JSONL transcript file for a session and returns messages in chronological order.
```typescript theme={null}
const messages = await getSessionMessages(sessionId, {
dir: '/my/project',
includeSystemMessages: false,
})
```
</Accordion>
<Accordion title="forkSession — branch a conversation">
Copies a session's transcript into a new session with remapped UUIDs. Supports `upToMessageId` to fork from a specific point.
```typescript theme={null}
const { sessionId: newId } = await forkSession(originalSessionId, {
upToMessageId: 'msg-uuid',
title: 'Experimental branch',
})
```
</Accordion>
<Accordion title="renameSession and tagSession">
```typescript theme={null}
await renameSession(sessionId, 'My refactor session')
await tagSession(sessionId, 'needs-review')
await tagSession(sessionId, null) // clear tag
```
</Accordion>
</AccordionGroup>
***
## Use cases
<Tabs>
<Tab title="IDE integration">
IDEs can spawn a persistent Claude Code process and route messages through the control protocol. Send the `initialize` request with a custom `systemPrompt` that describes the IDE context, then forward user messages from the editor's chat panel. Use `PreToolUse` hook callbacks to intercept file edits and display diffs in the IDE's native UI before they are applied.
</Tab>
<Tab title="CI/CD automation">
In CI pipelines, use `--output-format json` and `--print` for one-shot tasks:
```bash theme={null}
result=$(echo "Review the diff and output pass/fail" | \
claude --output-format json --print \
--permission-mode bypassPermissions)
```
Parse the `result` field from the JSON output to extract the agent's response programmatically.
</Tab>
<Tab title="Headless agents">
For long-running background agents, use `query()` from the TypeScript SDK with a streaming output format. Combine with `watchScheduledTasks` (internal) to fire tasks on cron schedules while keeping a persistent daemon process that maintains the WebSocket connection to claude.ai.
</Tab>
</Tabs>
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,473 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# Permissions API
> Reference for permission modes, allow/deny rule syntax, and configuration methods for controlling which tools Claude Code can use without prompting.
The permissions system controls whether Claude Code runs a tool immediately, prompts you for confirmation, or blocks the call entirely. You configure it through permission modes and rule lists that can be set globally, per project, or per session.
## Permission modes
A permission mode sets the baseline behavior for all tool calls. Individual allow/deny rules can override this baseline for specific tools or commands.
| Mode | Description |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `default` | Prompt for approval on potentially dangerous operations. Safe read-only tools run without prompting. |
| `acceptEdits` | Auto-approve all file edit operations (`Write`, `Edit`, `MultiEdit`). Bash commands still prompt. |
| `bypassPermissions` | Skip all permission checks. All tools run without prompting. Requires `allowDangerouslySkipPermissions: true` in settings. |
| `plan` | Read-only planning mode. No tool execution; Claude can only read files and explain what it would do. |
| `dontAsk` | Do not prompt the user. Deny any tool call that is not pre-approved by an explicit allow rule. |
<Warning>
`bypassPermissions` mode disables all safeguards. Only use it in sandboxed environments or CI pipelines where you fully control the input. The mode requires `allowDangerouslySkipPermissions: true` in your settings file.
</Warning>
### Setting the permission mode
<Tabs>
<Tab title="CLI flag">
Pass `--permission-mode` to set the mode for a single invocation:
```bash theme={null}
claude --permission-mode acceptEdits
claude --permission-mode bypassPermissions --dangerously-skip-permissions
claude --permission-mode plan
```
</Tab>
<Tab title="Settings file">
Set `defaultPermissionMode` in any Claude Code settings file to make it the default for all sessions in that scope:
```json theme={null}
{
"defaultPermissionMode": "acceptEdits"
}
```
Settings files load in this priority order (highest wins):
* `.claude/settings.local.json` — local overrides, not committed
* `.claude/settings.json` — project-level defaults
* `~/.claude/settings.json` — user-level defaults
</Tab>
<Tab title="/permissions command">
Run `/permissions` inside a session to open the interactive permissions panel where you can view and edit allow/deny rules. Session-level changes are not persisted to disk.
```
/permissions
```
</Tab>
<Tab title="SDK control request">
Change the permission mode programmatically via the control protocol:
```json theme={null}
{
"type": "control_request",
"request_id": "pm-1",
"request": {
"subtype": "set_permission_mode",
"mode": "acceptEdits"
}
}
```
</Tab>
</Tabs>
***
## Permission rules
Rules let you pre-approve or block specific tools and commands without changing the global permission mode. Rules are additive across settings scopes — allow rules from all files merge together.
### Configuration format
```json theme={null}
{
"permissions": {
"allow": [
"Bash(git *)",
"Bash(npm run *)",
"Read",
"Write(src/**)",
"mcp__myserver"
],
"deny": [
"Bash(rm -rf *)",
"Bash(curl * | bash)",
"Write(/etc/**)"
]
}
}
```
<ResponseField name="allow" type="string[]">
Rules that auto-approve matching tool calls without prompting.
</ResponseField>
<ResponseField name="deny" type="string[]">
Rules that unconditionally block matching tool calls.
</ResponseField>
<Note>
Deny rules always take precedence over allow rules. If both an allow rule and a deny rule match a tool call, the call is blocked.
</Note>
### Rule syntax
A rule is a string that matches a tool name, optionally with a parenthesized content pattern.
**Tool name only** — matches every call to that tool:
```
Read
Write
Edit
Bash
```
**Tool name with content pattern** — matches calls where the tool's primary input matches the glob:
```
Bash(git *)
Bash(npm run *)
Write(src/*)
Edit(*.ts)
```
For `Bash`, the pattern is matched against the full command string. For file tools (`Write`, `Edit`, `Read`, `Glob`), the pattern is matched against the file path argument.
**MCP server** — matches all tools from a specific MCP server:
```
mcp__myserver
```
**MCP server wildcard** — same as above, explicit wildcard form:
```
mcp__myserver__*
```
**Specific MCP tool** — matches one tool from a server:
```
mcp__myserver__query_database
```
**Agent type** — blocks or allows a specific subagent:
```
Agent(Explore)
Agent(CodeReviewer)
```
### Pattern matching for `Bash`
Bash rule patterns use shell-style glob matching on the full command string.
```json theme={null}
{
"permissions": {
"allow": [
"Bash(git status)",
"Bash(git log *)",
"Bash(git diff *)",
"Bash(npm run test*)",
"Bash(make *)"
],
"deny": [
"Bash(rm *)",
"Bash(sudo *)",
"Bash(* | bash)",
"Bash(* | sh)"
]
}
}
```
<Warning>
Bash patterns match prefix-first. A rule like `Bash(git *)` matches `git status`, `git log --oneline`, and `git push --force`. Be specific when writing deny rules.
</Warning>
### Pattern matching for file tools
File path patterns are matched against the absolute path of the file being read, written, or edited.
```json theme={null}
{
"permissions": {
"allow": [
"Write(src/**)",
"Write(tests/**)",
"Edit(*.md)",
"Read"
],
"deny": [
"Write(/etc/**)",
"Write(~/.ssh/**)",
"Edit(.env*)"
]
}
}
```
***
## Permission rule sources and priority
Rules are collected from multiple sources and evaluated in a defined order. When the same tool call matches rules from different sources, deny takes precedence over allow, and the most restrictive result wins.
| Source | Where configured | Editable |
| ----------------- | -------------------------------------------- | -------------- |
| `policySettings` | Managed policy layer | No |
| `flagSettings` | CLI flags and SDK control requests | Per-session |
| `userSettings` | `~/.claude/settings.json` | Yes |
| `projectSettings` | `.claude/settings.json` | Yes |
| `localSettings` | `.claude/settings.local.json` | Yes |
| `cliArg` | `--allowedTools` / `--disallowedTools` flags | Per-invocation |
| `session` | `/permissions` command, SDK updates | Per-session |
### `--allowedTools` and `--disallowedTools` CLI flags
Pass comma-separated rule strings directly on the command line:
```bash theme={null}
claude --allowedTools "Bash(git *),Read,Write" --print "Run the tests"
claude --disallowedTools "Bash,Write" --print "Summarize this project"
```
These map to the `cliArg` source and apply for the duration of the invocation.
***
## Permission decisions
The permission engine evaluates each tool call through a pipeline and returns one of three outcomes.
| Decision | Meaning |
| -------- | ------------------------------------------------------ |
| `allow` | Tool runs immediately. |
| `ask` | User is prompted for confirmation. |
| `deny` | Tool call is blocked; Claude receives an error result. |
### Decision pipeline
Claude Code evaluates tool calls in this order:
1. **Deny rules** — if any deny rule matches, the call is blocked immediately.
2. **Ask rules** — if any ask rule matches, the permission dialog is shown.
3. **Tool's own permission check** — the tool's `checkPermissions` method runs (e.g., Bash checks individual subcommands).
4. **Safety checks** — paths inside `.git/`, `.claude/`, `.vscode/`, and shell config files always prompt, even in `bypassPermissions` mode.
5. **Mode check** — `bypassPermissions` and plan mode apply here.
6. **Allow rules** — if an allow rule matches, the call is approved.
7. **Default behavior** — if no rule matched, prompt the user.
<Note>
Safety checks (step 4) are bypass-immune. Even with `bypassPermissions` mode, Claude Code will prompt before modifying files in `.git/` or shell configuration files like `~/.bashrc`.
</Note>
***
## Working directories
By default, Claude Code restricts file operations to the current working directory and its subdirectories. You can grant access to additional directories.
### Via CLI flag
```bash theme={null}
claude --add-dir /path/to/extra/dir
```
### Via settings
```json theme={null}
{
"permissions": {
"additionalDirectories": [
"/shared/data",
"/home/user/configs"
]
}
}
```
### Via SDK control request
```json theme={null}
{
"type": "control_request",
"request_id": "dirs-1",
"request": {
"subtype": "apply_flag_settings",
"settings": {
"permissions": {
"additionalDirectories": ["/shared/data"]
}
}
}
}
```
***
## Permission updates via the SDK
SDK hosts (IDEs, desktop apps) can respond to `can_use_tool` control requests and include permission updates to persist rule changes alongside their decisions.
### `PermissionUpdate` object
```json theme={null}
{
"type": "addRules",
"rules": [
{ "toolName": "Bash", "ruleContent": "git *" }
],
"behavior": "allow",
"destination": "userSettings"
}
```
<ResponseField name="type" type="'addRules' | 'replaceRules' | 'removeRules' | 'setMode' | 'addDirectories' | 'removeDirectories'" required>
The update operation.
</ResponseField>
<ResponseField name="rules" type="PermissionRuleValue[]">
Rules to add, replace, or remove. Each rule has `toolName` and an optional `ruleContent` (the parenthesized pattern).
</ResponseField>
<ResponseField name="behavior" type="'allow' | 'deny' | 'ask'" required>
Which rule list to modify.
</ResponseField>
<ResponseField name="destination" type="'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'" required>
Where to persist the update. `session` applies only to the current session; `userSettings`, `projectSettings`, and `localSettings` write to the corresponding settings files on disk.
</ResponseField>
### Permission decision response
When responding to a `can_use_tool` request, include `updatedPermissions` to persist rule changes:
```json theme={null}
{
"type": "control_response",
"response": {
"subtype": "success",
"request_id": "<request_id>",
"response": {
"behavior": "allow",
"updatedPermissions": [
{
"type": "addRules",
"rules": [{ "toolName": "Bash", "ruleContent": "git *" }],
"behavior": "allow",
"destination": "userSettings"
}
],
"decisionClassification": "user_permanent"
}
}
}
```
<ResponseField name="behavior" type="'allow' | 'deny'" required>
The permission decision.
</ResponseField>
<ResponseField name="updatedInput" type="Record<string, unknown>">
Modified tool input to use instead of the original. Only valid when `behavior` is `"allow"`.
</ResponseField>
<ResponseField name="updatedPermissions" type="PermissionUpdate[]">
Permission rule updates to apply and persist alongside this decision.
</ResponseField>
<ResponseField name="decisionClassification" type="'user_temporary' | 'user_permanent' | 'user_reject'">
How the user responded, for telemetry. `user_temporary` for allow-once; `user_permanent` for always-allow; `user_reject` for deny.
</ResponseField>
***
## Hooks and permissions
`PreToolUse` and `PermissionRequest` hooks can inject permission decisions programmatically. See [Hooks reference](/reference/sdk/hooks-reference) for details on `permissionDecision` output and `hookSpecificOutput.decision`.
The hook-based permission flow is especially useful for headless agents that cannot show interactive prompts. When `shouldAvoidPermissionPrompts` is true (background agent mode), Claude Code runs `PermissionRequest` hooks before falling back to auto-deny.
***
## Safety recommendations
<AccordionGroup>
<Accordion title="CI/CD pipelines">
Use `bypassPermissions` only in isolated, short-lived environments where you control all inputs. Set explicit deny rules for destructive operations as a defense-in-depth measure:
```json theme={null}
{
"defaultPermissionMode": "bypassPermissions",
"allowDangerouslySkipPermissions": true,
"permissions": {
"deny": [
"Bash(rm -rf *)",
"Bash(sudo *)",
"Bash(curl * | bash)"
]
}
}
```
</Accordion>
<Accordion title="IDE and interactive use">
Use `default` mode with allow rules for common safe operations. This minimizes interruptions while keeping you in control of destructive actions:
```json theme={null}
{
"defaultPermissionMode": "default",
"permissions": {
"allow": [
"Read",
"Glob",
"Grep",
"Bash(git status)",
"Bash(git log *)",
"Bash(git diff *)",
"Bash(npm run *)",
"Bash(make *)"
]
}
}
```
</Accordion>
<Accordion title="Code review and read-only analysis">
Use `plan` mode when you want Claude to reason about code without making any changes. Claude can read files and explain what it would do, but cannot write, edit, or run commands:
```bash theme={null}
claude --permission-mode plan "Explain the architecture of this codebase"
```
</Accordion>
<Accordion title="Automated agents with human approval">
Use `dontAsk` mode combined with an SDK `PermissionRequest` hook to replace the interactive dialog with your own approval UI. The hook receives every tool call that would have prompted and can allow, deny, or forward it to a human reviewer:
```json theme={null}
{
"defaultPermissionMode": "dontAsk",
"permissions": {
"allow": [
"Read",
"Bash(git *)"
]
}
}
```
Any tool call not matching an allow rule is sent to your `PermissionRequest` hook handler instead of being auto-denied.
</Accordion>
</AccordionGroup>
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,225 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# Agent & Task Tools
> Spawn sub-agents for complex tasks and track work with a structured todo list.
Claude Code has two meta-tools for managing complex, multi-step work: `Task` (also called the Agent tool) for launching autonomous sub-agents, and `TodoWrite` for maintaining a structured task list within a session.
***
## Task (Agent tool)
Launches a specialized sub-agent to handle a complex task autonomously. The sub-agent runs independently, uses its own set of tools, and returns a single result message when it finishes.
### Parameters
<ParamField body="prompt" type="string" required>
The full task description for the agent. Since sub-agents start with no knowledge of the parent conversation, the prompt must be self-contained — include relevant file paths, line numbers, context, and any constraints. Terse command-style prompts produce shallow results.
</ParamField>
<ParamField body="description" type="string" required>
A short (35 word) label describing what the agent will do. Shown in the UI.
</ParamField>
<ParamField body="subagent_type" type="string">
The type of specialized agent to use (e.g., `"code-reviewer"`, `"test-runner"`). When omitted, the general-purpose agent is used. Available agent types are listed in the system prompt.
</ParamField>
<ParamField body="model" type="string">
Optional model override: `"sonnet"`, `"opus"`, or `"haiku"`. Takes precedence over the agent definition's configured model. Omit to inherit from the agent definition or parent.
</ParamField>
<ParamField body="run_in_background" type="boolean">
When `true`, the agent runs in the background. Claude is notified when it completes and should not poll or sleep while waiting. Use background mode when you have genuinely independent work to continue in the meantime.
</ParamField>
<ParamField body="isolation" type="string">
Isolation mode for the agent's filesystem context:
* `"worktree"` — agent runs in a temporary git worktree (isolated copy of the repo). The worktree is cleaned up automatically if the agent makes no changes; otherwise the path and branch are returned.
</ParamField>
<ParamField body="cwd" type="string">
Absolute path to use as the working directory for all filesystem and shell operations inside the agent. Mutually exclusive with `isolation: "worktree"`.
</ParamField>
<ParamField body="name" type="string">
A name for the spawned agent. Makes it addressable via `SendMessage({ to: name })` while it is running.
</ParamField>
### How sub-agents work
Each agent invocation starts with zero conversation context. The agent:
1. Receives its own system prompt and the `prompt` you provide
2. Has access to a tool set defined by its `subagent_type` (or all tools for the general-purpose agent)
3. Runs autonomously until the task is complete
4. Returns a single result message back to the parent
The result is **not** shown directly to the user — Claude summarizes it in a follow-up message.
<Warning>
Never write "based on your findings, fix the bug" or similar delegation phrases. Prompts that push synthesis back onto the agent produce generic work. Include concrete file paths, line numbers, and specific instructions in the prompt.
</Warning>
### When to use the Task tool
<Tabs>
<Tab title="Good use cases">
* Open-ended research that requires multiple rounds of searching and reading
* Running a test suite and analyzing failures after code changes
* Independent code review by a fresh agent with no prior context bias
* Long-running operations that can proceed while Claude handles other requests
* Tasks that would generate noisy intermediate output you don't need in the main context
</Tab>
<Tab title="When NOT to use it">
* Reading a specific file — use the `Read` tool directly
* Searching for a class definition — use `Grep` directly
* Searching within 23 known files — use `Read` directly
* Simple tasks unrelated to the available agent types
</Tab>
</Tabs>
### Parallel agents
When tasks are independent, Claude launches multiple agents in a single message:
```
Task({ description: "Run tests", prompt: "Run the full test suite..." })
Task({ description: "Check types", prompt: "Run tsc --noEmit and report errors..." })
```
Both agents run concurrently. When both complete, Claude synthesizes the results.
### Resuming agents
To send a follow-up message to a running or completed agent, use `SendMessage` with the agent's `name` as the `to` field. The agent resumes with its full context preserved.
### Writing effective prompts
<Accordion title="Brief like a colleague joining mid-task">
The agent knows nothing about your session. Treat the prompt like a complete briefing for a smart colleague who just arrived:
* What you're trying to accomplish and why
* What you've already tried or ruled out
* The specific files, functions, or systems involved
* What form the result should take ("report in under 200 words", "make the fix directly", etc.)
</Accordion>
<Accordion title="Lookups vs. investigations">
* **Lookups**: hand over the exact command or query. The agent should not need to figure out what to run.
* **Investigations**: hand over the question, not prescribed steps. Over-specifying steps for open-ended problems causes the agent to waste effort on a wrong path.
</Accordion>
***
## TodoWrite
Maintains a structured task list for the current session. Claude uses this tool proactively to track progress, organize multi-step work, and provide visibility into what it is doing.
### Parameters
<ParamField body="todos" type="TodoItem[]" required>
The complete, updated todo list. Each call **replaces** the entire list — there is no incremental add or remove.
</ParamField>
### TodoItem schema
Each item in the `todos` array has the following fields:
<ParamField body="content" type="string" required>
The task description in imperative form — what needs to be done. Example: `"Run tests"`, `"Fix authentication bug"`.
</ParamField>
<ParamField body="activeForm" type="string" required>
The present-continuous form of the task description, shown while the task is in progress. Example: `"Running tests"`, `"Fixing authentication bug"`.
</ParamField>
<ParamField body="status" type="string" required>
The current state of the task. One of:
| Value | Meaning |
| ------------- | ------------------------- |
| `pending` | Not yet started |
| `in_progress` | Currently being worked on |
| `completed` | Finished successfully |
Exactly one task should be `in_progress` at any time.
</ParamField>
### How Claude uses TodoWrite
Claude calls `TodoWrite` proactively when:
* A task requires **3 or more distinct steps**
* Work is non-trivial and benefits from structured tracking
* The user provides a list of multiple things to do
* New sub-tasks are discovered mid-implementation
Claude does **not** use `TodoWrite` for:
* Single-step tasks
* Trivial operations (e.g., adding a comment, running one command)
* Purely informational or conversational responses
### Task lifecycle
<Accordion title="Starting work">
Claude marks a task `in_progress` **before** beginning, not after. This ensures the UI reflects what is actively happening.
```json theme={null}
{ "content": "Add dark mode toggle", "activeForm": "Adding dark mode toggle", "status": "in_progress" }
```
</Accordion>
<Accordion title="Completing work">
Claude marks a task `completed` immediately when it finishes — it does not batch completions. A task is only marked complete when:
* Implementation is fully done
* No tests are failing
* No unresolved errors remain
</Accordion>
<Accordion title="Handling blockers">
If a task cannot be completed (missing file, failing test, unresolved error), Claude keeps it `in_progress` and creates a new `pending` task describing what needs to be resolved first.
</Accordion>
<Accordion title="Clearing the list">
When all tasks are marked `completed`, Claude clears the list automatically. An empty list signals that all requested work is done.
</Accordion>
### Example list
```json theme={null}
{
"todos": [
{
"content": "Add dark mode CSS variables",
"activeForm": "Adding dark mode CSS variables",
"status": "completed"
},
{
"content": "Implement theme context provider",
"activeForm": "Implementing theme context provider",
"status": "in_progress"
},
{
"content": "Update existing components to use theme",
"activeForm": "Updating existing components to use theme",
"status": "pending"
},
{
"content": "Run tests and build",
"activeForm": "Running tests and build",
"status": "pending"
}
]
}
```
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,170 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# Bash
> Execute shell commands in a persistent bash session.
The `Bash` tool runs shell commands and returns their output. Commands execute in a persistent bash session — the working directory is preserved between calls, though the shell state (variables, aliases, functions) is re-initialized from the user's profile on each invocation.
<Note>
Claude prefers dedicated tools (`Read`, `Edit`, `Glob`, `Grep`) over Bash equivalents for file operations. Bash is reserved for tasks where no purpose-built tool applies.
</Note>
## Parameters
<ParamField body="command" type="string" required>
The shell command to execute. Supports all standard bash syntax including pipes, redirections, and compound operators (`&&`, `||`, `;`).
</ParamField>
<ParamField body="timeout" type="number">
Maximum execution time in milliseconds. Defaults to **120,000 ms (2 minutes)**. Maximum allowed value is **600,000 ms (10 minutes)**.
Both values can be overridden at runtime via `BASH_DEFAULT_TIMEOUT_MS` and `BASH_MAX_TIMEOUT_MS` environment variables.
</ParamField>
<ParamField body="description" type="string">
A short human-readable description of what the command does. Shown in the UI when Claude explains its actions.
</ParamField>
<ParamField body="run_in_background" type="boolean">
When `true`, the command runs in the background. Claude is notified when it completes and does not need to poll for results. Do not append `&` to the command when using this parameter — background execution is handled internally.
</ParamField>
## Session behavior
The bash session persists working directory across calls but does **not** persist:
* Shell variables set in previous commands
* Aliases or functions
* `cd` changes (Claude uses absolute paths instead)
Claude initializes each session from the user's shell profile (`bash` or `zsh`).
## Timeouts
| Setting | Default | Max |
| --------------- | ------------------- | --- |
| Default timeout | 120,000 ms (2 min) | — |
| Maximum timeout | 600,000 ms (10 min) | — |
Pass a `timeout` value (in milliseconds) to override the default for a specific command.
## Permission model
Every Bash command passes through a permission check before execution. The outcome is one of:
* **Allow** — command matches an existing allow rule or is classified as read-only
* **Ask** — command requires user approval before running
* **Deny** — command matches an explicit deny rule and is blocked
### Allow rules
Rules are matched by exact command, prefix (`git commit:*`), or wildcard pattern. Safe wrapper commands (`timeout`, `time`, `nice`, `nohup`) and safe environment variable assignments (`NODE_ENV=prod`, `GOARCH=arm64`) are stripped before matching so prefix rules work correctly.
### Read-only auto-allow
Commands that only read state (e.g., `ls`, `cat`, `git log`, `grep`) are automatically allowed without a prompt.
### Security restrictions
Claude's security layer checks each command for patterns that commonly indicate injection or obfuscation attempts. Commands containing the following require explicit user approval:
* Command substitution: `` `...` ``, `$()`, `${}`
* Process substitution: `<()`, `>()`
* Input/output redirections (`<`, `>`) in suspicious contexts
* Zsh-specific constructs: `zmodload`, `emulate -c`, `ztcp`, `zsocket`
* ANSI-C quoting (`$'...'`) or locale quoting (`$"..."`)
* IFS variable manipulation (`$IFS`)
* Access to `/proc/*/environ`
* Newlines or carriage returns in non-quoted positions
<Warning>
Commands are split into subcommands before permission checking. A rule like `Bash(ls:*)` will **not** match `ls /tmp && rm -rf /` — the `rm -rf /` subcommand is checked separately.
</Warning>
## Background execution
<Tabs>
<Tab title="Foreground (default)">
```json theme={null}
{
"command": "npm run build",
"description": "Build the project"
}
```
Claude waits for the command to finish and receives its output immediately.
</Tab>
<Tab title="Background">
```json theme={null}
{
"command": "npm run dev",
"description": "Start dev server",
"run_in_background": true
}
```
The command starts and Claude continues without blocking. A notification arrives when the process finishes.
</Tab>
</Tabs>
## Examples
<Accordion title="Running tests">
```bash theme={null}
pytest tests/ -x --tb=short
```
Run a test suite and stop on the first failure.
</Accordion>
<Accordion title="Git operations">
```bash theme={null}
git status && git diff --staged
```
Check working tree status and staged changes in a single compound command.
<Note>
Claude follows a strict protocol for `git commit` and `git push` — it never amends pushed commits, never skips hooks with `--no-verify`, and never force-pushes to `main`/`master` without explicit user instruction.
</Note>
</Accordion>
<Accordion title="Installing dependencies">
```bash theme={null}
npm install
```
Standard package installation. Claude stages related commands in parallel when they are independent.
</Accordion>
<Accordion title="Long-running server with timeout override">
```json theme={null}
{
"command": "cargo build --release",
"timeout": 300000,
"description": "Release build (up to 5 min)"
}
```
Override the 2-minute default for commands known to take longer.
</Accordion>
## Tool preference
Claude uses Bash only when no purpose-built tool is available:
| Task | Preferred tool |
| ----------------------------- | -------------- |
| Find files by name | `Glob` |
| Search file contents | `Grep` |
| Read a file | `Read` |
| Edit a file | `Edit` |
| Write a new file | `Write` |
| Shell commands, builds, tests | **Bash** |
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,157 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# File Operations
> Read, edit, and write files on the local filesystem.
Claude Code has three dedicated tools for working with files: `Read` for reading content, `Edit` for precise in-place edits, and `Write` for creating or fully rewriting files.
<Tip>
Prefer `Edit` over `Write` when modifying existing files — `Edit` sends only the changed fragment, saving context and reducing the chance of unintended overwrites.
</Tip>
***
## Read
Reads a file from the local filesystem and returns its contents with line numbers.
### Parameters
<ParamField body="file_path" type="string" required>
Absolute path to the file. Relative paths are not accepted.
</ParamField>
<ParamField body="offset" type="number">
Line number to start reading from (1-indexed). Use this with `limit` to read a specific section of a large file.
</ParamField>
<ParamField body="limit" type="number">
Maximum number of lines to return. Defaults to **2,000** lines. For files longer than this, call `Read` again with a higher `offset` to page through the content.
</ParamField>
### Output format
Results use `cat -n` style formatting: each line is prefixed with its 1-indexed line number.
```
1 import { z } from 'zod'
2
3 export const schema = z.object({
4 name: z.string(),
5 })
```
Claude preserves exact indentation from this output when constructing `Edit` calls.
### Supported file types
| Type | Behavior |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Text files | Returns raw text with line numbers |
| Images (PNG, JPG, etc.) | Displayed visually — Claude is multimodal |
| PDF files | Returned as document content. For PDFs over 10 pages, use the `pages` parameter (e.g., `"1-5"`). Maximum 20 pages per request. |
| Jupyter notebooks (`.ipynb`) | All cells and outputs are returned, combining code, text, and visualizations |
<Note>
`Read` cannot list directories. To inspect a directory's contents, use `ls` via the `Bash` tool.
</Note>
### Caching
If a file has not changed since the last `Read` call in the same conversation, Claude receives a cached stub instead of re-reading the file. This avoids redundant reads on unchanged files.
***
## Edit
Performs exact string replacement within a file.
### Parameters
<ParamField body="file_path" type="string" required>
Absolute path to the file to modify.
</ParamField>
<ParamField body="old_string" type="string" required>
The exact string to find and replace. Must match the file content character-for-character, including whitespace and indentation.
</ParamField>
<ParamField body="new_string" type="string" required>
The replacement string. Use an empty string to delete `old_string`.
</ParamField>
<ParamField body="replace_all" type="boolean">
When `true`, replaces every occurrence of `old_string` in the file instead of only the first. Useful for renaming variables or symbols that appear multiple times.
</ParamField>
### How Edit works
`Edit` finds the literal text in `old_string` inside the file and substitutes it with `new_string`. No regex interpretation occurs — the match is a plain string comparison.
<Warning>
The tool **fails** if `old_string` appears more than once in the file and `replace_all` is not set. Provide enough surrounding context in `old_string` to make it unique, or set `replace_all: true` to update all occurrences.
</Warning>
### Pre-read requirement
Claude must call `Read` on a file at least once in the conversation before calling `Edit` on it. The tool enforces this to prevent edits based on stale or assumed content.
### Indentation matching
When Claude derives `old_string` from `Read` output, it uses the content that appears **after** the line-number prefix. For example, given:
```
12 const x = 1
```
The `old_string` is ` const x = 1` (six leading spaces), not ` 12 const x = 1`.
***
## Write
Creates a new file or fully overwrites an existing one.
### Parameters
<ParamField body="file_path" type="string" required>
Absolute path to the file to create or overwrite.
</ParamField>
<ParamField body="content" type="string" required>
The complete content to write to the file. If the file already exists, it is replaced entirely.
</ParamField>
### When to use Write vs Edit
<Tabs>
<Tab title="Use Edit">
* Modifying one or more sections of an existing file
* Renaming a variable or symbol across the file
* Adding or removing a block of code
Edit is preferred because it transmits only the changed fragment.
</Tab>
<Tab title="Use Write">
* Creating a new file from scratch
* Completely rewriting a file (e.g., regenerating a config from new requirements)
* When the new content is entirely different from the original
Write replaces the entire file in one call.
</Tab>
</Tabs>
### Pre-read requirement
When overwriting an existing file, Claude must call `Read` first. Write enforces this to prevent unintentional data loss.
<Warning>
Claude does not proactively create documentation files (`*.md`, `README.*`) unless explicitly instructed. Write follows the same principle.
</Warning>
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,187 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# Search
> Find files by name pattern and search file contents with regular expressions.
Claude Code has two dedicated search tools: `Glob` for finding files by name and `Grep` for searching file contents. Both are preferred over running `find` or `grep` as Bash commands — they have correct permission integration, return results sorted by modification time, and produce structured output Claude can act on directly.
***
## Glob
Finds files whose paths match a glob pattern. Results are sorted by modification time (most recently modified first).
### Parameters
<ParamField body="pattern" type="string" required>
A glob pattern to match file paths against. Supports `*` (any characters within a path segment), `**` (any number of path segments), and `?` (single character).
</ParamField>
<ParamField body="path" type="string">
The directory to search in. Defaults to the current working directory. Must be an existing directory path — omit the parameter entirely to use the default; do not pass `null` or `"undefined"`.
</ParamField>
### Output
Returns a list of matching file paths, relative to the working directory, sorted by modification time. Results are capped at **100 files**. If the result is truncated, consider narrowing the pattern or specifying a more specific `path`.
### Pattern examples
| Pattern | Matches |
| ---------------------------- | ----------------------------------------------- |
| `**/*.ts` | All TypeScript files anywhere in the tree |
| `src/**/*.tsx` | All TSX files under `src/` |
| `*.json` | JSON files in the current directory only |
| `**/{package,tsconfig}.json` | `package.json` and `tsconfig.json` at any depth |
| `tools/*/prompt.ts` | `prompt.ts` one level inside `tools/` |
<Tip>
Use `Glob` when you know the filename or extension you're looking for. For open-ended exploration that requires multiple rounds of searching, use the `Task` (Agent) tool instead.
</Tip>
***
## Grep
Searches file contents using regular expressions, powered by ripgrep. Returns matching file paths, line numbers, and (optionally) matching lines.
### Parameters
<ParamField body="pattern" type="string" required>
A regular expression to search for in file contents. Supports full regex syntax: character classes, quantifiers, lookaheads, alternation, etc.
Ripgrep syntax differs from POSIX `grep` in one notable way: literal braces must be escaped. Use `interface\{\}` to find `interface{}` in Go code.
</ParamField>
<ParamField body="path" type="string">
File or directory to search in. Defaults to the current working directory. Can be a single file path to restrict the search.
</ParamField>
<ParamField body="glob" type="string">
Glob pattern to filter which files are searched (e.g., `"*.js"`, `"*.{ts,tsx}"`). Maps to `rg --glob`.
</ParamField>
<ParamField body="type" type="string">
Ripgrep file type to restrict the search (e.g., `"js"`, `"py"`, `"rust"`, `"go"`, `"java"`). More efficient than `glob` for standard file type filtering. Maps to `rg --type`.
</ParamField>
<ParamField body="output_mode" type="string">
Controls what is returned. Options:
* `"files_with_matches"` *(default)* — returns file paths only
* `"content"` — returns matching lines with context support
* `"count"` — returns match counts per file
</ParamField>
<ParamField body="-i" type="boolean">
Case-insensitive search. Maps to `rg -i`.
</ParamField>
<ParamField body="-n" type="boolean">
Show line numbers in output. Applies to `output_mode: "content"` only. Defaults to `true`.
</ParamField>
<ParamField body="-A" type="number">
Lines of context to show after each match. Applies to `output_mode: "content"` only. Maps to `rg -A`.
</ParamField>
<ParamField body="-B" type="number">
Lines of context to show before each match. Applies to `output_mode: "content"` only. Maps to `rg -B`.
</ParamField>
<ParamField body="context" type="number">
Lines of context to show before and after each match (equivalent to `rg -C`). Takes precedence over `-A` and `-B`. Applies to `output_mode: "content"` only.
</ParamField>
<ParamField body="multiline" type="boolean">
Enable multiline mode where `.` matches newlines and patterns can span multiple lines (`rg -U --multiline-dotall`). Default: `false`.
</ParamField>
<ParamField body="head_limit" type="number">
Limit output to the first N lines or entries (equivalent to `| head -N`). Applies across all output modes. Defaults to **250**. Pass `0` for unlimited results.
</ParamField>
<ParamField body="offset" type="number">
Skip the first N entries before applying `head_limit` (equivalent to `| tail -n +N`). Useful for paginating large result sets. Defaults to `0`.
</ParamField>
### Output modes
<Tabs>
<Tab title="files_with_matches (default)">
Returns a list of file paths that contain at least one match, sorted by modification time.
```
Found 3 files
src/utils/permissions/bashClassifier.ts
src/tools/BashTool/BashTool.tsx
src/tools/BashTool/bashPermissions.ts
```
</Tab>
<Tab title="content">
Returns the matching lines themselves, with optional surrounding context.
```
src/utils/permissions/bashClassifier.ts:42:export function classifyBashCommand(
src/utils/permissions/bashClassifier.ts:43: command: string,
```
</Tab>
<Tab title="count">
Returns match counts per file.
```
src/utils/permissions/bashClassifier.ts:7
src/tools/BashTool/bashPermissions.ts:3
Found 10 total occurrences across 2 files.
```
</Tab>
</Tabs>
### Pattern syntax notes
<Accordion title="Escaping braces for Go / TypeScript">
Ripgrep treats `{` and `}` as literal characters by default, unlike some regex engines that use them for quantifiers. To search for literal braces, escape them:
```
interface\{\} → finds interface{}
map\[string\] → finds map[string]
```
</Accordion>
<Accordion title="Multiline patterns">
By default, `.` does not match newlines. To search across line boundaries:
```json theme={null}
{
"pattern": "struct \\{[\\s\\S]*?field",
"multiline": true
}
```
</Accordion>
<Accordion title="Combining glob and type filters">
`glob` and `type` can be used independently or together:
```json theme={null}
{ "pattern": "TODO", "type": "ts" }
```
```json theme={null}
{ "pattern": "TODO", "glob": "src/**/*.ts" }
```
Use `type` for standard language types; use `glob` when the file set doesn't align with a named type.
</Accordion>
### Excluded directories
Grep automatically excludes version-control metadata directories: `.git`, `.svn`, `.hg`, `.bzr`, `.jj`, `.sl`.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,154 @@
> ## Documentation Index
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
> Use this file to discover all available pages before exploring further.
# Web
> Fetch web pages and search the internet for current information.
Claude Code has two web tools: `WebFetch` for retrieving and analyzing specific URLs, and `WebSearch` for querying the web when information may be beyond Claude's training cutoff.
***
## WebFetch
Fetches a URL, converts the HTML to markdown, and then processes the content using a small fast model with a prompt you provide. Returns the model's response — not the raw page content.
### Parameters
<ParamField body="url" type="string" required>
A fully-formed, valid URL. HTTP URLs are automatically upgraded to HTTPS.
</ParamField>
<ParamField body="prompt" type="string" required>
A natural-language prompt describing what to extract or analyze from the page content. The fetched content is passed to a secondary model along with this prompt, and the model's response is returned.
</ParamField>
### Behavior
1. Claude fetches the URL and converts HTML to markdown.
2. The markdown and the `prompt` are sent to a small, fast model.
3. That model's response is returned as the tool result.
Because a secondary model processes the content, the result is always a synthesized answer — not a raw dump of the page. If the content is very large, it may be summarized automatically.
<Info>
WebFetch includes a 15-minute in-memory cache. Repeated calls to the same URL within that window return cached content without a network request.
</Info>
### Redirects
When a URL redirects to a different host, the tool returns a special message indicating the redirect destination rather than following it automatically. Claude then makes a new `WebFetch` call with the redirect URL.
### Limitations
* Read-only — does not submit forms or interact with pages
* Not suitable for pages requiring authentication (login walls, paywalls)
* For GitHub resources, prefer the `gh` CLI via `Bash` (e.g., `gh pr view`, `gh issue view`, `gh api`)
<Tip>
If an MCP-provided web fetch tool is available in your environment, it may have fewer restrictions and should be preferred over this built-in tool.
</Tip>
### Example usage
<Tabs>
<Tab title="Extract API details">
```json theme={null}
{
"url": "https://docs.example.com/api/authentication",
"prompt": "What authentication methods are supported and what headers are required?"
}
```
</Tab>
<Tab title="Check library version">
```json theme={null}
{
"url": "https://github.com/some-org/some-lib/blob/main/CHANGELOG.md",
"prompt": "What changed in the latest version?"
}
```
</Tab>
<Tab title="Read documentation">
```json theme={null}
{
"url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API",
"prompt": "Summarize the Fetch API and show a basic usage example."
}
```
</Tab>
</Tabs>
***
## WebSearch
Searches the web and returns results including titles, URLs, and a model-synthesized summary. Useful when information may be newer than Claude's training data.
<Info>
Web search is only available in the United States. It requires a compatible API provider (Anthropic first-party, Vertex AI with Claude 4.0+ models, or Foundry).
</Info>
### Parameters
<ParamField body="query" type="string" required>
The search query to execute. Minimum length: 2 characters.
</ParamField>
<ParamField body="allowed_domains" type="string[]">
When set, only return results from these domains. Cannot be combined with `blocked_domains` in the same request.
Example: `["docs.python.org", "peps.python.org"]`
</ParamField>
<ParamField body="blocked_domains" type="string[]">
Exclude results from these domains. Cannot be combined with `allowed_domains` in the same request.
Example: `["w3schools.com"]`
</ParamField>
### Output
The tool returns search results as structured blocks containing:
* Result titles and URLs
* A synthesized summary produced by a model that has access to the search results
Claude is required to cite sources from web searches by appending a `Sources:` section with markdown hyperlinks to its response.
### Domain filtering
<Accordion title="Restricting to specific domains (allowed_domains)">
Use `allowed_domains` when you want results exclusively from trusted or authoritative sources:
```json theme={null}
{
"query": "Python asyncio best practices 2024",
"allowed_domains": ["docs.python.org", "realpython.com"]
}
```
</Accordion>
<Accordion title="Excluding domains (blocked_domains)">
Use `blocked_domains` to suppress low-quality or paywalled sources:
```json theme={null}
{
"query": "React server components tutorial",
"blocked_domains": ["medium.com"]
}
```
</Accordion>
### Search limits
Each `WebSearch` invocation performs up to **8 individual web searches** internally. Claude automatically refines queries as needed within that budget.
### Current date awareness
When searching for recent information, Claude includes the current year in search queries to avoid returning outdated results — for example, appending the year when searching for library documentation or current events.
Built with [Mintlify](https://mintlify.com).