Initial commit to new repository
This commit is contained in:
206
docs/claude-code-docs-main/en/guides/authentication.md
Normal file
206
docs/claude-code-docs-main/en/guides/authentication.md
Normal 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).
|
||||
436
docs/claude-code-docs-main/en/guides/hooks.md
Normal file
436
docs/claude-code-docs-main/en/guides/hooks.md
Normal 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).
|
||||
282
docs/claude-code-docs-main/en/guides/mcp-servers.md
Normal file
282
docs/claude-code-docs-main/en/guides/mcp-servers.md
Normal 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).
|
||||
195
docs/claude-code-docs-main/en/guides/multi-agent.md
Normal file
195
docs/claude-code-docs-main/en/guides/multi-agent.md
Normal 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).
|
||||
245
docs/claude-code-docs-main/en/guides/skills.md
Normal file
245
docs/claude-code-docs-main/en/guides/skills.md
Normal 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).
|
||||
Reference in New Issue
Block a user