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,126 @@
> ## 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.
# How Claude Code works
> The agentic loop, context loading, tool execution model, and conversation lifecycle under the hood.
Claude Code is a terminal-based coding agent that runs a continuous agentic loop: it reads your request, reasons about what to do, calls tools, observes results, and repeats until the task is complete or it needs your input.
## The agentic loop
Every interaction follows the same fundamental cycle:
<Steps>
<Step title="User sends a message">
You type a message in the terminal (interactive mode) or pass one via `--print` / stdin (non-interactive / headless mode). The message is appended to the conversation history.
</Step>
<Step title="Context is assembled">
Before calling the model, Claude Code assembles a system prompt that includes: the current date, git status (branch, recent commits, working-tree status), any loaded CLAUDE.md memory files, and the list of available tools. This context is built once per conversation and memoized — see [`context.ts`](/concepts/memory-context).
</Step>
<Step title="Claude reasons and selects tools">
The assembled conversation is sent to the Anthropic API. The model reasons about the task and emits one or more `tool_use` blocks — each specifying a tool name and structured JSON input.
</Step>
<Step title="Permission check">
Before executing each tool call, Claude Code evaluates the current permission mode and any allow/deny rules. Depending on the mode, it either auto-approves, prompts you for confirmation, or blocks the call entirely. See [Permissions](/concepts/permissions).
</Step>
<Step title="Tool executes and returns a result">
Approved tool calls run. Results — file contents, command output, search hits — are appended to the conversation as `tool_result` blocks.
</Step>
<Step title="Loop continues">
The model receives the tool results and either calls more tools or produces a final text response. The loop repeats until no tool calls remain in a model turn.
</Step>
</Steps>
<Note>
The loop runs entirely in your terminal process. There is no remote execution server — your files, shell, and credentials never leave your machine unless a tool explicitly sends them (e.g., `WebFetch`, `WebSearch`, or an MCP server).
</Note>
## Context loading
At the start of each conversation, Claude Code builds two context blocks that are prepended to every API call:
<Tabs>
<Tab title="System context">
Assembled by `getSystemContext()` in `context.ts`. Contains:
* **Git status** — current branch, default/main branch, git username, `git status --short` output (truncated to 2 000 characters if larger), and the last 5 commits from `git log --oneline`.
* **Cache-breaking injection** — an optional ephemeral string used internally to bust the server-side prompt cache during debugging.
Git status is skipped when `CLAUDE_CODE_REMOTE=1` is set (remote/cloud mode) or when git instructions are disabled in settings.
</Tab>
<Tab title="User context">
Assembled by `getUserContext()` in `context.ts`. Contains:
* **CLAUDE.md memory** — all memory files discovered by the 4-level hierarchy (managed → user → project → local). Disabled by `CLAUDE_CODE_DISABLE_CLAUDE_MDS=1` or in bare mode without explicit `--add-dir`. See [Memory & context](/concepts/memory-context).
* **Current date** — injected as `Today's date is YYYY-MM-DD` so the model always knows the date.
</Tab>
</Tabs>
Both context blocks are **memoized** for the duration of the conversation using `lodash/memoize`. Calling `setSystemPromptInjection()` clears the caches immediately.
## Tool execution model
Claude Code does not execute tool calls autonomously by default. Each tool has a `checkPermissions` method, and the result determines what happens next:
| Permission result | What happens |
| ----------------- | ------------------------------------------------------ |
| `allow` | Tool runs immediately, result appended to conversation |
| `ask` | Claude Code pauses and renders a confirmation dialog |
| `deny` | Tool call is rejected; Claude receives an error result |
The permission behavior is controlled by the active [permission mode](/concepts/permissions) and any configured allow/deny rules. In `bypassPermissions` mode all checks are skipped. In `acceptEdits` mode file-edit tools are auto-approved but bash commands still prompt.
Tool calls that are safe and read-only (e.g., `Read`, `Glob`, `Grep`) are generally auto-approved across all modes.
## Interactive vs. non-interactive (task) mode
<CardGroup cols={2}>
<Card title="Interactive (REPL) mode" icon="terminal">
The default experience. Claude Code renders a live terminal UI using React/Ink. You see streaming output, tool-use confirmations, and spinner animations as the agent works. Messages persist across the session until you exit.
</Card>
<Card title="Non-interactive / print mode" icon="file-code">
Activated with `--print` or by piping stdin. No UI is rendered. Output is written to stdout so it can be captured by scripts or CI pipelines. Useful for one-shot automation tasks.
</Card>
</CardGroup>
### Sub-agents (Task tool)
Claude can spawn sub-agents via the `Task` tool (`AgentTool`). Each sub-agent runs its own nested agentic loop with an isolated conversation and, optionally, a restricted tool set. Sub-agents can run locally (in-process) or on remote compute. Results are returned to the parent agent when the sub-agent completes. See [Tools](/concepts/tools) for details.
## Conversation storage and resumption
Conversations are stored as JSON transcript files on disk (in `~/.claude/` by default). Each conversation has a unique session ID. You can resume a previous conversation with `--resume <session-id>` or pick from the list with `--resume` alone.
When a conversation is resumed:
* The full message history is loaded from disk.
* Memory files are re-discovered and may differ from when the conversation was first started.
* The permission mode resets to the configured default unless it was persisted in the session.
<Tip>
Long conversations are periodically **compacted** — the oldest messages are summarised to keep the context window manageable. The full raw transcript is always preserved on disk; compaction only affects what is sent to the API.
</Tip>
## The query engine
Under the hood, each "turn" in the agentic loop is driven by a **query** — a call to `query.ts` that sends the current message list to the Anthropic API and streams back the response. The query engine handles:
* Streaming token output to the terminal in real time.
* Dispatching `tool_use` blocks to the appropriate tool handlers.
* Enforcing per-turn token and tool-call budgets.
* Collecting tool results and appending them before the next model call.
* Triggering compaction when the context window fills up.
Each tool has a `maxResultSizeChars` property. When a result exceeds this limit the content is saved to a temporary file and the model receives a preview with the file path, preventing context-window overflow from large outputs.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,206 @@
> ## 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.
# Memory and context (CLAUDE.md)
> How Claude Code discovers, loads, and prioritises CLAUDE.md memory files to give Claude persistent, project-aware instructions.
Claude Code supports a layered memory system based on plain Markdown files. By writing instructions into `CLAUDE.md` files at different levels of your filesystem, you can customise Claude's behaviour globally, per-project, or per-user — and keep some instructions private while committing others to source control.
## The 4-level memory hierarchy
Memory files are loaded in the following order (from lowest to highest priority). Files loaded **later** take precedence because the model pays more attention to instructions that appear later in the context window.
<Steps>
<Step title="Managed memory (lowest priority)">
**Path:** `/etc/claude-code/CLAUDE.md` (or the platform equivalent configured by your organisation)
System-wide instructions set by an administrator or deployment tool. Applies to all users on the machine. Also supports a `rules/` subdirectory at `managed claude rules dir`. Cannot be overridden by user or project files when enforced via policy settings.
</Step>
<Step title="User memory">
**Path:** `~/.claude/CLAUDE.md` and `~/.claude/rules/*.md`
Your private global instructions that apply to every project. A good place for personal preferences like preferred code style, default language, or your git username. This file is never committed to any repository.
</Step>
<Step title="Project memory">
**Paths (checked in each ancestor directory, from root down to CWD):**
* `CLAUDE.md`
* `.claude/CLAUDE.md`
* `.claude/rules/*.md`
Instructions checked into the codebase and shared with the whole team. Ideal for project conventions, architecture notes, testing commands, and anything that every contributor should follow. Committed to source control.
</Step>
<Step title="Local memory (highest priority)">
**Path:** `CLAUDE.local.md` (checked in each ancestor directory)
Private project-specific overrides. This file should be added to `.gitignore`. Use it for personal workflow preferences that apply only to this project — local environment paths, personal shortcuts, or instructions you don't want to share.
</Step>
</Steps>
<Info>
Files closer to the current working directory are loaded **later** and therefore have **higher priority**. A `CLAUDE.md` in your project root outweighs one in a parent directory.
</Info>
## File discovery algorithm
When Claude Code starts, it walks the filesystem from the current working directory **up to the filesystem root**, collecting memory files at each level. The walk is performed by `getMemoryFiles()` in `utils/claudemd.ts`.
The discovery order ensures lower-priority files appear first in the assembled context:
1. Managed files are loaded first.
2. User files are loaded next.
3. Project and local files are loaded by iterating the path from the **root downward to CWD** — so ancestor directories come before child directories.
<Note>
The full list of discovered files is memoised for the duration of the conversation. Use `/memory` to open the memory editor and force a reload, or restart the session to pick up changes made outside Claude Code.
</Note>
## The `@include` directive
Memory files can reference other files using `@` notation. The referenced file is inserted into the context as a separate entry before the including file.
```markdown theme={null}
# My project CLAUDE.md
@./docs/architecture.md
@./docs/conventions/typescript.md
Always run `bun test` before committing.
```
**Supported path forms:**
| Syntax | Resolves to |
| ------------------ | ------------------------------------------------- |
| `@filename` | Relative path from the including file's directory |
| `@./relative/path` | Explicit relative path |
| `@~/home/path` | Path relative to the user's home directory |
| `@/absolute/path` | Absolute path |
**Rules:**
* `@include` paths inside fenced code blocks and inline code spans are **ignored** — only plain text nodes are processed.
* Circular references are detected and skipped.
* Non-existent files are silently ignored.
* Maximum include depth is **5 levels**.
* Only text-based file types are included (`.md`, `.ts`, `.py`, `.json`, etc.). Binary files such as images and PDFs are skipped.
<Warning>
By default, `@include` paths that point outside the current project directory require explicit approval. Claude Code will display a warning and ask for confirmation the first time an external include is detected.
</Warning>
## `.claude/rules/*.md` — granular rule files
Instead of putting everything in one large `CLAUDE.md`, you can split instructions across multiple Markdown files inside `.claude/rules/`:
```
my-project/
├── CLAUDE.md
└── .claude/
└── rules/
├── testing.md
├── typescript-style.md
└── git-workflow.md
```
All `.md` files in `.claude/rules/` (and subdirectories) are loaded automatically for the project and user memory levels. Rules files also support **path-scoped frontmatter**:
```markdown theme={null}
---
paths:
- "src/api/**"
- "src/services/**"
---
Always use dependency injection. Never import concrete implementations directly.
```
When `paths` is set, the rule file is only injected into context when Claude is working on a file that matches one of the glob patterns. This keeps context lean for large projects.
## Maximum file size
The recommended maximum for any single memory file is **40 000 characters** (`MAX_MEMORY_CHARACTER_COUNT`). Files that exceed this limit are flagged, and Claude may not read the full content. Keep memory files focused and concise.
## How memory affects Claude's behaviour
When memory files are loaded, they are assembled into a single context block prefixed with:
> *"Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written."*
This means instructions in CLAUDE.md files take precedence over Claude's built-in defaults. Use this to enforce project conventions, restrict certain operations, or inject domain knowledge.
## When to use each level
<AccordionGroup>
<Accordion title="Use managed memory for…">
Organisation-wide policies, security guardrails, or deployment-specific configuration that every user on a machine must follow. Managed by system administrators, not individual developers.
</Accordion>
<Accordion title="Use user memory (~/.claude/CLAUDE.md) for…">
Personal preferences that apply across all projects: your preferred language for responses, commit message style, editor shortcuts, or personal aliases. This is private and never committed.
</Accordion>
<Accordion title="Use project memory (CLAUDE.md) for…">
Project conventions shared with your team: how to run tests, build commands, architecture decisions, naming conventions, PR checklist items, or links to internal documentation. Commit this file.
</Accordion>
<Accordion title="Use local memory (CLAUDE.local.md) for…">
Your personal overrides for a specific project: local environment paths, personal debugging notes, or workflow preferences that differ from the team defaults. Add this to `.gitignore`.
</Accordion>
</AccordionGroup>
## Example CLAUDE.md
```markdown theme={null}
# My Project
## Commands
- Build: `bun run build`
- Test: `bun test`
- Lint: `bun run lint`
- Type check: `bun run typecheck`
## Architecture
This is a monorepo. Core logic lives in `packages/core`. The CLI entrypoint is `src/index.ts`.
## Conventions
- Use `zod/v4` for all schema validation.
- Never use `any` — prefer `unknown` with a type guard.
- All async functions must handle errors explicitly; never swallow exceptions.
- Tests go in `__tests__/` next to the source file they test.
## Git
- Branch names: `feat/<ticket>-short-description`
- Always run `bun test && bun run typecheck` before committing.
- Do not include `console.log` statements in committed code.
@./docs/api-conventions.md
```
## The `/memory` command
Run `/memory` inside the Claude Code REPL to open the memory file editor. It shows you which memory files are currently loaded, lets you edit them directly, and reloads the context when you save.
<Tip>
You can ask Claude directly: *"Add a rule to CLAUDE.md that we always use 2-space indentation."* Claude will locate the appropriate memory file and write the instruction for you.
</Tip>
## Disabling memory loading
| Method | Effect |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `CLAUDE_CODE_DISABLE_CLAUDE_MDS=1` | Disables all memory file loading entirely |
| `--bare` flag | Skips auto-discovery of memory files from the CWD walk; only loads files from explicitly provided `--add-dir` directories |
| `claudeMdExcludes` setting | Glob patterns of memory file paths to skip (e.g., to exclude a noisy ancestor `CLAUDE.md`) |
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,222 @@
> ## 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
> How Claude Code controls which operations Claude can perform automatically versus which require your explicit approval.
Claude Code runs tools on your local machine — executing shell commands, editing files, fetching URLs. The permission system gives you precise control over which operations Claude performs automatically and which require your explicit approval.
## What permissions control
Permissions apply to three categories of operations:
<CardGroup cols={3}>
<Card title="File operations" icon="file">
Reading, editing, and writing files on your local filesystem via the `Read`, `Edit`, and `Write` tools.
</Card>
<Card title="Bash commands" icon="terminal">
Any shell command executed through the `Bash` tool, including installs, builds, git operations, and arbitrary scripts.
</Card>
<Card title="MCP tool calls" icon="plug">
Tools exposed by connected MCP servers, which may include database queries, API calls, or browser automation.
</Card>
</CardGroup>
## Permission modes
The permission mode determines the default behaviour when no specific allow/deny rule matches a tool call. Set the mode once and it applies for the entire session.
<AccordionGroup>
<Accordion title="default — ask for potentially dangerous operations">
The standard mode. Claude Code evaluates each tool call and prompts you for confirmation on operations that could have side effects: running shell commands, editing files, making network requests. Read-only operations (file reads, searches) are auto-approved.
This is the recommended mode for everyday use.
</Accordion>
<Accordion title="acceptEdits — auto-approve file edits">
File edit and write operations (`Edit`, `Write`) are automatically approved without prompting. Bash commands still require confirmation.
Useful when you trust Claude to make file changes freely but still want to review shell commands.
</Accordion>
<Accordion title="plan — read-only planning mode">
Claude can read files, search the codebase, and discuss changes, but cannot execute any write or bash operations. All mutating tool calls are blocked.
Use this mode when you want Claude to analyse a problem and produce a plan before you authorise any changes. The model can exit plan mode and request permission to proceed via the `ExitPlanMode` tool.
</Accordion>
<Accordion title="bypassPermissions — skip all permission checks">
All permission checks are disabled. Every tool call is executed immediately without any confirmation prompts.
<Warning>
This mode is intended for automated, fully-scripted workflows where you have audited what Claude will do in advance. Never use `bypassPermissions` in an interactive session where Claude might take unexpected actions.
</Warning>
</Accordion>
<Accordion title="dontAsk — suppress prompts">
Similar to `bypassPermissions` but uses a slightly different internal path. Tool calls that would normally prompt are auto-approved. Intended for scripted/non-interactive scenarios.
</Accordion>
<Accordion title="auto — transcript-classifier mode (feature-gated)">
An experimental mode that uses a secondary AI classifier to evaluate each proposed tool call against the conversation transcript. The classifier decides whether the operation is within the scope of what was requested, and either auto-approves or escalates to a human prompt.
This mode is only available when the `TRANSCRIPT_CLASSIFIER` feature flag is enabled.
</Accordion>
</AccordionGroup>
## Setting the permission mode
<Tabs>
<Tab title="CLI flag">
Pass `--permission-mode` when starting Claude Code:
```bash theme={null}
claude --permission-mode acceptEdits
claude --permission-mode bypassPermissions
claude --permission-mode plan
```
</Tab>
<Tab title="/permissions command">
Change the mode mid-session without restarting:
```
/permissions
```
An interactive menu lets you select the new mode. The change takes effect for the remainder of the session.
</Tab>
<Tab title="settings.json">
Set a persistent default in your user or project settings:
```json theme={null}
{
"defaultMode": "acceptEdits"
}
```
Valid values: `"default"`, `"acceptEdits"`, `"bypassPermissions"`, `"plan"`, `"dontAsk"`.
</Tab>
</Tabs>
## Permission rules (allow/deny lists)
Beyond the global mode, you can create fine-grained rules that always allow or always deny specific tool calls — regardless of the active mode.
Rules have three components:
| Field | Description |
| ------------- | -------------------------------------------------------------------------------------- |
| `toolName` | The name of the tool the rule applies to (e.g., `"Bash"`, `"Edit"`, `"mcp__myserver"`) |
| `ruleContent` | An optional pattern that must match the tool's input (e.g., a command prefix for Bash) |
| `behavior` | `"allow"`, `"deny"`, or `"ask"` |
Rules are evaluated **before** the permission mode. If a matching rule exists, its behavior is applied immediately.
### Rule sources and persistence
Rules can originate from different sources and are stored accordingly:
| Source | Where stored | Scope |
| ----------------- | ----------------------------- | --------------------------------- |
| `userSettings` | `~/.claude/settings.json` | All projects for the current user |
| `projectSettings` | `.claude/settings.json` | All users of this project |
| `localSettings` | `.claude/settings.local.json` | Current user, this project only |
| `session` | In-memory | Current session only |
| `cliArg` | CLI flags | Current invocation only |
### Example: always allow specific git commands
```json theme={null}
{
"permissions": {
"allow": [
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)",
"Read(*)"
],
"deny": [
"Bash(rm -rf *)",
"Bash(sudo *)"
]
}
}
```
## How bash permissions work
Bash command permission checking deserves special attention because shell commands can be complex and ambiguous.
### Pattern matching
A `Bash` permission rule with a `ruleContent` string is matched against the command using wildcard pattern matching:
* `git status` — exact match only
* `git *` — matches any `git` subcommand
* `npm run *` — matches any `npm run` script
* `*` — matches any bash command (use with extreme caution)
### Compound commands
When a bash command contains multiple sub-commands joined by `&&`, `||`, `;`, or pipes (`|`), each sub-command is checked independently. The overall permission is the most restrictive result: if any sub-command is denied, the entire compound command is blocked.
### Operator restrictions
Certain shell constructs are flagged for extra scrutiny regardless of rules:
* Output redirections (`>`, `>>`) to paths outside the project directory
* Commands that change the current directory (`cd`) to outside the working tree
* `sed -i` edit-in-place commands (handled specially to track file modifications)
### Safety checks
Regardless of the active permission mode, certain operations are always blocked or escalated:
* Commands targeting `.claude/` or `.git/` configuration directories
* Modifications to shell config files (`.bashrc`, `.zshrc`, etc.)
* Attempts to bypass path restrictions using cross-platform path tricks
<Note>
In `auto` mode (feature-gated), safety checks marked `classifierApprovable: true` are sent to the transcript classifier rather than forcing a prompt. The classifier has visibility into the full conversation context and can decide whether the operation is appropriate.
</Note>
## MCP tool permissions
MCP tools follow the same rule system as built-in tools. You can allow or deny an entire MCP server or individual tools within a server:
```json theme={null}
{
"permissions": {
"deny": [
"mcp__myserver"
],
"allow": [
"mcp__myserver__read_database"
]
}
}
```
Using `mcp__servername` as the rule (without a specific tool name) blanket-denies all tools from that server — they are filtered out of the tool list before the model even sees them.
## Safety recommendations
<Warning>
`bypassPermissions` and `dontAsk` modes remove all safeguards. Only use them in isolated environments (containers, CI sandboxes) where Claude's actions are constrained by the environment itself, not by permission prompts.
</Warning>
* **Start with `default` mode** for any interactive session.
* **Use `plan` mode** when exploring an unfamiliar codebase or designing a large change — review the plan before enabling writes.
* **Use `acceptEdits`** for coding sessions where you trust Claude to edit files freely but want to review shell commands.
* **Prefer granular allow rules** over broad mode escalation. Allowing `Bash(git *)` is safer than switching to `bypassPermissions`.
* **Scope deny rules tightly.** A blanket `Bash(*)` deny prevents Claude from running any shell command, including safe read-only operations.
* **Review project settings files** (`.claude/settings.json`) when cloning unfamiliar repositories — they may pre-configure permission rules.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,208 @@
> ## 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.
# Tools
> Reference for every built-in tool Claude Code can use, including file operations, shell execution, web access, and sub-agent spawning.
Claude Code gives Claude a set of built-in tools it can call to interact with your machine. Each tool call is subject to the active [permission mode and rules](/concepts/permissions). Below is a reference for every tool available by default.
## File tools
<CardGroup cols={2}>
<Card title="Read" icon="file-lines">
**Read a file from the local filesystem.**
Reads up to 2 000 lines by default. Supports an `offset` and `limit` for targeted reads of large files. Returns content in `cat -n` format with line numbers.
Also supports reading images (PNG, JPG, etc.) as visual input, PDF files (up to 20 pages at a time), and Jupyter notebooks (`.ipynb`).
Read-only. Always auto-approved in `default` mode.
</Card>
<Card title="Edit" icon="file-pen">
**Perform exact string replacements in a file.**
Requires a prior `Read` call on the file in the same conversation. Replaces `old_string` with `new_string` — the match must be unique in the file. Use `replace_all: true` to rename across the entire file.
Fails if `old_string` appears more than once (unless `replace_all` is set). This precision prevents unintended edits.
</Card>
<Card title="Write" icon="file-arrow-up">
**Create a new file or completely overwrite an existing one.**
For existing files, a prior `Read` call is required in the same conversation. Prefer `Edit` for modifying existing files — `Write` sends the entire file content and is better suited for new files or full rewrites.
</Card>
<Card title="Glob" icon="folder-magnifying-glass">
**Find files by name pattern.**
Fast pattern matching that works on any codebase size. Returns matching file paths sorted by modification time (most recently modified first).
Supports patterns like `**/*.ts`, `src/**/*.test.js`, `**/CLAUDE.md`. For open-ended multi-step searches, use the `Task` tool instead.
Read-only. Always auto-approved.
</Card>
</CardGroup>
## Shell tool
<Card title="Bash" icon="terminal">
**Execute a shell command in a persistent shell session.**
Runs the command in a shell that persists across tool calls within a conversation — environment variables and working-directory changes carry over between calls. Supports a `timeout` parameter (default and max values are configurable).
Key behaviours:
* **Compound commands** (`&&`, `||`, `;`, `|`) are parsed and each sub-command is permission-checked independently.
* **Background execution** — pass `run_in_background: true` to run a long-running command without blocking. You are notified when it completes.
* **Output limits** — stdout/stderr is truncated if it exceeds the per-tool result size budget; a preview and file path are returned instead.
* **Search commands** (`find`, `grep`, `rg`) — for content search, prefer the dedicated `Grep` tool, which has optimised permissions and access.
Subject to permission prompts in `default` mode. Auto-approved in `acceptEdits` mode only for commands covered by an allow rule.
</Card>
## Search tools
<CardGroup cols={2}>
<Card title="Grep" icon="magnifying-glass">
**Search file contents using regular expressions.**
Built on ripgrep. Supports full regex syntax (`log.*Error`, `function\s+\w+`), file-type filtering (`*.ts`, `**/*.py`), and three output modes:
* `files_with_matches` (default) — returns only file paths
* `content` — returns matching lines with context
* `count` — returns match counts per file
Multiline patterns are supported with `multiline: true`.
Read-only. Always auto-approved.
</Card>
<Card title="LS" icon="list">
**List directory contents.**
Returns files and subdirectories in a structured format. Useful for exploring project structure before reading or editing files.
Read-only. Always auto-approved.
<Note>In bare-minimum mode (`CLAUDE_CODE_SIMPLE=1`) only `Bash`, `Read`, and `Edit` are available — use `ls` via `Bash` instead.</Note>
</Card>
</CardGroup>
## Web tools
<CardGroup cols={2}>
<Card title="WebFetch" icon="globe">
**Fetch a URL and extract information from it.**
Takes a URL and a prompt describing what to extract. Converts HTML to Markdown, then passes the content through a secondary model to produce a focused answer.
Features:
* HTTP URLs are automatically upgraded to HTTPS.
* Includes a 15-minute self-cleaning cache — repeated fetches of the same URL are fast.
* When a URL redirects to a different host, the tool returns the redirect URL for a follow-up request.
* For GitHub URLs, prefer the `gh` CLI via `Bash` (e.g., `gh pr view`, `gh api`).
Read-only. Prompts for approval in `default` mode.
</Card>
<Card title="WebSearch" icon="magnifying-glass-arrow-right">
**Search the web and return results.**
Returns search results with titles, snippets, and URLs formatted as Markdown links. Useful for accessing information beyond the model's training cutoff.
After answering, Claude automatically appends a `Sources:` section listing all referenced URLs.
Domain filtering is supported to include or exclude specific sites. Currently only available in the US.
Prompts for approval in `default` mode.
</Card>
</CardGroup>
## Agent and task tools
<CardGroup cols={2}>
<Card title="Task (Agent)" icon="robot">
**Spawn a sub-agent to complete a task.**
Starts a nested agentic loop in a separate context. The sub-agent has its own conversation history, its own tool set (optionally restricted), and runs to completion before returning a result to the parent agent.
Sub-agents can run:
* **Locally** — in-process, sharing the parent's filesystem and shell
* **Remotely** — on separate compute when remote agent eligibility criteria are met
Use `Task` for open-ended multi-step searches, parallel workstreams, or delegating distinct sub-problems to isolated agents.
The parent agent receives the sub-agent's final output as a tool result.
</Card>
<Card title="TodoWrite" icon="list-check">
**Create and manage a structured task list.**
Writes a list of todo items with statuses (`pending`, `in_progress`, `completed`) to a persistent panel in the terminal UI. Helps Claude track progress on complex multi-step tasks and shows you what it is working on.
Use proactively for tasks with 3 or more distinct steps. Not necessary for simple single-step requests.
Results are rendered in the todo panel, not the conversation transcript.
</Card>
</CardGroup>
## MCP tools
MCP (Model Context Protocol) servers can expose additional tools to Claude Code. Connected tools appear in the tool list alongside built-in tools and follow the same permission system.
MCP tools are named with a `mcp__` prefix:
```
mcp__<server-name>__<tool-name>
```
For example, a tool named `query` on a server named `mydb` appears as `mcp__mydb__query`.
Common MCP tool categories include:
* Database query and management tools
* Browser and web automation tools
* Cloud provider APIs (AWS, GCP, Azure)
* Issue tracker integrations (GitHub, Linear, Jira)
* Internal company tools and APIs
<Info>
MCP servers are configured in `~/.claude/mcp_servers.json` or `.claude/mcp_servers.json`. Tools from a connected server are automatically included in Claude's context once the server is running.
</Info>
To deny all tools from a specific MCP server, add a deny rule for the server prefix:
```json theme={null}
{
"permissions": {
"deny": ["mcp__untrusted-server"]
}
}
```
## Notebook tool
<Card title="NotebookEdit" icon="book">
**Edit cells in a Jupyter notebook.**
Allows Claude to insert, replace, or delete cells in a `.ipynb` file with line-level precision. Read notebooks using the standard `Read` tool, which returns all cells and their outputs.
</Card>
## Tool availability
Not all tools are available in every context. The active tool set is determined at startup and can be affected by:
* `CLAUDE_CODE_SIMPLE=1` — restricts to `Bash`, `Read`, and `Edit` only
* Permission deny rules — tools blanket-denied by a rule are removed from the tool list before the model sees them
* `isEnabled()` checks — each tool can self-disable based on environment conditions (e.g., `WebSearch` is gated by region)
* MCP server connection state — MCP tools are only available when the server is running and connected
You can inspect the active tool set with the `/tools` command in the REPL.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,209 @@
> ## 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.
# CLAUDE.md
> How to write and organize CLAUDE.md files to give Claude persistent, project-specific instructions.
`CLAUDE.md` files let you encode project knowledge that Claude loads at the start of every session. Instead of explaining your project's conventions, build system, and architecture every time, you write them once and Claude reads them automatically.
## What belongs in CLAUDE.md
Write instructions that would cause mistakes if missing. Everything else is noise.
**Include:**
* Build, test, and lint commands (exact invocations, not just tool names)
* Architecture decisions that affect how code should be written or organized
* Coding conventions specific to your project (naming patterns, file structure rules)
* Environment setup requirements (required env vars, expected services)
* Common pitfalls or patterns Claude should know to avoid
* Monorepo structure and which packages own which responsibilities
**Omit:**
* Things Claude already knows (standard TypeScript syntax, common library APIs)
* Obvious reminders ("write clean code", "add comments")
* Sensitive data — API keys, passwords, tokens, or secrets of any kind
* Information that changes frequently and will become stale
<Tip>
The test: would removing this line cause Claude to make a mistake on your codebase? If not, cut it.
</Tip>
## File locations
Claude discovers memory files by traversing from your current directory up to the filesystem root. Files closer to your current directory have higher priority (they are loaded later, so the model pays more attention to them).
| File | Type | Purpose |
| ----------------------------------- | ------- | ------------------------------------------------------------- |
| `/etc/claude-code/CLAUDE.md` | Managed | System-wide instructions for all users, set by administrators |
| `~/.claude/CLAUDE.md` | User | Your personal global instructions, applied to every project |
| `~/.claude/rules/*.md` | User | Modular global rules, each file loaded separately |
| `CLAUDE.md` (project root) | Project | Shared team instructions, checked into source control |
| `.claude/CLAUDE.md` (project root) | Project | Alternative location for shared project instructions |
| `.claude/rules/*.md` (project root) | Project | Modular project rules, organized by topic |
| `CLAUDE.local.md` (project root) | Local | Your private project-specific instructions, not checked in |
<Note>
`.claude/rules/` directories support subdirectories. All `.md` files found recursively are loaded as separate memory entries.
</Note>
## Loading order and priority
Files are loaded in the following order. Because the model attends more to content that appears later in context, later files have higher effective priority.
<Steps>
<Step title="Managed memory">
`/etc/claude-code/CLAUDE.md` and `/etc/claude-code/rules/*.md` — global policy set by administrators. Always loaded; cannot be excluded by users.
</Step>
<Step title="User memory">
`~/.claude/CLAUDE.md` and `~/.claude/rules/*.md` — your personal global instructions for all projects.
</Step>
<Step title="Project memory (root-to-CWD)">
`CLAUDE.md`, `.claude/CLAUDE.md`, and `.claude/rules/*.md` files in each directory from the filesystem root down to your current directory. Files in directories closer to your CWD are loaded later (higher priority).
</Step>
<Step title="Local memory">
`CLAUDE.local.md` in each directory from root to CWD. Same traversal order. Gitignored by default.
</Step>
</Steps>
## The @include directive
Memory files can include other files using `@` notation. Included files are processed recursively and inserted before the file that references them.
```markdown theme={null}
# CLAUDE.md
@./docs/architecture.md
@~/shared/style-guide.md
@/etc/company-standards.md
```
**Supported path formats:**
| Syntax | Resolves to |
| ------------------ | ---------------------------------------------------------------- |
| `@filename` | Relative to the current file's directory (same as `@./filename`) |
| `@./relative/path` | Relative to the current file's directory |
| `@~/path/in/home` | Path under your home directory |
| `@/absolute/path` | Absolute filesystem path |
**Behavior:**
* Paths with a fragment (`#heading`) have the fragment stripped before resolving
* Non-existent files are silently ignored
* Circular references are detected and prevented
* Includes nest up to 5 levels deep
* Only text file formats are supported — binary files (images, PDFs) are skipped
* `@include` inside code blocks is not processed
<Warning>
External includes (files outside the project directory) require explicit approval the first time they are loaded. Claude will prompt you to confirm before fetching content from outside your project.
</Warning>
## Frontmatter path targeting
Files in `.claude/rules/` can use YAML frontmatter to restrict which file paths they apply to. This lets you load rules conditionally based on the file Claude is working with.
```markdown theme={null}
---
paths:
- "src/api/**"
- "*.graphql"
---
# API conventions
All API handlers must validate input using the shared `validate()` helper.
GraphQL resolvers must not perform direct database queries — use the data layer.
```
Rules without frontmatter apply unconditionally. Rules with `paths` frontmatter only apply when Claude is working in files matching the glob patterns.
## Example CLAUDE.md for a TypeScript project
```markdown theme={null}
# Project: Payments API
## Build and test
- Build: `bun run build`
- Tests: `bun test` (uses Bun's built-in test runner — do not use Jest)
- Lint: `bun run lint` (biome, not eslint)
- Type check: `bun run typecheck`
Always run `bun run typecheck` before considering a change complete.
## Architecture
- `src/handlers/` — HTTP handlers, one file per route group
- `src/services/` — Business logic, no direct DB access
- `src/db/` — Database layer (Drizzle ORM); all queries live here
- `src/schemas/` — Zod schemas shared between handler validation and DB types
Handlers call services. Services call the DB layer. Never skip layers.
## Conventions
- Use `z.object().strict()` for all input validation schemas
- Errors propagate as `Result<T, AppError>` — never throw in service code
- All monetary values are integers in cents
- Timestamps are Unix seconds (number), not Date objects
## Environment
Required env vars: `DATABASE_URL`, `STRIPE_SECRET_KEY`, `JWT_SECRET`
Local dev: copy `.env.example` to `.env.local` and fill in values
## Common mistakes to avoid
- Do not use `new Date()` directly — use `getCurrentTimestamp()` from `src/utils/time.ts`
- Do not add `console.log` — use the `logger` from `src/utils/logger.ts`
- Do not write raw SQL — use the Drizzle query builder
```
## Generating CLAUDE.md with /init
Run `/init` in any Claude Code session to automatically generate a `CLAUDE.md` for your project. Claude analyzes your codebase and produces a file containing the commands and context most relevant to the project.
```
/init
```
The generated file is a starting point. Review it, trim anything that isn't genuinely useful, and add project-specific knowledge that Claude couldn't infer from the code.
## Editing CLAUDE.md with /memory
Run `/memory` to open the memory editor, which lists all currently loaded memory files and lets you edit them directly within the session.
```
/memory
```
Changes take effect immediately — Claude reloads the updated file and applies the new instructions to the current session.
## Excluding files
If you have CLAUDE.md files you want to prevent Claude from loading (for example, in vendored dependencies or generated code), add exclusion patterns to your settings:
```json theme={null}
{
"claudeMdExcludes": [
"/absolute/path/to/vendor/CLAUDE.md",
"**/generated/**",
"**/third-party/.claude/rules/**"
]
}
```
Patterns are matched against absolute paths using picomatch. Only User, Project, and Local memory types can be excluded — Managed (administrator) files are always loaded.
See [Settings](/configuration/settings) for full documentation on the `claudeMdExcludes` option.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,261 @@
> ## 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.
# Environment variables
> Environment variables that Claude Code reads to configure authentication, API access, behavior, and runtime options.
Claude Code reads environment variables at startup. These variables let you configure authentication, point to custom API endpoints, tune runtime behavior, and control which features are active — without modifying settings files.
## Authentication
<ParamField path="ANTHROPIC_API_KEY" type="string">
API key for authenticating directly with the Anthropic API. When set, Claude Code uses this key instead of (or in addition to) OAuth credentials. Takes priority over OAuth when present in most contexts.
```bash theme={null}
export ANTHROPIC_API_KEY="sk-ant-..."
```
</ParamField>
<ParamField path="ANTHROPIC_AUTH_TOKEN" type="string">
Alternative authentication token. Used in contexts where `ANTHROPIC_API_KEY` is not applicable.
</ParamField>
<ParamField path="ANTHROPIC_BASE_URL" type="string">
Override the Anthropic API base URL. Useful for pointing Claude Code at a proxy, staging environment, or compatible third-party endpoint.
```bash theme={null}
export ANTHROPIC_BASE_URL="https://my-proxy.example.com"
```
</ParamField>
<ParamField path="CLAUDE_CODE_API_BASE_URL" type="string">
Claude Code-specific API base URL override. Takes precedence over `ANTHROPIC_BASE_URL` when set.
</ParamField>
<ParamField path="ANTHROPIC_BEDROCK_BASE_URL" type="string">
Base URL for AWS Bedrock API access. Set this when routing Claude Code through a Bedrock endpoint.
</ParamField>
<ParamField path="ANTHROPIC_VERTEX_PROJECT_ID" type="string">
Google Cloud project ID for Vertex AI access. Required when using Claude Code through Google Cloud's Vertex AI platform.
</ParamField>
<ParamField path="CLAUDE_CODE_USE_BEDROCK" type="string">
Set to `1` or `true` to use AWS Bedrock as the API provider.
</ParamField>
<ParamField path="CLAUDE_CODE_USE_FOUNDRY" type="string">
Set to `1` or `true` to use Anthropic Foundry as the API provider.
</ParamField>
<ParamField path="CLAUDE_CODE_OAUTH_TOKEN" type="string">
OAuth access token to use for authentication directly, bypassing the interactive login flow. Useful for automated environments.
</ParamField>
## Configuration paths
<ParamField path="CLAUDE_CONFIG_DIR" type="string" default="~/.claude">
Override the directory where Claude Code stores its configuration, settings, and transcripts. Defaults to `~/.claude` in your home directory.
```bash theme={null}
export CLAUDE_CONFIG_DIR="/opt/claude-config"
```
</ParamField>
<ParamField path="CLAUDE_CODE_MANAGED_SETTINGS_PATH" type="string">
Override the path to the managed settings file. Useful in enterprise environments where the default platform path is not appropriate.
</ParamField>
## Model selection
<ParamField path="ANTHROPIC_MODEL" type="string">
Default model to use. Overridden by the `model` setting in settings files and by explicit `--model` flags.
</ParamField>
<ParamField path="CLAUDE_CODE_SUBAGENT_MODEL" type="string">
Model to use for sub-agent tasks spawned by the main agent. When not set, sub-agents use the same model as the main session.
</ParamField>
<ParamField path="CLAUDE_CODE_AUTO_MODE_MODEL" type="string">
Model to use when running in auto mode. Defaults to the main session model when not specified.
</ParamField>
## Behavior toggles
<ParamField path="CLAUDE_CODE_REMOTE" type="string">
Set to `1` or `true` to enable remote/container mode. In this mode, Claude Code adjusts its behavior for non-interactive environments — extended API timeouts (120s vs. 300s), suppressed interactive prompts, and adapted output formatting.
```bash theme={null}
export CLAUDE_CODE_REMOTE=1
```
</ParamField>
<ParamField path="CLAUDE_CODE_SIMPLE" type="string">
Set to `1` or `true` (or pass `--bare`) to run in bare mode. Bare mode skips hooks, LSP integration, plugin sync, skill directory walks, attribution, background prefetches, and all keychain/credential reads. Authentication must be provided via `ANTHROPIC_API_KEY` or `apiKeyHelper` in `--settings`. Useful for lightweight scripted use.
</ParamField>
<ParamField path="DISABLE_AUTO_COMPACT" type="string">
Set to `1` or `true` to disable automatic context compaction. When set, Claude Code will not compact the conversation context even when it approaches the model's context limit.
```bash theme={null}
export DISABLE_AUTO_COMPACT=1
```
</ParamField>
<ParamField path="CLAUDE_CODE_DISABLE_BACKGROUND_TASKS" type="boolean">
Set to `1` or `true` to disable background task execution. When enabled, the `run_in_background` parameter is removed from Bash and PowerShell tools, and Claude cannot run shell commands as background processes.
</ParamField>
<ParamField path="CLAUDE_CODE_DISABLE_THINKING" type="string">
Set to `1` or `true` to disable extended thinking for all API calls, regardless of model support.
</ParamField>
<ParamField path="CLAUDE_CODE_DISABLE_AUTO_MEMORY" type="string">
Set to `1` or `true` to disable automatic memory. When disabled, Claude does not read from or write to the auto-memory directory. Set to `0` or `false` to explicitly enable it (useful when other conditions would disable it, such as bare mode).
Auto-memory is also disabled automatically in bare mode (`CLAUDE_CODE_SIMPLE`) and remote mode (`CLAUDE_CODE_REMOTE`) unless explicitly enabled.
</ParamField>
<ParamField path="CLAUDE_CODE_DISABLE_CLAUDE_MDS" type="string">
Set to `1` or `true` to completely disable loading of all `CLAUDE.md` memory files. Claude will not read any CLAUDE.md, CLAUDE.local.md, or `.claude/rules/*.md` files.
</ParamField>
<ParamField path="CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" type="string">
Set to `1` or `true` to suppress analytics, telemetry, and other non-essential network requests.
</ParamField>
<ParamField path="CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD" type="string">
Set to `1` or `true` to load `CLAUDE.md` files from directories added via `--add-dir`. By default, additional directories do not have their CLAUDE.md files loaded.
</ParamField>
<ParamField path="CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR" type="string">
Set to `1` or `true` to reset the working directory back to the original project root after each Bash command. Prevents one command from changing the CWD for subsequent commands.
</ParamField>
## Resource limits
<ParamField path="CLAUDE_CODE_MAX_OUTPUT_TOKENS" type="number">
Override the maximum number of output tokens per API response. When not set, Claude Code uses the model's default maximum. Useful for controlling costs in automated workflows.
```bash theme={null}
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096
```
</ParamField>
<ParamField path="CLAUDE_CODE_MAX_CONTEXT_TOKENS" type="number">
Override the maximum context window size. When set, Claude Code uses this value instead of the model's reported context limit.
</ParamField>
<ParamField path="BASH_MAX_OUTPUT_LENGTH" type="number">
Maximum number of characters captured from Bash command output. Output exceeding this limit is truncated. Useful for preventing very large command outputs from consuming context.
```bash theme={null}
export BASH_MAX_OUTPUT_LENGTH=50000
```
</ParamField>
<ParamField path="API_TIMEOUT_MS" type="number">
Override the API request timeout in milliseconds. Defaults to 300,000ms (5 minutes) for standard mode and 120,000ms (2 minutes) in remote mode.
```bash theme={null}
export API_TIMEOUT_MS=60000
```
</ParamField>
## Telemetry and observability
<ParamField path="CLAUDE_CODE_ENABLE_TELEMETRY" type="string">
Set to `1` or `true` to enable OpenTelemetry export of traces, metrics, and logs. Requires additional OTEL configuration (endpoint, headers, etc.) to be set via standard OpenTelemetry environment variables.
```bash theme={null}
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_EXPORTER_OTLP_ENDPOINT="https://otel.example.com"
```
</ParamField>
<ParamField path="CLAUDE_CODE_JSONL_TRANSCRIPT" type="string">
Path to a file where Claude Code writes a JSONL transcript of the session. Each line is a JSON object representing a conversation event.
```bash theme={null}
export CLAUDE_CODE_JSONL_TRANSCRIPT="/tmp/session.jsonl"
```
</ParamField>
## Node.js runtime
<ParamField path="NODE_OPTIONS" type="string">
Standard Node.js options passed to the runtime. Claude Code reads this to detect flags like `--max-old-space-size` and adjusts its behavior accordingly. Claude Code itself sets this internally to configure heap size for large sessions.
```bash theme={null}
export NODE_OPTIONS="--max-old-space-size=4096"
```
<Warning>
Avoid setting `NODE_OPTIONS` to values that include code execution flags. Claude Code validates shell environments and treats some `NODE_OPTIONS` values as requiring confirmation before running Bash commands.
</Warning>
</ParamField>
## Host platform override
<ParamField path="CLAUDE_CODE_HOST_PLATFORM" type="string">
Override the reported host platform for analytics. Accepts `"win32"`, `"darwin"`, or `"linux"`. Useful when Claude Code runs in a container (where `process.platform` reports the container OS) but the actual host platform differs.
```bash theme={null}
export CLAUDE_CODE_HOST_PLATFORM=darwin
```
</ParamField>
## Cloud provider region overrides
Claude Code supports per-model Vertex AI region overrides. Set the corresponding environment variable to route a specific model to a different region.
| Model prefix | Environment variable |
| ------------------- | --------------------------------- |
| `claude-haiku-4-5` | `VERTEX_REGION_CLAUDE_HAIKU_4_5` |
| `claude-3-5-haiku` | `VERTEX_REGION_CLAUDE_3_5_HAIKU` |
| `claude-3-5-sonnet` | `VERTEX_REGION_CLAUDE_3_5_SONNET` |
| `claude-3-7-sonnet` | `VERTEX_REGION_CLAUDE_3_7_SONNET` |
| `claude-opus-4-1` | `VERTEX_REGION_CLAUDE_4_1_OPUS` |
| `claude-opus-4` | `VERTEX_REGION_CLAUDE_4_0_OPUS` |
| `claude-sonnet-4-6` | `VERTEX_REGION_CLAUDE_4_6_SONNET` |
| `claude-sonnet-4-5` | `VERTEX_REGION_CLAUDE_4_5_SONNET` |
| `claude-sonnet-4` | `VERTEX_REGION_CLAUDE_4_0_SONNET` |
```bash theme={null}
# Route Opus 4 to a specific Vertex region
export VERTEX_REGION_CLAUDE_4_0_OPUS="us-central1"
```
The default Vertex region is controlled by `CLOUD_ML_REGION` (defaults to `us-east5`).
## AWS credentials
For Bedrock access, Claude Code respects standard AWS credential environment variables:
<ParamField path="AWS_REGION" type="string">
AWS region for Bedrock API calls. Falls back to `AWS_DEFAULT_REGION`, then defaults to `us-east-1`.
</ParamField>
<ParamField path="AWS_DEFAULT_REGION" type="string">
Fallback AWS region when `AWS_REGION` is not set.
</ParamField>
## Setting environment variables for all sessions
You can set environment variables that apply to every Claude Code session using the `env` field in your settings file, rather than setting them in your shell profile:
```json theme={null}
{
"env": {
"DISABLE_AUTO_COMPACT": "1",
"BASH_MAX_OUTPUT_LENGTH": "30000"
}
}
```
See [Settings](/configuration/settings) for documentation on the `env` field.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,439 @@
> ## 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.
# Settings
> Configure Claude Code behavior through JSON settings files at the user, project, and managed levels.
Claude Code reads settings from JSON files at multiple scopes. Settings merge from lowest to highest priority, so more specific scopes override broader ones.
## Settings files
<Tabs>
<Tab title="Global (user)">
**Location:** `~/.claude/settings.json`
Applies to every Claude Code session you run, across all projects. This is where you set personal preferences like your preferred model, theme, and cleanup policy.
```json theme={null}
{
"model": "claude-opus-4-5",
"cleanupPeriodDays": 30,
"permissions": {
"defaultMode": "acceptEdits"
}
}
```
</Tab>
<Tab title="Project (shared)">
**Location:** `.claude/settings.json` in your project root
Checked into source control. Use this for settings that should apply to everyone working on the project — permission rules, hook configurations, MCP servers, and environment variables.
```json theme={null}
{
"permissions": {
"allow": ["Bash(npm run *)", "Bash(git *)"],
"deny": ["Bash(rm -rf *)"]
},
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [{ "type": "command", "command": "npm run lint" }]
}
]
}
}
```
</Tab>
<Tab title="Local (personal project)">
**Location:** `.claude/settings.local.json` in your project root
Not checked into source control (automatically added to `.gitignore`). Use this for personal overrides within a specific project — your own permission preferences or environment variables that shouldn't be shared.
```json theme={null}
{
"permissions": {
"defaultMode": "bypassPermissions"
}
}
```
</Tab>
<Tab title="Managed (enterprise)">
**Location:** Platform-specific system path
Set by administrators via MDM, registry (Windows), plist (macOS), or a managed settings file. Managed settings take highest priority and cannot be overridden by users or projects.
See [Managed settings](#managed-settings-enterprise) below for details.
</Tab>
</Tabs>
## Opening settings
Run `/config` inside any Claude Code session to open the settings UI. This opens the **Config** tab of the settings panel, where you can browse and edit the currently active settings for each scope.
You can also edit the JSON files directly. Claude Code reloads settings automatically when it detects file changes.
## Settings precedence
Settings merge from lowest to highest priority. Later sources override earlier ones for scalar values; arrays are concatenated and deduplicated.
```
Plugin defaults → User settings → Project settings → Local settings → Managed (policy) settings
```
<Note>
Managed (policy) settings always take final precedence. An administrator setting `permissions.defaultMode` to `"default"` cannot be overridden by users or project files.
</Note>
## Settings reference
<AccordionGroup>
<Accordion title="model">
**Type:** `string` | **Scope:** Any
Override the default model used by Claude Code. Accepts any model ID supported by your configured provider.
```json theme={null}
{ "model": "claude-opus-4-5" }
```
</Accordion>
<Accordion title="permissions">
**Type:** `object` | **Scope:** Any
Controls which tools Claude can use and in what mode. See [Permissions](/concepts/permissions) for full documentation on rule syntax.
| Field | Type | Description |
| ------------------------------ | ----------- | ----------------------------------------------------------------------------------------- |
| `allow` | `string[]` | Rules for operations Claude may perform without asking |
| `deny` | `string[]` | Rules for operations Claude is always blocked from |
| `ask` | `string[]` | Rules for operations that always prompt for confirmation |
| `defaultMode` | `string` | Default permission mode: `"default"`, `"acceptEdits"`, `"plan"`, or `"bypassPermissions"` |
| `disableBypassPermissionsMode` | `"disable"` | Prevent users from entering bypass permissions mode |
| `additionalDirectories` | `string[]` | Extra directories Claude may access |
```json theme={null}
{
"permissions": {
"defaultMode": "acceptEdits",
"allow": ["Bash(npm run *)", "Bash(git log *)"],
"deny": ["Bash(curl *)"]
}
}
```
</Accordion>
<Accordion title="hooks">
**Type:** `object` | **Scope:** Any
Run custom shell commands before or after tool executions. See [Hooks](/guides/hooks) for full documentation.
Supported hook events: `PreToolUse`, `PostToolUse`, `Notification`, `UserPromptSubmit`, `SessionStart`, `SessionEnd`, `Stop`, `SubagentStop`, `PreCompact`, `PostCompact`.
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [{ "type": "command", "command": "prettier --write $CLAUDE_FILE_PATHS" }]
}
]
}
}
```
</Accordion>
<Accordion title="cleanupPeriodDays">
**Type:** `integer` (non-negative) | **Default:** `30` | **Scope:** Any
Number of days to retain chat transcripts. Setting to `0` disables session persistence entirely — no transcripts are written and existing ones are deleted at startup.
```json theme={null}
{ "cleanupPeriodDays": 7 }
```
</Accordion>
<Accordion title="env">
**Type:** `object` | **Scope:** Any
Environment variables to inject into every Claude Code session. Values are coerced to strings.
```json theme={null}
{
"env": {
"NODE_ENV": "development",
"MY_API_URL": "https://api.example.com"
}
}
```
</Accordion>
<Accordion title="availableModels">
**Type:** `string[]` | **Scope:** Managed
Enterprise allowlist of models users can select. Accepts family aliases (`"opus"` allows any Opus version), version prefixes, or full model IDs. If `undefined`, all models are available. If an empty array, only the default model is available.
```json theme={null}
{ "availableModels": ["claude-opus-4-5", "claude-sonnet-4"] }
```
</Accordion>
<Accordion title="allowedMcpServers / deniedMcpServers">
**Type:** `object[]` | **Scope:** Any
Enterprise allowlist and denylist for MCP servers. Each entry must have exactly one of `serverName`, `serverCommand`, or `serverUrl`. The denylist takes precedence — if a server matches both lists, it is blocked.
```json theme={null}
{
"allowedMcpServers": [
{ "serverName": "my-db-server" },
{ "serverUrl": "https://mcp.example.com/*" }
],
"deniedMcpServers": [
{ "serverCommand": ["npx", "malicious-server"] }
]
}
```
</Accordion>
<Accordion title="worktree">
**Type:** `object` | **Scope:** Any
Configuration for `--worktree` flag behavior.
| Field | Type | Description |
| -------------------- | ---------- | --------------------------------------------------------------------------------- |
| `symlinkDirectories` | `string[]` | Directories to symlink from the main repo into worktrees (e.g., `"node_modules"`) |
| `sparsePaths` | `string[]` | Paths to check out in sparse mode, for faster worktrees in large monorepos |
```json theme={null}
{
"worktree": {
"symlinkDirectories": ["node_modules", ".cache"],
"sparsePaths": ["src/", "packages/my-service/"]
}
}
```
</Accordion>
<Accordion title="attribution">
**Type:** `object` | **Scope:** Any
Customize the attribution text Claude appends to commits and pull request descriptions.
| Field | Type | Description |
| -------- | -------- | -------------------------------------------------------------------------------- |
| `commit` | `string` | Attribution text (including any git trailers). Empty string removes attribution. |
| `pr` | `string` | Attribution text for PR descriptions. Empty string removes attribution. |
```json theme={null}
{
"attribution": {
"commit": "Co-Authored-By: Claude <noreply@anthropic.com>",
"pr": ""
}
}
```
</Accordion>
<Accordion title="language">
**Type:** `string` | **Scope:** Any
Preferred language for Claude responses and voice dictation. Accepts plain language names.
```json theme={null}
{ "language": "japanese" }
```
</Accordion>
<Accordion title="sandbox">
**Type:** `object` | **Scope:** Any
Sandbox configuration for isolating Claude's tool executions. Contact your administrator for sandbox setup details.
</Accordion>
<Accordion title="alwaysThinkingEnabled">
**Type:** `boolean` | **Default:** `true` | **Scope:** Any
When `false`, extended thinking is disabled. When absent or `true`, thinking is enabled automatically for models that support it.
```json theme={null}
{ "alwaysThinkingEnabled": false }
```
</Accordion>
<Accordion title="effortLevel">
**Type:** `"low" | "medium" | "high"` | **Scope:** Any
Persisted effort level for models that support adjustable thinking budgets.
```json theme={null}
{ "effortLevel": "high" }
```
</Accordion>
<Accordion title="autoMemoryEnabled">
**Type:** `boolean` | **Scope:** User, local
Enable or disable auto-memory for this project. When `false`, Claude does not read from or write to the auto-memory directory.
```json theme={null}
{ "autoMemoryEnabled": false }
```
</Accordion>
<Accordion title="autoMemoryDirectory">
**Type:** `string` | **Scope:** User, local
Custom path for auto-memory storage. Supports `~/` for home directory expansion. Ignored if set in project settings (`.claude/settings.json`) for security reasons. Defaults to `~/.claude/projects/<sanitized-cwd>/memory/`.
```json theme={null}
{ "autoMemoryDirectory": "~/my-memory-store" }
```
</Accordion>
<Accordion title="claudeMdExcludes">
**Type:** `string[]` | **Scope:** Any
Glob patterns or absolute paths of `CLAUDE.md` files to exclude from loading. Patterns are matched against absolute paths using picomatch. Only applies to User, Project, and Local memory types — Managed files cannot be excluded.
```json theme={null}
{
"claudeMdExcludes": [
"/home/user/monorepo/vendor/CLAUDE.md",
"**/third-party/.claude/rules/**"
]
}
```
</Accordion>
<Accordion title="disableAllHooks">
**Type:** `boolean` | **Scope:** Any
Set to `true` to disable all hook and `statusLine` execution.
```json theme={null}
{ "disableAllHooks": true }
```
</Accordion>
<Accordion title="respectGitignore">
**Type:** `boolean` | **Default:** `true` | **Scope:** Any
Whether the file picker respects `.gitignore` files. `.ignore` files are always respected regardless of this setting.
```json theme={null}
{ "respectGitignore": false }
```
</Accordion>
<Accordion title="defaultShell">
**Type:** `"bash" | "powershell"` | **Default:** `"bash"` | **Scope:** Any
Default shell for `!` commands in the input box.
```json theme={null}
{ "defaultShell": "powershell" }
```
</Accordion>
<Accordion title="forceLoginMethod">
**Type:** `"claudeai" | "console"` | **Scope:** Managed
Force a specific login method. Use `"claudeai"` for Claude Pro/Max accounts, or `"console"` for Anthropic Console billing.
```json theme={null}
{ "forceLoginMethod": "console" }
```
</Accordion>
<Accordion title="apiKeyHelper">
**Type:** `string` | **Scope:** User, managed
Path to a script that outputs authentication values. The script is called to retrieve credentials dynamically instead of reading a static API key.
```json theme={null}
{ "apiKeyHelper": "/usr/local/bin/get-claude-key.sh" }
```
</Accordion>
<Accordion title="syntaxHighlightingDisabled">
**Type:** `boolean` | **Scope:** Any
Disable syntax highlighting in diffs.
```json theme={null}
{ "syntaxHighlightingDisabled": true }
```
</Accordion>
<Accordion title="prefersReducedMotion">
**Type:** `boolean` | **Scope:** Any
Reduce or disable animations (spinner shimmer, flash effects, etc.) for accessibility.
```json theme={null}
{ "prefersReducedMotion": true }
```
</Accordion>
</AccordionGroup>
## Managed settings (enterprise)
Administrators can push settings to all users via platform-native mechanisms. Managed settings take precedence over all user and project settings.
<Tabs>
<Tab title="macOS">
Deploy a plist file to `/Library/Preferences/` or via MDM (Jamf, Kandji, etc.) targeting `com.anthropic.claudecode`.
</Tab>
<Tab title="Windows">
Write settings to the `HKLM\Software\Anthropic\Claude Code` registry key (machine-wide) or `HKCU\Software\Anthropic\Claude Code` (per-user, lower priority than HKLM).
</Tab>
<Tab title="File-based">
Place a `managed-settings.json` file at the platform-specific managed path. For drop-in configuration fragments, create a `managed-settings.d/` directory alongside it. Files in that directory are sorted alphabetically and merged on top of the base file — later filenames win.
```
managed-settings.json # base settings (lowest precedence)
managed-settings.d/
10-security.json # merged first
20-model-policy.json # merged second (wins over 10-)
```
This convention matches systemd/sudoers drop-ins: independent teams can ship policy fragments without coordinating edits to a single file.
</Tab>
</Tabs>
The following managed-only settings lock down user customization surfaces:
| Setting | Description |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allowManagedHooksOnly` | When `true`, only hooks defined in managed settings run. User, project, and local hooks are ignored. |
| `allowManagedPermissionRulesOnly` | When `true`, only permission rules from managed settings are respected. |
| `allowManagedMcpServersOnly` | When `true`, the `allowedMcpServers` allowlist is only read from managed settings. |
| `strictPluginOnlyCustomization` | Lock specific customization surfaces (`"skills"`, `"agents"`, `"hooks"`, `"mcp"`) to plugin-only sources. Pass `true` to lock all four, or an array of surface names. |
<Warning>
`allowManagedPermissionRulesOnly` ignores permission rules from user settings, project settings, local settings, and CLI arguments. Make sure your managed rules are comprehensive before enabling this.
</Warning>
## JSON schema
Add `$schema` to your settings file for editor autocompletion and validation:
```json theme={null}
{
"$schema": "https://schemas.anthropic.com/claude-code/settings.json"
}
```
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,206 @@
> ## 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.
# Authentication
> Configure how Claude Code authenticates with the Anthropic API, AWS Bedrock, or GCP Vertex AI.
Claude Code supports several authentication methods. The method you use depends on how you're accessing the API — directly through Anthropic, through a cloud provider, or via an API key helper script.
## Claude.ai OAuth (default)
When you run `claude` for the first time without any API key configured, Claude Code starts an OAuth flow using your claude.ai account.
<Steps>
<Step title="Run Claude Code">
Open your terminal and run:
```bash theme={null}
claude
```
</Step>
<Step title="Follow the login prompt">
Claude Code will display a URL and prompt you to open it in your browser. Visit the URL, sign in to your claude.ai account, and grant authorization.
</Step>
<Step title="Return to the terminal">
After authorizing in the browser, Claude Code receives the OAuth token automatically and stores it in secure storage (macOS Keychain on macOS, or a credentials file on other platforms). You're now authenticated.
</Step>
</Steps>
<Note>
OAuth tokens are refreshed automatically before they expire. You do not need to re-authenticate unless you explicitly log out or revoke access.
</Note>
## API key
You can authenticate using an Anthropic API key instead of OAuth.
<Tabs>
<Tab title="Environment variable">
Set the `ANTHROPIC_API_KEY` environment variable in your shell profile or before running `claude`:
```bash theme={null}
export ANTHROPIC_API_KEY=sk-ant-...
```
When this variable is set, Claude Code uses it directly and does not prompt for OAuth.
</Tab>
<Tab title="Settings file">
Add the `apiKeyHelper` setting to `~/.claude/settings.json` to run a shell command that outputs your API key. Claude Code executes this command and caches the result for 5 minutes (configurable with `CLAUDE_CODE_API_KEY_HELPER_TTL_MS`):
```json theme={null}
{
"apiKeyHelper": "cat ~/.anthropic/api-key"
}
```
The `apiKeyHelper` command must print only the API key to stdout and exit with code 0. Any stderr output is treated as an error.
</Tab>
</Tabs>
<Warning>
When `ANTHROPIC_API_KEY` is set or `apiKeyHelper` is configured, the OAuth flow is disabled. Claude Code will not attempt to use your claude.ai account.
</Warning>
## AWS Bedrock
To use Claude through Amazon Bedrock, set the `CLAUDE_CODE_USE_BEDROCK` environment variable and configure your AWS credentials.
<Steps>
<Step title="Enable Bedrock mode">
```bash theme={null}
export CLAUDE_CODE_USE_BEDROCK=1
```
</Step>
<Step title="Configure AWS credentials">
Claude Code uses the standard AWS credential chain. Any of the following work:
* AWS credentials file (`~/.aws/credentials`)
* Environment variables: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`
* IAM roles (EC2 instance profiles, ECS task roles, etc.)
* AWS SSO (`aws sso login`)
</Step>
<Step title="Set your region and model (optional)">
```bash theme={null}
export AWS_REGION=us-east-1
```
Claude Code selects a Claude model automatically based on your Bedrock configuration.
</Step>
</Steps>
### Automated AWS credential refresh
If your AWS session expires mid-session (for example, with short-lived SSO tokens), configure `awsAuthRefresh` in your settings to run a command that refreshes credentials automatically:
```json theme={null}
{
"awsAuthRefresh": "aws sso login --profile my-profile"
}
```
Claude Code runs this command when it detects that credentials have expired and streams the output so you can complete any browser-based flows.
To export credentials from a command (for example, `aws sts assume-role`), use `awsCredentialExport`:
```json theme={null}
{
"awsCredentialExport": "aws sts assume-role --role-arn arn:aws:iam::123456789012:role/MyRole --role-session-name claude-code --query Credentials --output json"
}
```
The command must output valid AWS STS JSON (with `Credentials.AccessKeyId`, `Credentials.SecretAccessKey`, and `Credentials.SessionToken`).
## GCP Vertex AI
To use Claude through Google Cloud Vertex AI, set the `CLAUDE_CODE_USE_VERTEX` environment variable and configure Application Default Credentials.
<Steps>
<Step title="Enable Vertex mode">
```bash theme={null}
export CLAUDE_CODE_USE_VERTEX=1
```
</Step>
<Step title="Configure GCP credentials">
Claude Code uses Google Application Default Credentials (ADC). Any of the following work:
* `gcloud auth application-default login` (for interactive use)
* Service account key file via `GOOGLE_APPLICATION_CREDENTIALS`
* Workload Identity (for GKE)
</Step>
<Step title="Set your GCP project and region (optional)">
```bash theme={null}
export ANTHROPIC_VERTEX_PROJECT_ID=my-gcp-project
export CLOUD_ML_REGION=us-central1
```
</Step>
</Steps>
### Automated GCP credential refresh
Similar to Bedrock, configure `gcpAuthRefresh` to run a command when credentials expire:
```json theme={null}
{
"gcpAuthRefresh": "gcloud auth application-default login"
}
```
Claude Code checks whether your current GCP credentials are valid before running the command, so it only refreshes when necessary.
## Switching accounts
### Log in to a different account
Run the `/login` command from within Claude Code to start a new OAuth flow. This replaces any stored tokens with those for the new account:
```
/login
```
### Log out
Run the `/logout` command to remove stored credentials:
```
/logout
```
After logging out, Claude Code will prompt you to authenticate on the next run.
## Token expiry and refresh
OAuth tokens expire automatically. Claude Code handles refresh silently:
* Before each API request, Claude Code checks whether the access token is expired.
* If it is, Claude Code acquires a lock and refreshes using the stored refresh token.
* Multiple concurrent Claude Code instances coordinate via a lock file to avoid redundant refreshes.
* If a `401` response arrives from the API (for example, due to a clock skew between when the token was issued and the local check), Claude Code forces an immediate refresh without waiting for the local expiry time.
You do not need to do anything when tokens refresh. If refresh fails (for example, because you revoked access in the claude.ai settings), Claude Code will prompt you to run `/login`.
## Authentication priority
When multiple authentication sources are configured, Claude Code resolves them in this order:
1. `ANTHROPIC_AUTH_TOKEN` environment variable
2. `CLAUDE_CODE_OAUTH_TOKEN` environment variable
3. OAuth token from file descriptor (for managed deployments)
4. `apiKeyHelper` from settings
5. Stored claude.ai OAuth tokens (keychain or credentials file)
6. `ANTHROPIC_API_KEY` environment variable
<Tip>
For CI and non-interactive environments, use `ANTHROPIC_API_KEY` or `CLAUDE_CODE_OAUTH_TOKEN`. These are checked before any interactive flows.
</Tip>
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,436 @@
> ## 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
> Run shell commands, HTTP requests, or prompts automatically when Claude uses tools or reaches session milestones.
Hooks let you attach automation to Claude Code's tool lifecycle. When Claude reads a file, runs a bash command, or finishes a response, your configured hooks execute automatically. Use hooks to enforce code style, run tests, log tool usage, or gate what Claude is allowed to do.
## How hooks work
A hook is a command (shell script, HTTP endpoint, or LLM prompt) bound to a specific **event**. When that event fires, Claude Code runs every matching hook and uses the exit code and output to decide what to do next.
The input to each hook is a JSON object on stdin describing what happened — for example, the tool name and its arguments for `PreToolUse`, or the tool name and response for `PostToolUse`.
### Exit code semantics
Exit code behavior varies by event. The full table is documented in each event's description, but the general pattern is:
| Exit code | Meaning |
| --------- | ------------------------------------------------------------------------------------ |
| `0` | Success. Stdout may be shown to Claude (event-specific). |
| `2` | Block or inject. Show stderr to Claude and (for `PreToolUse`) prevent the tool call. |
| Other | Show stderr to the user only; execution continues. |
## Hook events
<AccordionGroup>
<Accordion title="PreToolUse — before tool execution">
Fires before every tool call. The hook input contains the tool name and arguments as JSON.
* Exit `0`: tool proceeds normally (stdout not shown)
* Exit `2`: block the tool call and show stderr to Claude so it can respond
* Other: show stderr to the user but allow the tool call to continue
Use matchers to restrict this hook to specific tools (e.g., `Bash`, `Write`).
</Accordion>
<Accordion title="PostToolUse — after tool execution">
Fires after every successful tool call. The hook input contains `inputs` (the tool arguments) and `response` (the tool result).
* Exit `0`: stdout is shown in transcript mode (Ctrl+O)
* Exit `2`: show stderr to Claude immediately (Claude can respond)
* Other: show stderr to the user only
Use this to run formatters, linters, or test runners after file edits.
</Accordion>
<Accordion title="PostToolUseFailure — after a tool error">
Fires when a tool call results in an error. Input contains `tool_name`, `tool_input`, `error`, `error_type`, `is_interrupt`, and `is_timeout`.
Same exit code semantics as `PostToolUse`.
</Accordion>
<Accordion title="Stop — before Claude concludes a response">
Fires just before Claude's turn ends. No matcher support.
* Exit `0`: no output shown
* Exit `2`: show stderr to Claude and continue the conversation (Claude gets another turn)
* Other: show stderr to the user only
Use this to check that all required tasks are complete before Claude finishes.
</Accordion>
<Accordion title="SubagentStop — before a subagent concludes">
Like `Stop`, but fires when a subagent (launched via the Agent tool) finishes. Input includes `agent_id`, `agent_type`, and `agent_transcript_path`. Same exit code semantics as `Stop`.
</Accordion>
<Accordion title="SubagentStart — when a subagent starts">
Fires when a new subagent is launched. Input includes `agent_id` and `agent_type`.
* Exit `0`: stdout is shown to the subagent's initial prompt
* Other: show stderr to user only
</Accordion>
<Accordion title="SessionStart — when a session begins">
Fires at the start of every session (startup, resume, `/clear`, or `/compact`). Input contains the start `source`.
* Exit `0`: stdout is shown to Claude
* Other: show stderr to user only (blocking errors are ignored)
Match on `source` values: `startup`, `resume`, `clear`, `compact`.
</Accordion>
<Accordion title="UserPromptSubmit — when you submit a prompt">
Fires when you press Enter to submit a prompt. Input contains your original prompt text.
* Exit `0`: stdout is shown to Claude (can prepend context)
* Exit `2`: block the prompt and show stderr to the user only
* Other: show stderr to user only
</Accordion>
<Accordion title="PreCompact — before conversation compaction">
Fires before Claude Code compacts the conversation (auto or manual). Input contains compaction details.
* Exit `0`: stdout is appended as custom compact instructions
* Exit `2`: block the compaction
* Other: show stderr to user but proceed
Match on `trigger`: `manual` or `auto`.
</Accordion>
<Accordion title="PostCompact — after conversation compaction">
Fires after compaction completes. Input contains compaction details and the summary.
* Exit `0`: stdout shown to user
* Other: show stderr to user only
</Accordion>
<Accordion title="Setup — repository setup and maintenance">
Fires with `trigger: init` (project onboarding) or `trigger: maintenance` (periodic). Use this for one-time setup scripts or periodic maintenance tasks.
* Exit `0`: stdout shown to Claude
* Other: show stderr to user only
</Accordion>
<Accordion title="PermissionRequest — when a permission dialog appears">
Fires when Claude Code would show a permission prompt. Output JSON with `hookSpecificOutput.decision` to approve or deny programmatically.
* Exit `0`: use the hook's decision if provided
* Other: show stderr to user only
</Accordion>
<Accordion title="PermissionDenied — after auto mode denies a tool call">
Fires when the auto mode classifier denies a tool call. Return `{"hookSpecificOutput":{"hookEventName":"PermissionDenied","retry":true}}` to tell Claude it may retry.
</Accordion>
<Accordion title="Notification — when notifications are sent">
Fires for permission prompts, idle prompts, auth success, and elicitation events. Match on `notification_type`.
* Exit `0`: no output shown
* Other: show stderr to user only
</Accordion>
<Accordion title="CwdChanged — after working directory changes">
Fires after the working directory changes. Input includes `old_cwd` and `new_cwd`. The `CLAUDE_ENV_FILE` environment variable is set — write bash export lines to that file to apply new env vars to subsequent Bash tool calls.
</Accordion>
<Accordion title="FileChanged — when a watched file changes">
Fires when a file matching the hook's `matcher` pattern changes on disk. The matcher specifies filename patterns to watch (e.g., `.envrc|.env`). Like `CwdChanged`, supports `CLAUDE_ENV_FILE` for injecting environment.
</Accordion>
<Accordion title="SessionEnd — when a session ends">
Fires when the session is ending (clear, logout, or exit). Match on `reason`: `clear`, `logout`, `prompt_input_exit`, or `other`.
</Accordion>
<Accordion title="ConfigChange — when config files change">
Fires when settings files change during a session. Match on `source`: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`.
* Exit `0`: allow the change
* Exit `2`: block the change from being applied
</Accordion>
<Accordion title="InstructionsLoaded — when a CLAUDE.md file is loaded">
Fires when any instruction file (CLAUDE.md or rule) is loaded. Observability-only — does not support blocking.
</Accordion>
<Accordion title="WorktreeCreate / WorktreeRemove — worktree lifecycle">
`WorktreeCreate` fires when an isolated worktree needs to be created. Stdout should contain the absolute path of the created worktree. `WorktreeRemove` fires when a worktree should be cleaned up.
</Accordion>
<Accordion title="Task events — task lifecycle">
`TaskCreated` and `TaskCompleted` fire when tasks are created or marked complete. Input includes `task_id`, `task_subject`, `task_description`, `teammate_name`, and `team_name`. Exit `2` prevents the state change.
</Accordion>
<Accordion title="TeammateIdle — when a teammate is about to go idle">
Fires before a teammate goes idle. Exit `2` to send stderr to the teammate and prevent it from going idle.
</Accordion>
<Accordion title="Elicitation / ElicitationResult — MCP elicitation">
`Elicitation` fires when an MCP server requests user input. Return JSON in `hookSpecificOutput` to provide the response programmatically. `ElicitationResult` fires after the user responds, allowing you to modify or block the response.
</Accordion>
</AccordionGroup>
## Configuring hooks
Run `/hooks` inside Claude Code to open the hooks configuration menu. The menu shows all configured hooks grouped by event and lets you add, edit, or remove them interactively.
Hooks are stored in the `hooks` field of settings files:
* `~/.claude/settings.json` — user-level hooks (apply everywhere)
* `.claude/settings.json` — project-level hooks (apply for this project)
* `.claude/settings.local.json` — local hooks (not checked into VCS)
### Configuration format
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "prettier --write $CLAUDE_FILE_PATH"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "echo 'Session complete' >> ~/.claude-log.txt"
}
]
}
]
}
}
```
Each event maps to an array of **matcher objects**. Each matcher object has:
* `matcher` (optional) — a string pattern to match against the event's matchable field (for example, `tool_name` for `PreToolUse`/`PostToolUse`, `trigger` for `Setup`, `source` for `SessionStart`)
* `hooks` — an array of hook commands to run when the matcher matches
### Hook command types
<Tabs>
<Tab title="Shell command">
```json theme={null}
{
"type": "command",
"command": "npm test",
"timeout": 60,
"shell": "bash"
}
```
Fields:
* `command` — the shell command to run (required)
* `timeout` — timeout in seconds (default: no limit)
* `shell` — `"bash"` (default) or `"powershell"`
* `statusMessage` — custom spinner text shown while the hook runs
* `async` — run in background without blocking (`true`/`false`)
* `once` — run once and remove the hook automatically
* `if` — permission rule syntax to conditionally skip the hook (e.g., `"Bash(git *)"`)
</Tab>
<Tab title="HTTP request">
```json theme={null}
{
"type": "http",
"url": "https://hooks.example.com/claude-event",
"headers": {
"Authorization": "Bearer $MY_TOKEN"
},
"allowedEnvVars": ["MY_TOKEN"],
"timeout": 10
}
```
Claude Code POSTs the hook input JSON to the URL. Headers support `$VAR` expansion for variables listed in `allowedEnvVars`.
</Tab>
<Tab title="LLM prompt">
```json theme={null}
{
"type": "prompt",
"prompt": "Review this tool call for security issues: $ARGUMENTS. If you find a problem, output an explanation and exit with code 2.",
"model": "claude-haiku-4-5",
"timeout": 30
}
```
The hook prompt is evaluated by an LLM. `$ARGUMENTS` is replaced with the hook input JSON. The LLM's response becomes the hook output.
</Tab>
<Tab title="Agent hook">
```json theme={null}
{
"type": "agent",
"prompt": "Verify that the unit tests in $ARGUMENTS passed and all assertions are meaningful.",
"timeout": 60
}
```
Like a prompt hook, but runs as a full agent with tool access. Useful for verification tasks that require reading files or running commands.
</Tab>
</Tabs>
## Matcher patterns
For events that support matching (like `PreToolUse`, `PostToolUse`, `SessionStart`), the `matcher` field filters which inputs trigger the hook.
* An empty or absent `matcher` matches all inputs for that event.
* For tool events, the `matcher` is matched against the `tool_name` (e.g., `"Bash"`, `"Write"`, `"Read"`).
* For `SessionStart`, it matches `source` (e.g., `"startup"`, `"compact"`).
* For `Setup`, it matches `trigger` (e.g., `"init"`, `"maintenance"`).
* For `FileChanged`, the `matcher` specifies filename patterns to watch (e.g., `".envrc|.env"`).
## Example hooks
### Auto-format files after editing
Run Prettier after every file write:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
}
]
}
]
}
}
```
### Run tests after bash commands
Run the test suite after any bash command that touches source files:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "if git diff --name-only HEAD | grep -q '\\.ts$'; then npm test; fi",
"timeout": 120,
"async": true
}
]
}
]
}
}
```
### Log all tool usage
Append every tool call to a log file:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) $CLAUDE_TOOL_NAME\" >> ~/.claude-tool-log.txt",
"async": true
}
]
}
]
}
}
```
### Block dangerous commands
Use `PreToolUse` to prevent `rm -rf` from being called:
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -q 'rm -rf'; then echo 'Blocked: rm -rf is not allowed' >&2; exit 2; fi"
}
]
}
]
}
}
```
### Inject environment on directory change
Use `CwdChanged` with `CLAUDE_ENV_FILE` to load `.envrc` when you change directories:
```json theme={null}
{
"hooks": {
"CwdChanged": [
{
"hooks": [
{
"type": "command",
"command": "if [ -f .envrc ]; then grep '^export ' .envrc >> \"$CLAUDE_ENV_FILE\"; fi"
}
]
}
]
}
}
```
## Hook timeout configuration
Set a per-hook timeout in seconds using the `timeout` field:
```json theme={null}
{
"type": "command",
"command": "npm run integration-tests",
"timeout": 300
}
```
Hooks without a `timeout` run until they exit naturally. For long-running hooks that should not block Claude, use `"async": true`.
## Hooks vs. skills
| Feature | Hooks | Skills |
| ------------- | ----------------------------------- | -------------------------------------------------- |
| When they run | Automatically on tool events | When Claude or you explicitly invoke `/skill-name` |
| Purpose | Side effects, gating, observability | On-demand workflows and capabilities |
| Configuration | Settings JSON | Markdown files in `.claude/skills/` |
| Input | JSON from the tool event | The arguments you pass to the skill |
Use hooks for things that should happen automatically every time (formatting, logging, enforcement). Use skills for repeatable workflows that you want to trigger on demand.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,282 @@
> ## 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.
# MCP servers
> Extend Claude Code with Model Context Protocol servers to connect databases, APIs, and custom tools.
Model Context Protocol (MCP) is an open standard that lets Claude Code connect to external data sources and services. When you add an MCP server, Claude gains access to new tools — for example, querying a database, reading Jira tickets, or interacting with a Slack workspace.
<CardGroup cols={2}>
<Card title="Extend Claude's capabilities" icon="plug">
Connect Claude to any service that exposes an MCP server: databases, APIs, file systems, and more.
</Card>
<Card title="Project or user scope" icon="folder">
Save server configs per-project in `.mcp.json` or globally in your user settings.
</Card>
<Card title="Enable and disable at runtime" icon="toggle-right">
Turn individual servers on and off with `/mcp enable` and `/mcp disable` without editing config files.
</Card>
<Card title="Permission gating" icon="shield">
Claude Code prompts before calling any MCP tool, giving you control over what actions are taken.
</Card>
</CardGroup>
## Adding a server
The primary way to add an MCP server is via the `claude mcp add` CLI command, or by editing a config file directly.
### Via the CLI
Run `/mcp` to open the MCP management panel where you can enable, disable, and reconnect servers.
To add a server from the command line using the `claude` CLI:
```bash theme={null}
claude mcp add <name> -- <command> [args...]
```
For example, to add the official filesystem MCP server:
```bash theme={null}
claude mcp add filesystem -- npx -y @modelcontextprotocol/server-filesystem /tmp
```
Specify the scope with `--scope`:
```bash theme={null}
# Save to .mcp.json in the current directory (shared with your team)
claude mcp add --scope project filesystem -- npx -y @modelcontextprotocol/server-filesystem /tmp
# Save to your user config (available in all projects)
claude mcp add --scope user my-db -- npx -y @my-org/mcp-server-postgres
```
### Via the `--mcp-config` flag
Pass a JSON config file when starting Claude Code:
```bash theme={null}
claude --mcp-config ./my-mcp-config.json
```
This is useful for CI environments or when you want a self-contained configuration that is not persisted to any settings file.
## Config file format
MCP server configurations use JSON with a top-level `mcpServers` key. Each server entry has a name and a configuration object.
<Tabs>
<Tab title="Stdio (local process)">
Most MCP servers run as a local subprocess communicating over stdin/stdout:
```json theme={null}
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"],
"env": {
"NODE_ENV": "production"
}
}
}
}
```
Fields:
* `command` — the executable to run (required)
* `args` — array of command-line arguments
* `env` — environment variables to pass to the process
</Tab>
<Tab title="HTTP (remote server)">
For servers hosted as HTTP endpoints:
```json theme={null}
{
"mcpServers": {
"my-api": {
"type": "http",
"url": "https://mcp.example.com/v1",
"headers": {
"Authorization": "Bearer $MY_API_TOKEN"
}
}
}
}
```
Fields:
* `type` — set to `"http"`
* `url` — the server URL (required)
* `headers` — HTTP headers; values support `$VAR` environment variable expansion
</Tab>
<Tab title="SSE (server-sent events)">
For servers using the SSE transport:
```json theme={null}
{
"mcpServers": {
"events-server": {
"type": "sse",
"url": "https://mcp.example.com/sse"
}
}
}
```
</Tab>
</Tabs>
Server names may only contain letters, numbers, hyphens, and underscores.
### Environment variable expansion
Values in `command`, `args`, `url`, and `headers` support `$VAR` and `${VAR}` syntax. Variables are expanded at startup from the shell environment. If a referenced variable is missing, Claude Code logs a warning but still attempts to connect.
## Configuration scopes
MCP configs are stored in different places depending on scope:
| Scope | Location | Use case |
| --------- | ------------------------------------------------------------------------ | ---------------------------------------------------- |
| `project` | `.mcp.json` in the current directory (and parent directories up to root) | Team-shared server configs |
| `user` | `~/.claude.json` (global config) | Personal servers available everywhere |
| `local` | `.claude/settings.local.json` in the current project | Per-project personal overrides, not committed to VCS |
When the same server name appears in multiple scopes, `local` takes precedence over `project`, which takes precedence over `user`.
## Managing servers
### Enable and disable
```
/mcp enable <server-name>
/mcp disable <server-name>
/mcp enable all
/mcp disable all
```
Disabled servers remain in the config but are not connected at startup. This is useful for servers you want to keep configured but not always running.
### Reconnect a server
If a server fails to connect or you need to force a reconnection:
```
/mcp reconnect <server-name>
```
### View server status
Run `/mcp` to see a list of all configured servers and their current connection status:
* **connected** — server is running and ready to use
* **pending** — server is starting up
* **failed** — server could not connect (check the error message)
* **needs-auth** — server requires OAuth authorization
* **disabled** — server is configured but turned off
## Approving MCP tool calls
Claude Code displays a permission prompt before calling any MCP tool. The prompt shows the tool name and its input arguments, so you can review what Claude is about to do before it executes.
You can:
* **Allow once** — approve this specific call
* **Allow always** — approve all calls to this tool in this session
* **Deny** — block the call; Claude receives an error and can try a different approach
<Note>
In auto mode (`--allowedTools`), MCP tools can be pre-approved by including their full name (formatted as `mcp__<server-name>__<tool-name>`) in the allowed tools list.
</Note>
## Example: filesystem server
The official filesystem MCP server gives Claude the ability to read and write files in directories you specify.
<Steps>
<Step title="Add the server">
```bash theme={null}
claude mcp add --scope project filesystem -- npx -y @modelcontextprotocol/server-filesystem /home/user/projects
```
</Step>
<Step title="Verify the connection">
Run `/mcp` and confirm `filesystem` shows as **connected**.
</Step>
<Step title="Use it">
Claude can now read and write files in `/home/user/projects` using the `mcp__filesystem__read_file` and `mcp__filesystem__write_file` tools.
</Step>
</Steps>
## Example: database server
```json theme={null}
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"POSTGRES_CONNECTION_STRING": "$DATABASE_URL"
}
}
}
}
```
Set `DATABASE_URL` in your environment before starting Claude Code, and the MCP server will receive it automatically.
## Official MCP registry
Anthropic and the community maintain an MCP server registry at [modelcontextprotocol.io](https://modelcontextprotocol.io). Browse available servers for databases, productivity tools, cloud providers, and more.
## Troubleshooting
<AccordionGroup>
<Accordion title="Server shows as 'failed'">
* Check that the command exists and is executable: `which npx`
* Run the command manually in your terminal to see if it starts without errors
* Check that required environment variables (like API keys) are set
* Run `claude --debug` to see detailed connection logs
</Accordion>
<Accordion title="MCP tools not appearing">
A server that is connected but unauthenticated will not expose any tools. Look for a **needs-auth** status in `/mcp` and follow the OAuth flow to authorize.
</Accordion>
<Accordion title="Environment variable not expanded">
Claude Code expands variables from the process environment at startup. If a variable is not set in your shell profile, it will not be available. Verify with `echo $YOUR_VAR` in the same terminal before starting `claude`.
</Accordion>
<Accordion title="Windows: npx fails to start">
On Windows, `npx` requires a `cmd /c` wrapper:
```json theme={null}
{
"mcpServers": {
"my-server": {
"command": "cmd",
"args": ["/c", "npx", "-y", "@my-org/mcp-server"]
}
}
}
```
</Accordion>
<Accordion title="Server works locally but not in CI">
Use the `--mcp-config` flag to pass a config file explicitly, and ensure all referenced environment variables are set in the CI environment. For stdio servers, make sure the command (e.g., `npx`, `node`) is available in the CI PATH.
</Accordion>
</AccordionGroup>
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,195 @@
> ## 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.
# Multi-agent workflows
> Parallelize complex tasks by having Claude spawn and coordinate sub-agents.
Claude Code can spawn sub-agents — separate Claude instances that run independently to complete tasks in parallel. This lets you tackle large, multi-step work by dividing it across specialized agents that run concurrently, rather than doing everything sequentially in a single conversation.
## How sub-agents work
When Claude uses the `Agent` tool, it launches a new Claude instance with its own context, system prompt, and tool permissions. The parent Claude waits for the agent to complete (or continues other work if the agent is running in the background), then receives the agent's result as a single message.
Each agent:
* Starts with a fresh context window (unless it's a fork)
* Gets a specialized system prompt based on its agent type
* Has its own tool permissions (configurable per agent type)
* Can itself spawn further sub-agents, though nesting is limited
## The Agent tool
Claude uses the `Agent` tool to spawn sub-agents. As a user, you don't call this tool directly — Claude decides when to use it. You can see when Claude spawns agents: they appear in the terminal with their own progress indicators.
The tool accepts:
* `description` — a 3-5 word summary of what the agent will do (shown in the UI)
* `prompt` — the full task description for the agent
* `subagent_type` — which specialized agent type to use (optional; defaults to general-purpose)
* `run_in_background` — whether to run asynchronously so Claude can continue other work
* `isolation``"worktree"` to give the agent an isolated git worktree
## When Claude uses sub-agents
Claude spawns agents when a task benefits from parallelism or specialization:
* **Independent parallel tasks** — writing tests while also updating documentation
* **Specialized work** — using a code-reviewer agent for a security audit
* **Long-running tasks** — background research while Claude works on something else
* **Isolated exploration** — forking itself to explore a solution without polluting the main context
Claude does not spawn agents for simple tasks, small file reads, or anything it can complete directly in a few tool calls.
## Requesting multi-agent workflows
You can ask Claude to use multiple agents explicitly:
```
Run the linter and the test suite in parallel.
```
```
Use separate agents to research how three competing libraries handle this problem,
then summarize the findings.
```
```
Have an agent review the security implications of this code change while you
continue implementing the feature.
```
<Tip>
When asking Claude to run agents "in parallel", it will send a single message with multiple Agent tool calls, launching all of them simultaneously. Be explicit about what should run in parallel vs. what must be sequential.
</Tip>
## Foreground vs. background agents
By default, agents run in the **foreground**: Claude waits for each agent to complete before proceeding. Use foreground agents when Claude needs the results to continue its work.
Background agents run asynchronously. Claude launches them and continues with other work. You receive a notification when the agent completes.
```
Run the integration tests in the background while you implement the next feature.
```
Claude will not poll or check on background agents — it continues working and receives the result as a notification when the agent finishes.
<Note>
Background agents are shown in a tasks panel alongside the main conversation. You can see their progress and cancel them if needed.
</Note>
## Coordinator mode
In coordinator mode, Claude acts as an orchestrator that delegates all implementation work to sub-agents and focuses on planning, routing, and synthesis. This is useful for very large tasks where you want Claude to manage the overall workflow while sub-agents do the hands-on work.
Coordinator mode is primarily used in multi-agent team setups. In a standard single-user session, Claude decides for itself when to delegate.
## Agent memory and context isolation
Each sub-agent starts with a **clean context window**. The parent Claude provides the full task description and any relevant background in the agent's prompt — the agent does not automatically inherit the parent's conversation history.
This means:
* Agents are independent; they cannot read the parent's conversation
* The parent must provide sufficient context in the prompt for the agent to succeed
* Results from agents are returned as a single response, not streamed turn by turn
### Persistent agent memory
Some agent types have persistent memory across invocations. Memory is stored in markdown files:
* **User scope**: `~/.claude/agent-memory/<agent-type>/MEMORY.md` — shared across all projects
* **Project scope**: `.claude/agent-memory/<agent-type>/MEMORY.md` — shared with your team
* **Local scope**: `.claude/agent-memory-local/<agent-type>/MEMORY.md` — local only, not committed
When an agent type has memory configured, it reads and writes this file to remember things across sessions. This is useful for agents that learn your preferences over time.
## Worktree isolation
Set `isolation: "worktree"` to give an agent its own git worktree — an isolated copy of the repository. Changes the agent makes do not affect your working directory until you merge them.
```
Implement this feature in an isolated worktree so I can review the changes before merging.
```
If the agent makes changes, the worktree path and branch are returned in the result so you can inspect them. If the agent makes no changes, the worktree is cleaned up automatically.
## Monitoring sub-agent progress
While agents run, you can see:
* The agent's description and elapsed time in the progress display
* Tool calls the agent is making (shown in transcript mode with Ctrl+O)
* A notification when the agent completes
For background agents, progress updates appear in the tasks panel. Claude summarizes the agent's findings when reporting back to you.
<Warning>
Do not ask Claude to check on a running background agent's output file directly. Claude receives a completion notification automatically. Polling the output file mid-run pulls the agent's internal tool noise into Claude's context, which is counterproductive.
</Warning>
## Writing effective agent prompts
Sub-agents start with zero context from the parent conversation. Claude should — and you can prompt Claude to — write agent prompts that are self-contained briefs.
A good agent prompt includes:
* What the agent is trying to accomplish and why
* Relevant file paths, function names, or data
* What the agent should report back (format, length, specific questions to answer)
* What the agent should *not* do (scope constraints)
* What has already been tried or ruled out
A weak prompt:
```
Based on your findings, fix the bug.
```
A stronger prompt:
```
Fix the null reference bug in UserService.getProfile() in src/services/user.ts:247.
The bug occurs when the user has no associated profile record — getProfile() calls
profile.preferences without checking if profile is null first. Add a null check and
return a default preferences object { theme: 'light', notifications: true }.
Run npm test afterward to confirm the fix passes existing tests.
```
## Best practices
<AccordionGroup>
<Accordion title="Give agents independent, parallelizable tasks">
Agents are most valuable when their work does not depend on each other's output. If task B requires the result of task A, they must be sequential — but tasks A and C can run in parallel while B waits for A.
</Accordion>
<Accordion title="Provide complete context in the prompt">
Paste relevant code snippets, file paths, function signatures, or error messages directly into the agent prompt. Never assume the agent will infer what it needs from minimal instructions.
</Accordion>
<Accordion title="Be specific about the expected output format">
If you need a concise summary, say "report in under 200 words." If you need structured output, describe the format. Vague prompts produce vague results.
</Accordion>
<Accordion title="Use worktree isolation for risky changes">
When an agent will make significant file changes, use `isolation: "worktree"` so you can review before merging. This is especially useful for refactoring or large feature work.
</Accordion>
<Accordion title="Don't over-parallelize">
Spawning many agents for small tasks adds overhead without benefit. Claude decides when agents are worthwhile; trust its judgment unless you have a specific parallel structure in mind.
</Accordion>
</AccordionGroup>
## Limitations and safety
* Sub-agents have their own permission modes. By default, they use `acceptEdits` mode.
* Agents can be denied by permission rules using `Agent(AgentName)` syntax in deny rules.
* Background agents are not linked to the parent's abort controller — pressing Escape cancels the parent turn but not running background agents. Use the tasks panel to cancel background agents explicitly.
* Sub-agents cannot spawn other teammates (the team roster is flat). They can spawn further sub-agents using the Agent tool.
* Fork agents (agents that inherit the parent's context) cannot themselves fork — Claude prevents recursive forking.
* Agent results are capped at 100,000 characters before being returned to the parent.
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,245 @@
> ## 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.
# Skills
> Create reusable on-demand capabilities that Claude invokes with a slash command.
Skills are markdown files that define reusable prompts and workflows. When you type `/skill-name` in Claude Code, Claude loads that skill's instructions and executes the described task. Skills are useful for any workflow you repeat across sessions — running a deployment, writing a changelog, reviewing a PR, or applying your team's specific coding conventions.
## How skills work
A skill is a directory inside `.claude/skills/` with a `SKILL.md` file. When you invoke `/skill-name`, Claude Code loads the skill's `SKILL.md` as the prompt for that action. The skill can include instructions, context, constraints, and even inline shell commands that run at invocation time.
Skills load lazily — they are only read when invoked, so having many skills defined doesn't affect startup time or context size.
## Creating a skill
<Steps>
<Step title="Create the skill directory">
Skills live in a `skills` subdirectory inside any `.claude/` directory:
```bash theme={null}
mkdir -p .claude/skills/my-skill
```
You can put skills in:
* `.claude/skills/` (project-level, relative to your working directory)
* `~/.claude/skills/` (user-level, available in all projects)
</Step>
<Step title="Write SKILL.md">
Create `.claude/skills/my-skill/SKILL.md` with your skill's instructions:
```markdown theme={null}
---
description: Run the full release process for this project
argument-hint: version number (e.g. 1.2.3)
---
Release the project at version $ARGUMENTS.
Steps:
1. Update the version in `package.json` to $ARGUMENTS
2. Update CHANGELOG.md with a new section for this version
3. Run `npm test` and confirm all tests pass
4. Commit with message "chore: release v$ARGUMENTS"
5. Create a git tag `v$ARGUMENTS`
```
</Step>
<Step title="Invoke the skill">
```
/my-skill 1.2.3
```
Claude loads the skill and executes the instructions, with `1.2.3` substituted for `$ARGUMENTS`.
</Step>
</Steps>
## Skill frontmatter
The frontmatter at the top of `SKILL.md` configures how the skill behaves. All fields are optional.
```yaml theme={null}
---
description: A short description shown in /skills and used by Claude to decide when to use it
argument-hint: what to pass as the argument (shown in autocomplete)
allowed-tools: Bash, Write, Read
when_to_use: Use this skill when the user asks to create a new component
model: claude-sonnet-4-6
user-invocable: true
context: fork
---
```
| Field | Description |
| ---------------- | ------------------------------------------------------------------------------------------ |
| `description` | Short description shown in `/skills` and used by Claude to decide when to invoke the skill |
| `argument-hint` | Hint shown in slash command autocomplete describing what argument to pass |
| `allowed-tools` | Comma-separated list of tools this skill is permitted to use (defaults to all) |
| `when_to_use` | Prose description of when Claude should use this skill proactively |
| `model` | Model to use for this skill (e.g., `claude-sonnet-4-6`); defaults to the session model |
| `user-invocable` | Set to `false` to hide the skill from the slash command list (still available to Claude) |
| `context` | `fork` to run the skill in an isolated subagent context |
| `paths` | Glob patterns; skill only activates when matching files are touched |
| `version` | Skill version string |
| `hooks` | Hooks scoped to this skill's execution (same format as settings hooks) |
## Argument substitution
Use `$ARGUMENTS` anywhere in `SKILL.md` to insert the text passed after the slash command:
```markdown theme={null}
Create a new React component named $ARGUMENTS following the project's conventions.
```
```
/new-component UserProfile
```
For named arguments, use `$ARG_NAME` syntax by listing arguments in frontmatter:
```yaml theme={null}
---
arguments: [name, directory]
---
```
Then reference them as `$name` and `$directory` in the body.
## Inline shell commands
Skills can embed shell commands that execute at invocation time using backtick injection syntax. The output is inserted into the prompt before Claude sees it:
```markdown theme={null}
---
description: Review recent changes
---
Here are the recent commits for context:
!`git log --oneline -20`
Review the changes above and summarize what was accomplished.
```
The `!` prefix followed by a backtick-quoted command runs the command and replaces the block with its output. This is useful for injecting live project state into the skill prompt.
<Warning>
Inline shell commands execute with the same permissions as your shell. They run when you invoke the skill, not when the skill is loaded at startup.
</Warning>
## Listing skills
Run `/skills` to see all available skills:
```
/skills
```
This shows skills from all scopes (project, user, managed) along with their descriptions.
## Namespaced skills
Skills in subdirectories are namespaced with colons:
```
.claude/skills/
deployment/
SKILL.md → /deployment
database/
migrate/
SKILL.md → /database:migrate
seed/
SKILL.md → /database:seed
```
## Conditional skills (path-based activation)
Add a `paths` frontmatter field to activate a skill only when you work with matching files:
```yaml theme={null}
---
description: Django model review
paths: "**/*.py"
when_to_use: Use when editing Django model files
---
```
The skill is loaded into Claude's context automatically when you read, write, or edit a file matching the glob pattern. This keeps skills out of context until they're relevant.
## Bundled skills
Claude Code ships with built-in skills that are always available. These are compiled into the binary and register themselves at startup. You can see them in `/skills` — they appear with source `bundled`.
Bundled skills include capabilities like:
* Project onboarding assistance
* Common code review workflows
* Agentic search and analysis patterns
Bundled skills follow the same interface as user-defined skills and can include reference files that are extracted to disk on first invocation.
## User-level skills
Skills in `~/.claude/skills/` are available in every project without needing to add them to each repository. This is a good place for personal workflows that span projects.
```bash theme={null}
mkdir -p ~/.claude/skills/standup
cat > ~/.claude/skills/standup/SKILL.md << 'EOF'
---
description: Summarize what I worked on today for a standup update
---
Look at my git commits from today across this repository and summarize them in standup format: what I did, what I'm doing next, and any blockers. Keep it to 3-4 sentences.
EOF
```
## Skills vs. hooks
| Feature | Skills | Hooks |
| ------------- | ---------------------------------------------------------------- | ------------------------------------------------- |
| Invocation | Explicit: `/skill-name` or by Claude when it recognizes the need | Automatic: fires on tool events |
| When to use | Repeatable workflows you want to trigger intentionally | Side effects, formatting, linting, blocking |
| Configuration | `SKILL.md` in `.claude/skills/` | `hooks` field in settings JSON |
| Context | Can include files, shell output, and detailed instructions | Receives event JSON, returns exit code and output |
Use skills when you want a named, repeatable action. Use hooks when you want something to happen automatically every time a specific event occurs.
## Example: custom component generator
```markdown theme={null}
---
description: Generate a new React component with tests
argument-hint: ComponentName
allowed-tools: Write, Bash
---
Create a new React component named $ARGUMENTS.
1. Create `src/components/$ARGUMENTS/$ARGUMENTS.tsx` with:
- A functional component using TypeScript
- Props interface named `$ARGUMENTSProps`
- JSDoc comment describing the component
- Default export
2. Create `src/components/$ARGUMENTS/$ARGUMENTS.test.tsx` with:
- At least one rendering test using React Testing Library
- A snapshot test
3. Create `src/components/$ARGUMENTS/index.ts` that re-exports the component.
4. Run `npx tsc --noEmit` to confirm no type errors.
```
Invoke with:
```
/new-component Button
```
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,270 @@
> ## 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.
# Installation
> Install Claude Code on macOS, Linux, or Windows (via WSL). Requires Node.js 18 or higher.
## Requirements
* **Node.js 18 or higher** — Claude Code checks the Node.js version at startup and exits with an error if it is below 18.
* **npm** — included with Node.js.
Check your current version:
```bash theme={null}
node --version
npm --version
```
***
## Install Claude Code
Install globally with npm:
```bash theme={null}
npm install -g @anthropic-ai/claude-code
```
After installation, verify it works:
```bash theme={null}
claude --version
```
***
## Platform-specific notes
<Tabs>
<Tab title="macOS">
npm global installs work out of the box on macOS. If you get a permissions error when running `npm install -g`, you have two options:
**Option A: Fix npm permissions (recommended)**
Configure npm to use a directory in your home folder:
```bash theme={null}
mkdir -p ~/.npm-global
npm config set prefix ~/.npm-global
```
Add the following to your shell profile (`~/.zshrc` or `~/.bash_profile`):
```bash theme={null}
export PATH=~/.npm-global/bin:$PATH
```
Then reload your profile and install:
```bash theme={null}
source ~/.zshrc
npm install -g @anthropic-ai/claude-code
```
**Option B: Use a Node version manager**
Tools like [nvm](https://github.com/nvm-sh/nvm) or [fnm](https://github.com/Schniz/fnm) install Node.js in your home directory, which avoids global permission issues entirely:
```bash theme={null}
# Using nvm
nvm install --lts
nvm use --lts
npm install -g @anthropic-ai/claude-code
```
</Tab>
<Tab title="Linux">
On most Linux distributions, `npm install -g` requires either `sudo` or a corrected npm prefix. Using `sudo` is not recommended because it can create permission problems later.
**Recommended: Use a Node version manager**
```bash theme={null}
# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
# Reload your shell, then install Node.js
nvm install --lts
nvm use --lts
# Install Claude Code
npm install -g @anthropic-ai/claude-code
```
**Alternative: Fix npm global prefix**
```bash theme={null}
mkdir -p ~/.npm-global
npm config set prefix ~/.npm-global
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
npm install -g @anthropic-ai/claude-code
```
</Tab>
<Tab title="Windows (WSL)">
Claude Code runs on Windows through the Windows Subsystem for Linux (WSL). Running it directly in Command Prompt or PowerShell is not supported.
**Step 1: Install WSL**
Open PowerShell as Administrator and run:
```powershell theme={null}
wsl --install
```
Restart your machine when prompted. This installs WSL 2 with Ubuntu by default.
**Step 2: Open a WSL terminal**
Launch Ubuntu from the Start menu, or run `wsl` from PowerShell.
**Step 3: Install Node.js inside WSL**
```bash theme={null}
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts
```
**Step 4: Install Claude Code**
```bash theme={null}
npm install -g @anthropic-ai/claude-code
```
<Note>
Always run `claude` from within your WSL terminal, not from Windows CMD or PowerShell. Your project files should live inside the WSL filesystem (e.g., `~/projects/`) for best performance. Accessing Windows files via `/mnt/c/...` works but is slower.
</Note>
</Tab>
</Tabs>
***
## Updating
Update Claude Code to the latest version with:
```bash theme={null}
npm update -g @anthropic-ai/claude-code
```
Or use Claude Code's built-in update command:
```bash theme={null}
claude update
```
To check what version you're running:
```bash theme={null}
claude --version
```
***
## Uninstalling
Remove Claude Code with:
```bash theme={null}
npm uninstall -g @anthropic-ai/claude-code
```
This removes the `claude` binary. Your configuration files in `~/.claude/` are not removed automatically. To delete them:
```bash theme={null}
rm -rf ~/.claude
```
***
## Troubleshooting
<AccordionGroup>
<Accordion title="'claude' command not found after installation">
This usually means the npm global bin directory is not on your `PATH`.
Find where npm installs global binaries:
```bash theme={null}
npm config get prefix
```
The `bin` subdirectory of that path needs to be on your `PATH`. For example, if the output is `/home/you/.npm-global`, add this to your shell profile:
```bash theme={null}
export PATH=/home/you/.npm-global/bin:$PATH
```
Reload your shell (`source ~/.zshrc` or open a new terminal) and try again.
</Accordion>
<Accordion title="Node.js version is below 18">
Claude Code requires Node.js 18 or higher. If you see this error at startup:
```
Error: Claude Code requires Node.js version 18 or higher.
```
Upgrade Node.js using your version manager:
```bash theme={null}
# nvm
nvm install --lts
nvm use --lts
# fnm
fnm install --lts
fnm use --lts
```
Or download the latest LTS release from [nodejs.org](https://nodejs.org).
</Accordion>
<Accordion title="Permission denied when running npm install -g">
Do not use `sudo npm install -g` — it can leave files owned by root and cause further issues. Instead, fix your npm prefix to point to a user-writable directory:
```bash theme={null}
mkdir -p ~/.npm-global
npm config set prefix ~/.npm-global
export PATH=~/.npm-global/bin:$PATH
npm install -g @anthropic-ai/claude-code
```
Add the `export PATH` line to your shell profile so it persists across sessions.
</Accordion>
<Accordion title="Authentication fails on first run">
If the browser-based OAuth flow fails or you cannot use a browser, set your API key directly as an environment variable instead:
```bash theme={null}
export ANTHROPIC_API_KEY=sk-ant-...
claude
```
You can add this to your shell profile to make it permanent. API keys are available in the [Anthropic Console](https://console.anthropic.com).
</Accordion>
<Accordion title="Running inside Docker or a CI environment">
In non-interactive environments, authenticate with an API key via the environment variable:
```bash theme={null}
export ANTHROPIC_API_KEY=sk-ant-...
```
Use the `-p` flag to run non-interactively:
```bash theme={null}
claude -p "run the test suite and report any failures"
```
If you need Claude Code to operate without permission prompts in a sandboxed container, use the `--dangerously-skip-permissions` flag. This flag only works in environments that pass Claude Code's sandbox safety checks (no internet access and not running as root outside a container).
</Accordion>
</AccordionGroup>
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,103 @@
> ## 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.
# Introduction
> Claude Code is an AI coding agent that runs in your terminal — reading, editing, and executing code across your entire codebase.
Claude Code is a terminal-based AI agent built on Claude. It has direct access to your filesystem, shell, and tools, so you can describe a task in plain language and Claude handles the implementation end-to-end — no copy-pasting, no context switching.
## What Claude Code can do
<CardGroup cols={2}>
<Card title="Read and edit files" icon="file-code" href="/reference/tools/file-operations">
Claude reads source files, writes new content, and makes targeted edits. It shows diffs before applying changes so you stay in control.
</Card>
<Card title="Run shell commands" icon="square-terminal" href="/reference/tools/bash">
Execute tests, build scripts, git operations, and any shell command — with configurable permission controls to keep you safe.
</Card>
<Card title="Search your codebase" icon="magnifying-glass" href="/reference/tools/search">
Find files by glob pattern, search content with regular expressions, and navigate large codebases without reading every file manually.
</Card>
<Card title="Fetch from the web" icon="globe" href="/reference/tools/web">
Pull documentation, read API specs, or search the web — all without leaving your terminal session.
</Card>
<Card title="Spawn sub-agents" icon="sitemap" href="/guides/multi-agent">
Break complex tasks into parallel workstreams. Claude can spin up and coordinate multiple agents to work on different parts of a problem simultaneously.
</Card>
<Card title="Connect MCP servers" icon="plug" href="/guides/mcp-servers">
Extend Claude's capabilities with Model Context Protocol servers for databases, APIs, internal tools, and more.
</Card>
</CardGroup>
## Permission system
Every tool use in Claude Code goes through a permission check. You control how much autonomy Claude has.
| Mode | Behavior |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `default` | Claude asks before running shell commands and making edits. You approve or deny each action. |
| `acceptEdits` | File edits are applied automatically. Shell commands still require approval. |
| `plan` | Claude produces a plan and asks for your sign-off before taking any action. Good for reviewing large changes before they happen. |
| `bypassPermissions` | All actions run without prompts. Intended for automated pipelines in sandboxed environments — not for interactive use. |
<Warning>
`bypassPermissions` mode disables all confirmation prompts. Only use it in isolated environments (Docker containers, CI sandboxes) where Claude cannot affect systems outside the task.
</Warning>
Set your permission mode with the `--permission-mode` flag when starting Claude, or change it with `/permissions` which also lets you manage allow/deny rules for specific tools:
```bash theme={null}
claude --permission-mode acceptEdits
```
## CLAUDE.md memory system
Claude Code reads `CLAUDE.md` files from your repository at the start of every session. These files let you encode project-specific knowledge — build commands, coding conventions, architecture notes, required environment variables — so Claude doesn't need to re-discover them from scratch every time.
There are three scopes:
* **Project** (`CLAUDE.md` at the repo root) — shared by everyone on the team, checked into source control.
* **Personal** (`CLAUDE.local.md` at the repo root) — your private preferences for this project, gitignored.
* **Subdirectory** (`CLAUDE.md` inside a subdirectory) — loaded automatically when Claude works in that directory. Useful for monorepos with distinct modules.
Run `/init` inside any Claude Code session to generate a `CLAUDE.md` for your project automatically. Claude analyzes your codebase and produces a file with the commands and context that matter most.
```bash theme={null}
# Inside a Claude Code session
/init
```
<Tip>
Keep `CLAUDE.md` concise. Every line should pass this test: "Would removing this cause Claude to make mistakes?" If not, cut it.
</Tip>
## Authentication
Claude Code authenticates in two ways:
1. **OAuth (recommended)** — Sign in with your Anthropic account at `claude.ai`. Run `claude` for the first time and follow the browser prompt.
2. **API key** — Set the `ANTHROPIC_API_KEY` environment variable. Useful for CI pipelines and non-interactive sessions.
See [Authentication](/guides/authentication) for the full priority order and cloud provider options (AWS Bedrock, GCP Vertex AI).
## Ready to get started?
<CardGroup cols={2}>
<Card title="Quickstart" icon="rocket" href="/quickstart">
Get Claude Code running in under 5 minutes
</Card>
<Card title="Installation" icon="download" href="/installation">
Detailed installation instructions for all platforms
</Card>
</CardGroup>
Built with [Mintlify](https://mintlify.com).

View File

@@ -0,0 +1,166 @@
> ## 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.
# Quickstart
> Install Claude Code, authenticate, and complete your first coding task in under 5 minutes.
## Prerequisites
* Node.js 18 or higher
* npm
To check your Node.js version:
```bash theme={null}
node --version
```
If you need to install or upgrade Node.js, download it from [nodejs.org](https://nodejs.org).
***
## Step 1: Install Claude Code
Install the package globally with npm:
```bash theme={null}
npm install -g @anthropic-ai/claude-code
```
Verify the installation:
```bash theme={null}
claude --version
```
***
## Step 2: Authenticate
Run `claude` from any directory to start the first-time setup:
```bash theme={null}
claude
```
On first run, Claude Code opens your browser and walks you through signing in with your Anthropic account. Once complete, your credentials are stored securely and reused for future sessions.
**Alternatively**, set an API key directly if you prefer not to use OAuth:
```bash theme={null}
export ANTHROPIC_API_KEY=sk-ant-...
```
<Note>
API keys take priority when the `ANTHROPIC_API_KEY` environment variable is set. For interactive use, OAuth is recommended because it handles token refresh automatically.
</Note>
***
## Step 3: Navigate to your project
Claude Code works within your current directory. Navigate to any project you want to work on:
```bash theme={null}
cd my-project
```
***
## Step 4: Start an interactive session
Run `claude` to open an interactive session:
```bash theme={null}
claude
```
You'll see a prompt where you can type tasks in plain language. Claude reads your project files, runs commands, and makes changes based on what you describe.
**Example first tasks to try:**
```
> explain the structure of this codebase
> add input validation to the signup form
> write tests for the UserService class
> find all places where we catch and swallow errors
```
Claude shows you what it plans to do before making changes that require permission. You can approve, deny, or ask for a different approach at each step.
***
## Step 5: Initialize a CLAUDE.md file
Run `/init` inside your session to generate a `CLAUDE.md` file for your project:
```
/init
```
Claude analyzes your repository — reading manifest files, existing documentation, and code structure — and produces a `CLAUDE.md` with the commands and context it needs to work effectively in your codebase. You should review and edit the generated file before committing it.
<Tip>
`CLAUDE.md` is loaded at the start of every session. It's the best place to capture things like non-standard build commands, testing quirks, and coding conventions specific to your team.
</Tip>
***
## Running a non-interactive command
Use the `-p` flag to run a single task and print the result, without entering an interactive session. This is useful for scripting or one-off queries:
```bash theme={null}
claude -p "explain this codebase"
```
```bash theme={null}
claude -p "list all TODO comments and the files they appear in"
```
```bash theme={null}
claude -p "check for unused exports in src/"
```
***
## Key slash commands
Once you're inside an interactive session, these slash commands are the most useful to know:
| Command | Description |
| -------------- | ----------------------------------------------------------- |
| `/help` | Show available commands and keyboard shortcuts |
| `/init` | Generate or update a `CLAUDE.md` for the current project |
| `/memory` | View and edit memory files (`CLAUDE.md`, `CLAUDE.local.md`) |
| `/permissions` | View or change the current permission mode |
| `/mcp` | Manage connected MCP servers |
| `/clear` | Clear the current conversation context |
| `/exit` | End the session |
***
## Next steps
<CardGroup cols={2}>
<Card title="Core concepts" icon="lightbulb" href="/concepts/how-it-works">
Understand how Claude Code thinks, plans, and acts on tasks
</Card>
<Card title="Permission modes" icon="shield" href="/concepts/permissions">
Learn how to configure how much autonomy Claude has
</Card>
<Card title="CLAUDE.md reference" icon="file-text" href="/configuration/claudemd">
Write effective memory files for your projects
</Card>
<Card title="MCP servers" icon="plug" href="/guides/mcp-servers">
Extend Claude with databases, APIs, and internal tools
</Card>
</CardGroup>
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.
# 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).