# Claude Code > ## Documentation Index --- # Source: https://code.claude.com/docs/en/amazon-bedrock.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code on Amazon Bedrock > Learn about configuring Claude Code through Amazon Bedrock, including setup, IAM configuration, and troubleshooting. ## Prerequisites Before configuring Claude Code with Bedrock, ensure you have: * An AWS account with Bedrock access enabled * Access to desired Claude models (for example, Claude Sonnet 4.5) in Bedrock * AWS CLI installed and configured (optional - only needed if you don't have another mechanism for getting credentials) * Appropriate IAM permissions ## Setup ### 1. Submit use case details First-time users of Anthropic models are required to submit use case details before invoking a model. This is done once per account. 1. Ensure you have the right IAM permissions (see more on that below) 2. Navigate to the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/) 3. Select **Chat/Text playground** 4. Choose any Anthropic model and you will be prompted to fill out the use case form ### 2. Configure AWS credentials Claude Code uses the default AWS SDK credential chain. Set up your credentials using one of these methods: **Option A: AWS CLI configuration** ```bash theme={null} aws configure ``` **Option B: Environment variables (access key)** ```bash theme={null} export AWS_ACCESS_KEY_ID=your-access-key-id export AWS_SECRET_ACCESS_KEY=your-secret-access-key export AWS_SESSION_TOKEN=your-session-token ``` **Option C: Environment variables (SSO profile)** ```bash theme={null} aws sso login --profile= export AWS_PROFILE=your-profile-name ``` **Option D: AWS Management Console credentials** ```bash theme={null} aws login ``` [Learn more](https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html) about `aws login`. **Option E: Bedrock API keys** ```bash theme={null} export AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key ``` Bedrock API keys provide a simpler authentication method without needing full AWS credentials. [Learn more about Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/). #### Advanced credential configuration Claude Code supports automatic credential refresh for AWS SSO and corporate identity providers. Add these settings to your Claude Code settings file (see [Settings](/en/settings) for file locations). When Claude Code detects that your AWS credentials are expired (either locally based on their timestamp or when Bedrock returns a credential error), it will automatically run your configured `awsAuthRefresh` and/or `awsCredentialExport` commands to obtain new credentials before retrying the request. ##### Example configuration ```json theme={null} { "awsAuthRefresh": "aws sso login --profile myprofile", "env": { "AWS_PROFILE": "myprofile" } } ``` ##### Configuration settings explained **`awsAuthRefresh`**: Use this for commands that modify the `.aws` directory, such as updating credentials, SSO cache, or config files. The command's output is displayed to the user, but interactive input isn't supported. This works well for browser-based SSO flows where the CLI displays a URL or code and you complete authentication in the browser. **`awsCredentialExport`**: Only use this if you can't modify `.aws` and must directly return credentials. Output is captured silently and not shown to the user. The command must output JSON in this format: ```json theme={null} { "Credentials": { "AccessKeyId": "value", "SecretAccessKey": "value", "SessionToken": "value" } } ``` ### 3. Configure Claude Code Set the following environment variables to enable Bedrock: ```bash theme={null} # Enable Bedrock integration export CLAUDE_CODE_USE_BEDROCK=1 export AWS_REGION=us-east-1 # or your preferred region # Optional: Override the region for the small/fast model (Haiku) export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2 ``` When enabling Bedrock for Claude Code, keep the following in mind: * `AWS_REGION` is a required environment variable. Claude Code does not read from the `.aws` config file for this setting. * When using Bedrock, the `/login` and `/logout` commands are disabled since authentication is handled through AWS credentials. * You can use settings files for environment variables like `AWS_PROFILE` that you don't want to leak to other processes. See [Settings](/en/settings) for more information. ### 4. Model configuration Claude Code uses these default models for Bedrock: | Model type | Default value | | :--------------- | :------------------------------------------------- | | Primary model | `global.anthropic.claude-sonnet-4-5-20250929-v1:0` | | Small/fast model | `us.anthropic.claude-haiku-4-5-20251001-v1:0` | For Bedrock users, Claude Code won't automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (for example, `us.anthropic.claude-haiku-4-5-20251001-v1:0`). To customize models, use one of these methods: ```bash theme={null} # Using inference profile ID export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-5-20250929-v1:0' export ANTHROPIC_SMALL_FAST_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0' # Using application inference profile ARN export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id' # Optional: Disable prompt caching if needed export DISABLE_PROMPT_CACHING=1 ``` [Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) may not be available in all regions. ### 5. Output token configuration These are the recommended token settings for Claude Code with Amazon Bedrock: ```bash theme={null} # Recommended output token settings for Bedrock export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096 export MAX_THINKING_TOKENS=1024 ``` **Why these values:** * **`CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096`**: Bedrock's burndown throttling logic sets a minimum of 4096 tokens as the `max_token` penalty. Setting this lower won't reduce costs but may cut off long tool uses, causing the Claude Code agent loop to fail persistently. Claude Code typically uses less than 4096 output tokens without extended thinking, but may need this headroom for tasks involving significant file creation or Write tool usage. * **`MAX_THINKING_TOKENS=1024`**: This provides space for extended thinking without cutting off tool use responses, while still maintaining focused reasoning chains. This balance helps prevent trajectory changes that aren't always helpful for coding tasks specifically. ## IAM configuration Create an IAM policy with the required permissions for Claude Code: ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowModelAndInferenceProfileAccess", "Effect": "Allow", "Action": [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream", "bedrock:ListInferenceProfiles" ], "Resource": [ "arn:aws:bedrock:*:*:inference-profile/*", "arn:aws:bedrock:*:*:application-inference-profile/*", "arn:aws:bedrock:*:*:foundation-model/*" ] }, { "Sid": "AllowMarketplaceSubscription", "Effect": "Allow", "Action": [ "aws-marketplace:ViewSubscriptions", "aws-marketplace:Subscribe" ], "Resource": "*", "Condition": { "StringEquals": { "aws:CalledViaLast": "bedrock.amazonaws.com" } } } ] } ``` For more restrictive permissions, you can limit the Resource to specific inference profile ARNs. For details, see [Bedrock IAM documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html). We recommend creating a dedicated AWS account for Claude Code to simplify cost tracking and access control. ## AWS Guardrails [Amazon Bedrock Guardrails](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html) let you implement content filtering for Claude Code. Create a Guardrail in the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/), publish a version, then add the Guardrail headers to your [settings file](/en/settings). Enable Cross-Region inference on your Guardrail if you're using cross-region inference profiles. Example configuration: ```json theme={null} { "env": { "ANTHROPIC_CUSTOM_HEADERS": "X-Amzn-Bedrock-GuardrailIdentifier: your-guardrail-id\nX-Amzn-Bedrock-GuardrailVersion: 1" } } ``` ## Troubleshooting If you encounter region issues: * Check model availability: `aws bedrock list-inference-profiles --region your-region` * Switch to a supported region: `export AWS_REGION=us-east-1` * Consider using inference profiles for cross-region access If you receive an error "on-demand throughput isn’t supported": * Specify the model as an [inference profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) ID Claude Code uses the Bedrock [Invoke API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html) and does not support the Converse API. ## Additional resources * [Bedrock documentation](https://docs.aws.amazon.com/bedrock/) * [Bedrock pricing](https://aws.amazon.com/bedrock/pricing/) * [Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) * [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)- [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md) --- # Source: https://code.claude.com/docs/en/analytics.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Track team usage with analytics > View Claude Code usage metrics, track adoption, and measure engineering velocity in the analytics dashboard. Claude Code provides analytics dashboards to help organizations understand developer usage patterns, track contribution metrics, and measure how Claude Code impacts engineering velocity. Access the dashboard for your plan: | Plan | Dashboard URL | Includes | Read more | | ----------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------- | | Claude for Teams / Enterprise | [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code) | Usage metrics, contribution metrics with GitHub integration, leaderboard, data export | [Details](#access-analytics-for-teams-and-enterprise) | | API (Claude Console) | [platform.claude.com/claude-code](https://platform.claude.com/claude-code) | Usage metrics, spend tracking, team insights | [Details](#access-analytics-for-api-customers) | ## Access analytics for Teams and Enterprise Navigate to [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code). Admins and Owners can view the dashboard. The Teams and Enterprise dashboard includes: * **Usage metrics**: lines of code accepted, suggestion accept rate, daily active users and sessions * **Contribution metrics**: PRs and lines of code shipped with Claude Code assistance, with [GitHub integration](#enable-contribution-metrics) * **Leaderboard**: top contributors ranked by Claude Code usage * **Data export**: download contribution data as CSV for custom reporting ### Enable contribution metrics Contribution metrics are in public beta and available on Claude for Teams and Claude for Enterprise plans. These metrics only cover users within your claude.ai organization. Usage through the Claude Console API or third-party integrations is not included. Usage and adoption data is available for all Claude for Teams and Claude for Enterprise accounts. Contribution metrics require additional setup to connect your GitHub organization. You need the Owner role to configure analytics settings. A GitHub admin must install the GitHub app. A GitHub admin installs the Claude GitHub app on your organization's GitHub account at [github.com/apps/claude](https://github.com/apps/claude). A Claude Owner navigates to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and enables the Claude Code analytics feature. On the same page, enable the "GitHub analytics" toggle. Complete the GitHub authentication flow and select which GitHub organizations to include in the analysis. Data typically appears within 24 hours after enabling, with daily updates. If no data appears, you may see one of these messages: * **"GitHub app required"**: install the GitHub app to view contribution metrics * **"Data processing in progress"**: check back in a few days and confirm the GitHub app is installed if data doesn't appear Contribution metrics support GitHub Cloud and GitHub Enterprise Server. ### Review summary metrics These metrics are deliberately conservative and represent an underestimate of Claude Code's actual impact. Only lines and PRs where there is high confidence in Claude Code's involvement are counted. The dashboard displays these summary metrics at the top: * **PRs with CC**: total count of merged pull requests that contain at least one line of code written with Claude Code * **Lines of code with CC**: total lines of code across all merged PRs that were written with Claude Code assistance. Only "effective lines" are counted: lines with more than 3 characters after normalization, excluding empty lines and lines with only brackets or trivial punctuation. * **PRs with Claude Code (%)**: percentage of all merged PRs that contain Claude Code-assisted code * **Suggestion accept rate**: percentage of times users accept Claude Code's code editing suggestions, including Edit, Write, and NotebookEdit tool usage * **Lines of code accepted**: total lines of code written by Claude Code that users have accepted in their sessions. This excludes rejected suggestions and does not track subsequent deletions. ### Explore the charts The dashboard includes several charts to visualize trends over time. #### Track adoption The Adoption chart shows daily usage trends: * **users**: daily active users * **sessions**: number of active Claude Code sessions per day #### Measure PRs per user This chart displays individual developer activity over time: * **PRs per user**: total number of PRs merged per day divided by daily active users * **users**: daily active users Use this to understand how individual productivity changes as Claude Code adoption increases. #### View pull requests breakdown The Pull requests chart shows a daily breakdown of merged PRs: * **PRs with CC**: pull requests containing Claude Code-assisted code * **PRs without CC**: pull requests without Claude Code-assisted code Toggle to **Lines of code** view to see the same breakdown by lines of code rather than PR count. #### Find top contributors The Leaderboard shows the top 10 users ranked by contribution volume. Toggle between: * **Pull requests**: shows PRs with Claude Code vs All PRs for each user * **Lines of code**: shows lines with Claude Code vs All lines for each user Click **Export all users** to download complete contribution data for all users as a CSV file. The export includes all users, not just the top 10 displayed. ### PR attribution When contribution metrics are enabled, Claude Code analyzes merged pull requests to determine which code was written with Claude Code assistance. This is done by matching Claude Code session activity against the code in each PR. #### Tagging criteria PRs are tagged as "with Claude Code" if they contain at least one line of code written during a Claude Code session. The system uses conservative matching: only code where there is high confidence in Claude Code's involvement is counted as assisted. #### Attribution process When a pull request is merged: 1. Added lines are extracted from the PR diff 2. Claude Code sessions that edited matching files within a time window are identified 3. PR lines are matched against Claude Code output using multiple strategies 4. Metrics are calculated for AI-assisted lines and total lines Before comparison, lines are normalized: whitespace is trimmed, multiple spaces are collapsed, quotes are standardized, and text is converted to lowercase. Merged pull requests containing Claude Code-assisted lines are labeled as `claude-code-assisted` in GitHub. #### Time window Sessions from 21 days before to 2 days after the PR merge date are considered for attribution matching. #### Excluded files Certain files are automatically excluded from analysis because they are auto-generated: * Lock files: package-lock.json, yarn.lock, Cargo.lock, and similar * Generated code: Protobuf outputs, build artifacts, minified files * Build directories: dist/, build/, node\_modules/, target/ * Test fixtures: snapshots, cassettes, mock data * Lines over 1,000 characters, which are likely minified or generated #### Attribution notes Keep these additional details in mind when interpreting attribution data: * Code substantially rewritten by developers, with more than 20% difference, is not attributed to Claude Code * Sessions outside the 21-day window are not considered * The algorithm does not consider the PR source or destination branch when performing attribution ### Get the most from analytics Use contribution metrics to demonstrate ROI, identify adoption patterns, and find team members who can help others get started. #### Monitor adoption Track the Adoption chart and user counts to identify: * Active users who can share best practices * Overall adoption trends across your organization * Dips in usage that may indicate friction or issues #### Measure ROI Contribution metrics help answer "Is this tool worth the investment?" with data from your own codebase: * Track changes in PRs per user over time as adoption increases * Compare PRs and lines of code shipped with vs. without Claude Code * Use alongside [DORA metrics](https://dora.dev/), sprint velocity, or other engineering KPIs to understand changes from adopting Claude Code #### Identify power users The Leaderboard helps you find team members with high Claude Code adoption who can: * Share prompting techniques and workflows with the team * Provide feedback on what's working well * Help onboard new users #### Access data programmatically To query this data through GitHub, search for PRs labeled with `claude-code-assisted`. ## Access analytics for API customers API customers using the Claude Console can access analytics at [platform.claude.com/claude-code](https://platform.claude.com/claude-code). You need the UsageView permission to access the dashboard, which is granted to Developer, Billing, Admin, Owner, and Primary Owner roles. Contribution metrics with GitHub integration are not currently available for API customers. The Console dashboard shows usage and spend metrics only. The Console dashboard displays: * **Lines of code accepted**: total lines of code written by Claude Code that users have accepted in their sessions. This excludes rejected suggestions and does not track subsequent deletions. * **Suggestion accept rate**: percentage of times users accept code editing tool usage, including Edit, Write, and NotebookEdit tools. * **Activity**: daily active users and sessions shown on a chart. * **Spend**: daily API costs in dollars alongside user count. ### View team insights The team insights table shows per-user metrics: * **Members**: all users who have authenticated to Claude Code. API key users display by key identifier, OAuth users display by email address. * **Spend this month**: per-user total API costs for the current month. * **Lines this month**: per-user total of accepted code lines for the current month. Spend figures in the Console dashboard are estimates for analytics purposes. For actual costs, refer to your billing page. ## Related resources * [Monitoring with OpenTelemetry](/en/monitoring-usage): export real-time metrics and events to your observability stack * [Manage costs effectively](/en/costs): set spend limits and optimize token usage * [Permissions](/en/permissions): configure roles and permissions --- # Source: https://code.claude.com/docs/en/authentication.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Authentication > Learn how to configure user authentication and credential management for Claude Code in your organization. ## Authentication methods Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of these ways: * [Claude for Teams or Enterprise](#claude-for-teams-or-enterprise) (recommended) * [Claude Console](#claude-console-authentication) * [Amazon Bedrock](/en/amazon-bedrock) * [Google Vertex AI](/en/google-vertex-ai) * [Microsoft Foundry](/en/microsoft-foundry) ### Claude for Teams or Enterprise [Claude for Teams](https://claude.com/pricing#team-&-enterprise) and [Claude for Enterprise](https://anthropic.com/contact-sales) provide the best experience for organizations using Claude Code. Team members get access to both Claude Code and Claude on the web with centralized billing and team management. * **Claude for Teams**: self-service plan with collaboration features, admin tools, and billing management. Best for smaller teams. * **Claude for Enterprise**: adds SSO, domain capture, role-based permissions, compliance API, and managed policy settings for organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements. Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or contact sales for [Claude for Enterprise](https://anthropic.com/contact-sales). Invite team members from the admin dashboard. Team members install Claude Code and log in with their Claude.ai accounts. ### Claude Console authentication For organizations that prefer API-based billing, you can set up access through the Claude Console. Use your existing Claude Console account or create a new one. You can add users through either method: * Bulk invite users from within the Console (Console -> Settings -> Members -> Invite) * [Set up SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso) When inviting users, assign one of: * **Claude Code** role: users can only create Claude Code API keys * **Developer** role: users can create any kind of API key Each invited user needs to: * Accept the Console invite * [Check system requirements](/en/setup#system-requirements) * [Install Claude Code](/en/setup#installation) * Log in with Console account credentials ### Cloud provider authentication For teams using Amazon Bedrock, Google Vertex AI, or Microsoft Azure: Follow the [Bedrock docs](/en/amazon-bedrock), [Vertex docs](/en/google-vertex-ai), or [Microsoft Foundry docs](/en/microsoft-foundry). Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/en/settings). Users can [install Claude Code](/en/setup#installation). ## Credential management Claude Code securely manages your authentication credentials: * **Storage location**: on macOS, API keys, OAuth tokens, and other credentials are stored in the encrypted macOS Keychain. * **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth. * **Custom credential scripts**: the [`apiKeyHelper`](/en/settings#available-settings) setting can be configured to run a shell script that returns an API key. * **Refresh intervals**: by default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals. ## See also * [Permissions](/en/permissions): configure what Claude Code can access and do * [Settings](/en/settings): complete configuration reference * [Security](/en/security): security safeguards and best practices --- # Source: https://code.claude.com/docs/en/best-practices.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Best Practices for Claude Code > Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions. Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely. This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements. But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand. This guide covers patterns that have proven effective across Anthropic's internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works under the hood, see [How Claude Code works](/en/how-claude-code-works). *** Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills. Claude's context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens. This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. For detailed strategies on reducing token usage, see [Reduce token usage](/en/costs#reduce-token-usage). *** ## Give Claude a way to verify its work Include tests, screenshots, or expected outputs so Claude can check itself. This is the single highest-leverage thing you can do. Claude performs dramatically better when it can verify its own work, like run tests, compare screenshots, and validate outputs. Without clear success criteria, it might produce something that looks right but actually doesn't work. You become the only feedback loop, and every mistake requires your attention. | Strategy | Before | After | | ------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Provide verification criteria** | *"implement a function that validates email addresses"* | *"write a validateEmail function. example test cases: [user@example.com](mailto:user@example.com) is true, invalid is false, [user@.com](mailto:user@.com) is false. run the tests after implementing"* | | **Verify UI changes visually** | *"make the dashboard look better"* | *"\[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them"* | | **Address root causes, not symptoms** | *"the build is failing"* | *"the build fails with this error: \[paste error]. fix it and verify the build succeeds. address the root cause, don't suppress the error"* | UI changes can be verified using the [Claude in Chrome extension](/en/chrome). It opens a browser, tests the UI, and iterates until the code works. Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid. *** ## Explore first, then plan, then code Separate research and planning from implementation to avoid solving the wrong problem. Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [Plan Mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to separate exploration from execution. The recommended workflow has four phases: Enter Plan Mode. Claude reads files and answers questions without making changes. ```txt claude (Plan Mode) theme={null} read /src/auth and understand how we handle sessions and login. also look at how we manage environment variables for secrets. ``` Ask Claude to create a detailed implementation plan. ```txt claude (Plan Mode) theme={null} I want to add Google OAuth. What files need to change? What's the session flow? Create a plan. ``` Press `Ctrl+G` to open the plan in your text editor for direct editing before Claude proceeds. Switch back to Normal Mode and let Claude code, verifying against its plan. ```txt claude (Normal Mode) theme={null} implement the OAuth flow from your plan. write tests for the callback handler, run the test suite and fix any failures. ``` Ask Claude to commit with a descriptive message and create a PR. ```txt claude (Normal Mode) theme={null} commit with a descriptive message and open a PR ``` Plan Mode is useful, but also adds overhead. For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly. Planning is most useful when you're uncertain about the approach, when the change modifies multiple files, or when you're unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan. *** ## Provide specific context in your prompts The more precise your instructions, the fewer corrections you'll need. Claude can infer intent, but it can't read your mind. Reference specific files, mention constraints, and point to example patterns. | Strategy | Before | After | | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Scope the task.** Specify which file, what scenario, and testing preferences. | *"add tests for foo.py"* | *"write a test for foo.py covering the edge case where the user is logged out. avoid mocks."* | | **Point to sources.** Direct Claude to the source that can answer a question. | *"why does ExecutionFactory have such a weird api?"* | *"look through ExecutionFactory's git history and summarize how its api came to be"* | | **Reference existing patterns.** Point Claude to patterns in your codebase. | *"add a calendar widget"* | *"look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase."* | | **Describe the symptom.** Provide the symptom, the likely location, and what "fixed" looks like. | *"fix the login bug"* | *"users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it"* | Vague prompts can be useful when you're exploring and can afford to course-correct. A prompt like `"what would you improve in this file?"` can surface things you wouldn't have thought to ask about. ### Provide rich content Use `@` to reference files, paste screenshots/images, or pipe data directly. You can provide rich data to Claude in several ways: * **Reference files with `@`** instead of describing where code lives. Claude reads the file before responding. * **Paste images directly**. Copy/paste or drag and drop images into the prompt. * **Give URLs** for documentation and API references. Use `/permissions` to allowlist frequently-used domains. * **Pipe in data** by running `cat error.log | claude` to send file contents directly. * **Let Claude fetch what it needs**. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files. *** ## Configure your environment A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see [Extend Claude Code](/en/features-overview). ### Write an effective CLAUDE.md Run `/init` to generate a starter CLAUDE.md file based on your current project structure, then refine over time. CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context **it can't infer from code alone**. The `/init` command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine. There's no required format for CLAUDE.md files, but keep it short and human-readable. For example: ```markdown CLAUDE.md theme={null} # Code style - Use ES modules (import/export) syntax, not CommonJS (require) - Destructure imports when possible (eg. import { foo } from 'bar') # Workflow - Be sure to typecheck when you're done making a series of code changes - Prefer running single tests, and not the whole test suite, for performance ``` CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use [skills](/en/skills) instead. Claude loads them on demand without bloating every conversation. Keep it concise. For each line, ask: *"Would removing this cause Claude to make mistakes?"* If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions! | ✅ Include | ❌ Exclude | | ---------------------------------------------------- | -------------------------------------------------- | | Bash commands Claude can't guess | Anything Claude can figure out by reading code | | Code style rules that differ from defaults | Standard language conventions Claude already knows | | Testing instructions and preferred test runners | Detailed API documentation (link to docs instead) | | Repository etiquette (branch naming, PR conventions) | Information that changes frequently | | Architectural decisions specific to your project | Long explanations or tutorials | | Developer environment quirks (required env vars) | File-by-file descriptions of the codebase | | Common gotchas or non-obvious behaviors | Self-evident practices like "write clean code" | If Claude keeps doing something you don't want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts. You can tune instructions by adding emphasis (e.g., "IMPORTANT" or "YOU MUST") to improve adherence. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time. CLAUDE.md files can import additional files using `@path/to/import` syntax: ```markdown CLAUDE.md theme={null} See @README.md for project overview and @package.json for available npm commands. # Additional Instructions - Git workflow: @docs/git-instructions.md - Personal overrides: @~/.claude/my-project-instructions.md ``` You can place CLAUDE.md files in several locations: * **Home folder (`~/.claude/CLAUDE.md`)**: Applies to all Claude sessions * **Project root (`./CLAUDE.md`)**: Check into git to share with your team, or name it `CLAUDE.local.md` and `.gitignore` it * **Parent directories**: Useful for monorepos where both `root/CLAUDE.md` and `root/foo/CLAUDE.md` are pulled in automatically * **Child directories**: Claude pulls in child CLAUDE.md files on demand when working with files in those directories ### Configure permissions Use `/permissions` to allowlist safe commands or `/sandbox` for OS-level isolation. This reduces interruptions while keeping you in control. By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you're not really reviewing anymore, you're just clicking through. There are two ways to reduce these interruptions: * **Permission allowlists**: Permit specific tools you know are safe (like `npm run lint` or `git commit`) * **Sandboxing**: Enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries Alternatively, use `--dangerously-skip-permissions` to bypass all permission checks for contained workflows like fixing lint errors or generating boilerplate. Letting Claude run arbitrary commands can result in data loss, system corruption, or data exfiltration via prompt injection. Only use `--dangerously-skip-permissions` in a sandbox without internet access. Read more about [configuring permissions](/en/settings) and [enabling sandboxing](/en/sandboxing#sandboxing). ### Use CLI tools Tell Claude Code to use CLI tools like `gh`, `aws`, `gcloud`, and `sentry-cli` when interacting with external services. CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the `gh` CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without `gh`, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits. Claude is also effective at learning CLI tools it doesn't already know. Try prompts like `Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.` ### Connect MCP servers Run `claude mcp add` to connect external tools like Notion, Figma, or your database. With [MCP servers](/en/mcp), you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows. ### Set up hooks Use hooks for actions that must happen every time with zero exceptions. [Hooks](/en/hooks-guide) run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens. Claude can write hooks for you. Try prompts like *"Write a hook that runs eslint after every file edit"* or *"Write a hook that blocks writes to the migrations folder."* Run `/hooks` for interactive configuration, or edit `.claude/settings.json` directly. ### Create skills Create `SKILL.md` files in `.claude/skills/` to give Claude domain knowledge and reusable workflows. [Skills](/en/skills) extend Claude's knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with `/skill-name`. Create a skill by adding a directory with a `SKILL.md` to `.claude/skills/`: ```markdown .claude/skills/api-conventions/SKILL.md theme={null} --- name: api-conventions description: REST API design conventions for our services --- # API Conventions - Use kebab-case for URL paths - Use camelCase for JSON properties - Always include pagination for list endpoints - Version APIs in the URL path (/v1/, /v2/) ``` Skills can also define repeatable workflows you invoke directly: ```markdown .claude/skills/fix-issue/SKILL.md theme={null} --- name: fix-issue description: Fix a GitHub issue disable-model-invocation: true --- Analyze and fix the GitHub issue: $ARGUMENTS. 1. Use `gh issue view` to get the issue details 2. Understand the problem described in the issue 3. Search the codebase for relevant files 4. Implement the necessary changes to fix the issue 5. Write and run tests to verify the fix 6. Ensure code passes linting and type checking 7. Create a descriptive commit message 8. Push and create a PR ``` Run `/fix-issue 1234` to invoke it. Use `disable-model-invocation: true` for workflows with side effects that you want to trigger manually. ### Create custom subagents Define specialized assistants in `.claude/agents/` that Claude can delegate to for isolated tasks. [Subagents](/en/sub-agents) run in their own context with their own set of allowed tools. They're useful for tasks that read many files or need specialized focus without cluttering your main conversation. ```markdown .claude/agents/security-reviewer.md theme={null} --- name: security-reviewer description: Reviews code for security vulnerabilities tools: Read, Grep, Glob, Bash model: opus --- You are a senior security engineer. Review code for: - Injection vulnerabilities (SQL, XSS, command injection) - Authentication and authorization flaws - Secrets or credentials in code - Insecure data handling Provide specific line references and suggested fixes. ``` Tell Claude to use subagents explicitly: *"Use a subagent to review this code for security issues."* ### Install plugins Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration. [Plugins](/en/plugins) bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic. If you work with a typed language, install a [code intelligence plugin](/en/discover-plugins#code-intelligence) to give Claude precise symbol navigation and automatic error detection after edits. For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/en/features-overview#match-features-to-your-goal). *** ## Communicate effectively The way you communicate with Claude Code significantly impacts the quality of results. ### Ask codebase questions Ask Claude questions you'd ask a senior engineer. When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer: * How does logging work? * How do I make a new API endpoint? * What does `async move { ... }` do on line 134 of `foo.rs`? * What edge cases does `CustomerOnboardingFlowImpl` handle? * Why does this code call `foo()` instead of `bar()` on line 333? Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly. ### Let Claude interview you For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the `AskUserQuestion` tool. Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs. ``` I want to build [brief description]. Interview me in detail using the AskUserQuestion tool. Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered. Keep interviewing until we've covered everything, then write a complete spec to SPEC.md. ``` Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference. *** ## Manage your session Conversations are persistent and reversible. Use this to your advantage! ### Course-correct early and often Correct Claude as soon as you notice it going off track. The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster. * **`Esc`**: Stop Claude mid-action with the `Esc` key. Context is preserved, so you can redirect. * **`Esc + Esc` or `/rewind`**: Press `Esc` twice or run `/rewind` to open the rewind menu and restore previous conversation and code state. * **`"Undo that"`**: Have Claude revert its changes. * **`/clear`**: Reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance. If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run `/clear` and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections. ### Manage context aggressively Run `/clear` between unrelated tasks to reset context. Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space. During long sessions, Claude's context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude. * Use `/clear` frequently between tasks to reset the context window entirely * When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions * For more control, run `/compact `, like `/compact Focus on the API changes` * Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization ### Use subagents for investigation Delegate research with `"use subagents to investigate X"`. They explore in a separate context, keeping your main conversation clean for implementation. Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries: ``` Use subagents to investigate how our authentication system handles token refresh, and whether we have any existing OAuth utilities I should reuse. ``` The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation. You can also use subagents for verification after Claude implements something: ``` use a subagent to review this code for edge cases ``` ### Rewind with checkpoints Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint. Claude automatically checkpoints before changes. Double-tap `Escape` or run `/rewind` to open the checkpoint menu. You can restore conversation only (keep code changes), restore code only (keep conversation), or restore both. Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn't work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later. Checkpoints only track changes made *by Claude*, not external processes. This isn't a replacement for git. ### Resume conversations Run `claude --continue` to pick up where you left off, or `--resume` to choose from recent sessions. Claude Code saves conversations locally. When a task spans multiple sessions (you start a feature, get interrupted, come back the next day) you don't have to re-explain the context: ```bash theme={null} claude --continue # Resume the most recent conversation claude --resume # Select from recent conversations ``` Use `/rename` to give sessions descriptive names (`"oauth-migration"`, `"debugging-memory-leak"`) so you can find them later. Treat sessions like branches. Different workstreams can have separate, persistent contexts. *** ## Automate and scale Once you're effective with one Claude, multiply your output with parallel sessions, headless mode, and fan-out patterns. Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done. ### Run headless mode Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json` for streaming JSON output. With `claude -p "your prompt"`, you can run Claude headlessly, without an interactive session. Headless mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats (plain text, JSON, streaming JSON) let you parse results programmatically. ```bash theme={null} # One-off queries claude -p "Explain what this project does" # Structured output for scripts claude -p "List all API endpoints" --output-format json # Streaming for real-time processing claude -p "Analyze this log file" --output-format stream-json ``` ### Run multiple Claude sessions Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows. There are two main ways to run parallel sessions: * [Claude Desktop](/en/desktop): Manage multiple local sessions visually. Each session gets its own isolated worktree. * [Claude Code on the web](/en/claude-code-on-the-web): Run on Anthropic's secure cloud infrastructure in isolated VMs. Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won't be biased toward code it just wrote. For example, use a Writer/Reviewer pattern: | Session A (Writer) | Session B (Reviewer) | | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Implement a rate limiter for our API endpoints` | | | | `Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns.` | | `Here's the review feedback: [Session B output]. Address these issues.` | | You can do something similar with tests: have one Claude write tests, then another write code to pass them. ### Fan out across files Loop through tasks calling `claude -p` for each. Use `--allowedTools` to scope permissions for batch operations. For large migrations or analyses, you can distribute work across many parallel Claude invocations: Have Claude list all files that need migrating (e.g., `list all 2,000 Python files that need migrating`) ```bash theme={null} for file in $(cat files.txt); do claude -p "Migrate $file from React to Vue. Return OK or FAIL." \ --allowedTools "Edit,Bash(git commit *)" done ``` Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The `--allowedTools` flag restricts what Claude can do, which matters when you're running unattended. You can also integrate Claude into existing data/processing pipelines: ```bash theme={null} claude -p "" --output-format json | your_command ``` Use `--verbose` for debugging during development, and turn it off in production. ### Safe Autonomous Mode Use `claude --dangerously-skip-permissions` to bypass all permission checks and let Claude work uninterrupted. This works well for workflows like fixing lint errors or generating boilerplate code. Letting Claude run arbitrary commands is risky and can result in data loss, system corruption, or data exfiltration (e.g., via prompt injection attacks). To minimize these risks, use `--dangerously-skip-permissions` in a container without internet access. With sandboxing enabled (`/sandbox`), you get similar autonomy with better security. Sandbox defines upfront boundaries rather than bypassing all checks. *** ## Avoid common failure patterns These are common mistakes. Recognizing them early saves time: * **The kitchen sink session.** You start with one task, then ask Claude something unrelated, then go back to the first task. Context is full of irrelevant information. > **Fix**: `/clear` between unrelated tasks. * **Correcting over and over.** Claude does something wrong, you correct it, it's still wrong, you correct again. Context is polluted with failed approaches. > **Fix**: After two failed corrections, `/clear` and write a better initial prompt incorporating what you learned. * **The over-specified CLAUDE.md.** If your CLAUDE.md is too long, Claude ignores half of it because important rules get lost in the noise. > **Fix**: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook. * **The trust-then-verify gap.** Claude produces a plausible-looking implementation that doesn't handle edge cases. > **Fix**: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it. * **The infinite exploration.** You ask Claude to "investigate" something without scoping it. Claude reads hundreds of files, filling the context. > **Fix**: Scope investigations narrowly or use subagents so the exploration doesn't consume your main context. *** ## Develop your intuition The patterns in this guide aren't set in stone. They're starting points that work well in general, but might not be optimal for every situation. Sometimes you *should* let context accumulate because you're deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it. Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass? Over time, you'll develop intuition that no guide can capture. You'll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate. ## Related resources Understand the agentic loop, tools, and context management Choose between skills, hooks, MCP, subagents, and plugins Step-by-step recipes for debugging, testing, PRs, and more Store project conventions and persistent context --- # Source: https://code.claude.com/docs/en/checkpointing.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Checkpointing > Automatically track and rewind Claude's edits to quickly recover from unwanted changes. Claude Code automatically tracks Claude's file edits as you work, allowing you to quickly undo changes and rewind to previous states if anything gets off track. ## How checkpoints work As you work with Claude, checkpointing automatically captures the state of your code before each edit. This safety net lets you pursue ambitious, wide-scale tasks knowing you can always return to a prior code state. ### Automatic tracking Claude Code tracks all changes made by its file editing tools: * Every user prompt creates a new checkpoint * Checkpoints persist across sessions, so you can access them in resumed conversations * Automatically cleaned up along with sessions after 30 days (configurable) ### Rewinding changes Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open up the rewind menu. You can choose to restore: * **Conversation only**: Rewind to a user message while keeping code changes * **Code only**: Revert file changes while keeping the conversation * **Both code and conversation**: Restore both to a prior point in the session ## Common use cases Checkpoints are particularly useful when: * **Exploring alternatives**: Try different implementation approaches without losing your starting point * **Recovering from mistakes**: Quickly undo changes that introduced bugs or broke functionality * **Iterating on features**: Experiment with variations knowing you can revert to working states ## Limitations ### Bash command changes not tracked Checkpointing does not track files modified by bash commands. For example, if Claude Code runs: ```bash theme={null} rm file.txt mv old.txt new.txt cp source.txt dest.txt ``` These file modifications cannot be undone through rewind. Only direct file edits made through Claude's file editing tools are tracked. ### External changes not tracked Checkpointing only tracks files that have been edited within the current session. Manual changes you make to files outside of Claude Code and edits from other concurrent sessions are normally not captured, unless they happen to modify the same files as the current session. ### Not a replacement for version control Checkpoints are designed for quick, session-level recovery. For permanent version history and collaboration: * Continue using version control (ex. Git) for commits, branches, and long-term history * Checkpoints complement but don't replace proper version control * Think of checkpoints as "local undo" and Git as "permanent history" ## See also * [Interactive mode](/en/interactive-mode) - Keyboard shortcuts and session controls * [Built-in commands](/en/interactive-mode#built-in-commands) - Accessing checkpoints using `/rewind` * [CLI reference](/en/cli-reference) - Command-line options --- # Source: https://code.claude.com/docs/en/chrome.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Use Claude Code with Chrome (beta) > Connect Claude Code to your browser to test web apps, debug with console logs, and automate browser tasks. Chrome integration is in beta and currently works with Google Chrome only. It is not yet supported on Brave, Arc, or other Chromium-based browsers. WSL (Windows Subsystem for Linux) is also not supported. Claude Code integrates with the Claude in Chrome browser extension to give you browser automation capabilities directly from your terminal. Build in your terminal, then test and debug in your browser without switching contexts. ## What the integration enables With Chrome connected, you can chain browser actions with terminal commands in a single workflow. For example: scrape documentation from a website, analyze it, generate code based on what you learned, and commit the result. Key capabilities include: * **Live debugging**: Claude reads console errors and DOM state directly, then fixes the code that caused them * **Design verification**: Build a UI from a Figma mock, then have Claude open it in the browser and verify it matches * **Web app testing**: Test form validation, check for visual regressions, or verify user flows work correctly * **Authenticated web apps**: Interact with Google Docs, Gmail, Notion, or any app you're logged into without needing API connectors * **Data extraction**: Pull structured information from web pages and save it locally * **Task automation**: Automate repetitive browser tasks like data entry, form filling, or multi-site workflows * **Session recording**: Record browser interactions as GIFs to document or share what happened ## Prerequisites Before using Claude Code with Chrome, you need: * [Google Chrome](https://www.google.com/chrome/) browser * [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher * [Claude Code CLI](/en/quickstart#step-1-install-claude-code) version 2.0.73 or higher * A paid Claude plan (Pro, Team, or Enterprise) ## How the integration works Claude Code communicates with Chrome through the Claude in Chrome browser extension. The extension uses Chrome's [Native Messaging API](https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging) to receive commands from Claude Code and execute them in your browser. This architecture lets Claude Code control browser tabs, read page content, and perform actions while you continue working in your terminal. When Claude encounters a login page, CAPTCHA, or other blocker, it pauses and asks you to handle it. You can provide credentials for Claude to enter, or log in manually in the browser. Once you're past the blocker, tell Claude to continue and it picks up where it left off. Claude opens new tabs for browser tasks rather than taking over existing ones. However, it shares your browser's login state, so if you're already signed into a site in Chrome, Claude can access it without re-authenticating. The Chrome integration requires a visible browser window. When Claude performs browser actions, you'll see Chrome open and navigate in real time. There's no headless mode since the integration relies on your actual browser session with its login state. ## Set up the integration Chrome integration requires a recent version of Claude Code. If you installed using the [native installer](/en/quickstart#step-1-install-claude-code), updates happen automatically. Otherwise, run: ```bash theme={null} claude update ``` Launch Claude Code with the `--chrome` flag: ```bash theme={null} claude --chrome ``` Run `/chrome` to check the connection status and manage settings. If the extension isn't detected, you'll see a warning with a link to install it. You can also enable Chrome integration from within an existing session using the `/chrome` command. ## Try it out Once connected, type this into Claude to see the integration in action: ``` Go to code.claude.com/docs, click on the search box, type "hooks", and tell me what results appear ``` Claude opens the page, clicks into the search field, types the query, and reports the autocomplete results. This shows navigation, clicking, and typing in a single workflow. ## Example workflows Claude can navigate pages, click and type, fill forms, scroll, read console logs and network requests, manage tabs, resize windows, and record GIFs. Run `/mcp` and click into `claude-in-chrome` to see the full list of available tools. The following examples show common patterns for browser automation. ### Test a local web application When developing a web app, ask Claude to verify your changes work correctly: ``` I just updated the login form validation. Can you open localhost:3000, try submitting the form with invalid data, and check if the error messages appear correctly? ``` Claude navigates to your local server, interacts with the form, and reports what it observes. ### Debug with console logs If your app has issues, Claude can read console output to help diagnose problems: ``` Open the dashboard page and check the console for any errors when the page loads. ``` Claude reads the console messages and can filter for specific patterns or error types. ### Automate form filling Speed up repetitive data entry tasks: ``` I have a spreadsheet of customer contacts in contacts.csv. For each row, go to our CRM at crm.example.com, click "Add Contact", and fill in the name, email, and phone fields. ``` Claude reads your local file, navigates the web interface, and enters the data for each record. ### Draft content in Google Docs Use Claude to write directly in your documents without API setup: ``` Draft a project update based on our recent commits and add it to my Google Doc at docs.google.com/document/d/abc123 ``` Claude opens the document, clicks into the editor, and types the content. This works with any web app you're logged into: Gmail, Notion, Sheets, and more. ### Extract data from web pages Pull structured information from websites: ``` Go to the product listings page and extract the name, price, and availability for each item. Save the results as a CSV file. ``` Claude navigates to the page, reads the content, and compiles the data into a structured format. ### Run multi-site workflows Coordinate tasks across multiple websites: ``` Check my calendar for meetings tomorrow, then for each meeting with an external attendee, look up their company on LinkedIn and add a note about what they do. ``` Claude works across tabs to gather information and complete the workflow. ### Record a demo GIF Create shareable recordings of browser interactions: ``` Record a GIF showing how to complete the checkout flow, from adding an item to the cart through to the confirmation page. ``` Claude records the interaction sequence and saves it as a GIF file. ## Best practices When using browser automation, keep these guidelines in mind: * **Modal dialogs can interrupt the flow**: JavaScript alerts, confirms, and prompts block browser events and prevent Claude from receiving commands. If a dialog appears, dismiss it manually and tell Claude to continue. * **Use fresh tabs**: Claude creates new tabs for each session. If a tab becomes unresponsive, ask Claude to create a new one. * **Filter console output**: Console logs can be verbose. When debugging, tell Claude what patterns to look for rather than asking for all console output. ## Troubleshooting ### Extension not detected If Claude Code shows "Chrome extension not detected": 1. Verify the Chrome extension (version 1.0.36 or higher) is installed 2. Verify Claude Code is version 2.0.73 or higher by running `claude --version` 3. Check that Chrome is running 4. Run `/chrome` and select "Reconnect extension" to re-establish the connection 5. If the issue persists, restart both Claude Code and Chrome ### Browser not responding If Claude's browser commands stop working: 1. Check if a modal dialog (alert, confirm, prompt) is blocking the page 2. Ask Claude to create a new tab and try again 3. Restart the Chrome extension by disabling and re-enabling it ### First-time setup The first time you use the integration, Claude Code installs a native messaging host that allows communication between the CLI and Chrome. If you encounter permission errors, you may need to restart Chrome for the installation to take effect. ## Enable by default Chrome integration requires the `--chrome` flag each time you start Claude Code. To enable it by default, run `/chrome` and select "Enabled by default". Enabling Chrome by default increases context usage since browser tools are always loaded. If you notice increased context consumption, disable this setting and use `--chrome` only when needed. Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on. Run `/chrome` to see current permission settings. ## See also * [CLI reference](/en/cli-reference) - Command-line flags including `--chrome` * [Common workflows](/en/common-workflows) - More ways to use Claude Code * [Getting started with Claude for Chrome](https://support.anthropic.com/en/articles/12012173-getting-started-with-claude-for-chrome) - Full documentation for the Chrome extension, including shortcuts, scheduling, and permissions --- # Source: https://code.claude.com/docs/en/claude-code-on-the-web.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code on the web > Run Claude Code tasks asynchronously on secure cloud infrastructure Claude Code on the web is currently in research preview. ## What is Claude Code on the web? Claude Code on the web lets developers kick off Claude Code from the Claude app. This is perfect for: * **Answering questions**: Ask about code architecture and how features are implemented * **Bug fixes and routine tasks**: Well-defined tasks that don't require frequent steering * **Parallel work**: Tackle multiple bug fixes in parallel * **Repositories not on your local machine**: Work on code you don't have checked out locally * **Backend changes**: Where Claude Code can write tests and then write code to pass those tests Claude Code is also available on the Claude iOS app for kicking off tasks on the go and monitoring work in progress. You can move between local and remote development: [send tasks from your terminal to run on the web](#from-terminal-to-web) with the `&` prefix, or [teleport web sessions back to your terminal](#from-web-to-terminal) to continue locally. ## Who can use Claude Code on the web? Claude Code on the web is available in research preview to: * **Pro users** * **Max users** * **Team premium seat users** * **Enterprise premium seat users** ## Getting started 1. Visit [claude.ai/code](https://claude.ai/code) 2. Connect your GitHub account 3. Install the Claude GitHub app in your repositories 4. Select your default environment 5. Submit your coding task 6. Review changes in diff view, iterate with comments, then create a pull request ## How it works When you start a task on Claude Code on the web: 1. **Repository cloning**: Your repository is cloned to an Anthropic-managed virtual machine 2. **Environment setup**: Claude prepares a secure cloud environment with your code 3. **Network configuration**: Internet access is configured based on your settings 4. **Task execution**: Claude analyzes code, makes changes, runs tests, and checks its work 5. **Completion**: You're notified when finished and can create a PR with the changes 6. **Results**: Changes are pushed to a branch, ready for pull request creation ## Review changes with diff view Diff view lets you see exactly what Claude changed before creating a pull request. Instead of clicking "Create PR" to review changes in GitHub, view the diff directly in the app and iterate with Claude until the changes are ready. When Claude makes changes to files, a diff stats indicator appears showing the number of lines added and removed (for example, `+12 -1`). Select this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right. From the diff view, you can: * Review changes file by file * Comment on specific changes to request modifications * Continue iterating with Claude based on what you see This lets you refine changes through multiple rounds of feedback without creating draft PRs or switching to GitHub. ## Moving tasks between web and terminal You can start tasks on the web and continue them in your terminal, or send tasks from your terminal to run on the web. Web sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude iOS app. Session handoff is one-way: you can pull web sessions into your terminal, but you can't push an existing terminal session to the web. The [`&` prefix](#from-terminal-to-web) creates a *new* web session with your current conversation context. ### From terminal to web Start a message with `&` inside Claude Code to send a task to run on the web: ``` & Fix the authentication bug in src/auth/login.ts ``` This creates a new web session on claude.ai with your current conversation context. The task runs in the cloud while you continue working locally. Use `/tasks` to check progress, or open the session on claude.ai or the Claude iOS app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation. You can also start a web session directly from the command line: ```bash theme={null} claude --remote "Fix the authentication bug in src/auth/login.ts" ``` #### Tips for background tasks **Plan locally, execute remotely**: For complex tasks, start Claude in plan mode to collaborate on the approach before sending work to the web: ```bash theme={null} claude --permission-mode plan ``` In plan mode, Claude can only read files and explore the codebase. Once you're satisfied with the plan, send it to the web for autonomous execution: ``` & Execute the migration plan we discussed ``` This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud. **Run tasks in parallel**: Each `&` command creates its own web session that runs independently. You can kick off multiple tasks and they'll all run simultaneously in separate sessions: ``` & Fix the flaky test in auth.spec.ts & Update the API documentation & Refactor the logger to use structured output ``` Monitor all sessions with `/tasks`. When a session completes, you can create a PR from the web interface or [teleport](#from-web-to-terminal) the session to your terminal to continue working. ### From web to terminal There are several ways to pull a web session into your terminal: * **Using `/teleport`**: From within Claude Code, run `/teleport` (or `/tp`) to see an interactive picker of your web sessions. If you have uncommitted changes, you'll be prompted to stash them first. * **Using `--teleport`**: From the command line, run `claude --teleport` for an interactive session picker, or `claude --teleport ` to resume a specific session directly. * **From `/tasks`**: Run `/tasks` to see your background sessions, then press `t` to teleport into one * **From the web interface**: Click "Open in CLI" to copy a command you can paste into your terminal When you teleport a session, Claude verifies you're in the correct repository, fetches and checks out the branch from the remote session, and loads the full conversation history into your terminal. #### Requirements for teleporting Teleport checks these requirements before resuming a session. If any requirement isn't met, you'll see an error or be prompted to resolve the issue. | Requirement | Details | | ------------------ | ---------------------------------------------------------------------------------------------------------------------- | | Clean git state | Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed. | | Correct repository | You must run `--teleport` from a checkout of the same repository, not a fork. | | Branch available | The branch from the web session must have been pushed to the remote. Teleport automatically fetches and checks it out. | | Same account | You must be authenticated to the same Claude.ai account used in the web session. | ## Cloud environment ### Default image We build and maintain a universal image with common toolchains and language ecosystems pre-installed. This image includes: * Popular programming languages and runtimes * Common build tools and package managers * Testing frameworks and linters #### Checking available tools To see what's pre-installed in your environment, ask Claude Code to run: ```bash theme={null} check-tools ``` This command displays: * Programming languages and their versions * Available package managers * Installed development tools #### Language-specific setups The universal image includes pre-configured environments for: * **Python**: Python 3.x with pip, poetry, and common scientific libraries * **Node.js**: Latest LTS versions with npm, yarn, pnpm, and bun * **Ruby**: Versions 3.1.6, 3.2.6, 3.3.6 (default: 3.3.6) with gem, bundler, and rbenv for version management * **PHP**: Version 8.4.14 * **Java**: OpenJDK with Maven and Gradle * **Go**: Latest stable version with module support * **Rust**: Rust toolchain with cargo * **C++**: GCC and Clang compilers #### Databases The universal image includes the following databases: * **PostgreSQL**: Version 16 * **Redis**: Version 7.0 ### Environment configuration When you start a session in Claude Code on the web, here's what happens under the hood: 1. **Environment preparation**: We clone your repository and run any configured Claude hooks for initialization. The repo will be cloned with the default branch on your GitHub repo. If you would like to check out a specific branch, you can specify that in the prompt. 2. **Network configuration**: We configure internet access for the agent. Internet access is limited by default, but you can configure the environment to have no internet or full internet access based on your needs. 3. **Claude Code execution**: Claude Code runs to complete your task, writing code, running tests, and checking its work. You can guide and steer Claude throughout the session via the web interface. Claude respects context you've defined in your `CLAUDE.md`. 4. **Outcome**: When Claude completes its work, it will push the branch to remote. You will be able to create a PR for the branch. Claude operates entirely through the terminal and CLI tools available in the environment. It uses the pre-installed tools in the universal image and any additional tools you install through hooks or dependency management. **To add a new environment:** Select the current environment to open the environment selector, and then select "Add environment". This will open a dialog where you can specify the environment name, network access level, and any environment variables you want to set. **To update an existing environment:** Select the current environment, to the right of the environment name, and select the settings button. This will open a dialog where you can update the environment name, network access, and environment variables. **To select your default environment from the terminal:** If you have multiple environments configured, run `/remote-env` to choose which one to use when starting web sessions from your terminal with `&` or `--remote`. With a single environment, this command shows your current configuration. Environment variables must be specified as key-value pairs, in [`.env` format](https://www.dotenv.org/). For example: ``` API_KEY=your_api_key DEBUG=true ``` ### Dependency management Configure automatic dependency installation using [SessionStart hooks](/en/hooks#sessionstart). This can be configured in your repository's `.claude/settings.json` file: ```json theme={null} { "hooks": { "SessionStart": [ { "matcher": "startup", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh" } ] } ] } } ``` Create the corresponding script at `scripts/install_pkgs.sh`: ```bash theme={null} #!/bin/bash npm install pip install -r requirements.txt exit 0 ``` Make it executable: `chmod +x scripts/install_pkgs.sh` #### Local vs remote execution By default, all hooks execute both locally and in remote (web) environments. To run a hook only in one environment, check the `CLAUDE_CODE_REMOTE` environment variable in your hook script. ```bash theme={null} #!/bin/bash # Example: Only run in remote environments if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then exit 0 fi npm install pip install -r requirements.txt ``` #### Persisting environment variables SessionStart hooks can persist environment variables for subsequent bash commands by writing to the file specified in the `CLAUDE_ENV_FILE` environment variable. For details, see [SessionStart hooks](/en/hooks#sessionstart) in the hooks reference. ## Network access and security ### Network policy #### GitHub proxy For security, all GitHub operations go through a dedicated proxy service that transparently handles all git interactions. Inside the sandbox, the git client authenticates using a custom-built scoped credential. This proxy: * Manages GitHub authentication securely - the git client uses a scoped credential inside the sandbox, which the proxy verifies and translates to your actual GitHub authentication token * Restricts git push operations to the current working branch for safety * Enables seamless cloning, fetching, and PR operations while maintaining security boundaries #### Security proxy Environments run behind an HTTP/HTTPS network proxy for security and abuse prevention purposes. All outbound internet traffic passes through this proxy, which provides: * Protection against malicious requests * Rate limiting and abuse prevention * Content filtering for enhanced security ### Access levels By default, network access is limited to [allowlisted domains](#default-allowed-domains). You can configure custom network access, including disabling network access. ### Default allowed domains When using "Limited" network access, the following domains are allowed by default: #### Anthropic Services * api.anthropic.com * statsig.anthropic.com * docs.claude.com * code.claude.com * claude.ai #### Version Control * github.com * [www.github.com](http://www.github.com) * api.github.com * npm.pkg.github.com * raw\.githubusercontent.com * pkg-npm.githubusercontent.com * objects.githubusercontent.com * codeload.github.com * avatars.githubusercontent.com * camo.githubusercontent.com * gist.github.com * gitlab.com * [www.gitlab.com](http://www.gitlab.com) * registry.gitlab.com * bitbucket.org * [www.bitbucket.org](http://www.bitbucket.org) * api.bitbucket.org #### Container Registries * registry-1.docker.io * auth.docker.io * index.docker.io * hub.docker.com * [www.docker.com](http://www.docker.com) * production.cloudflare.docker.com * download.docker.com * gcr.io * \*.gcr.io * ghcr.io * mcr.microsoft.com * \*.data.mcr.microsoft.com * public.ecr.aws #### Cloud Platforms * cloud.google.com * accounts.google.com * gcloud.google.com * \*.googleapis.com * storage.googleapis.com * compute.googleapis.com * container.googleapis.com * azure.com * portal.azure.com * microsoft.com * [www.microsoft.com](http://www.microsoft.com) * \*.microsoftonline.com * packages.microsoft.com * dotnet.microsoft.com * dot.net * visualstudio.com * dev.azure.com * \*.amazonaws.com * \*.api.aws * oracle.com * [www.oracle.com](http://www.oracle.com) * java.com * [www.java.com](http://www.java.com) * java.net * [www.java.net](http://www.java.net) * download.oracle.com * yum.oracle.com #### Package Managers - JavaScript/Node * registry.npmjs.org * [www.npmjs.com](http://www.npmjs.com) * [www.npmjs.org](http://www.npmjs.org) * npmjs.com * npmjs.org * yarnpkg.com * registry.yarnpkg.com #### Package Managers - Python * pypi.org * [www.pypi.org](http://www.pypi.org) * files.pythonhosted.org * pythonhosted.org * test.pypi.org * pypi.python.org * pypa.io * [www.pypa.io](http://www.pypa.io) #### Package Managers - Ruby * rubygems.org * [www.rubygems.org](http://www.rubygems.org) * api.rubygems.org * index.rubygems.org * ruby-lang.org * [www.ruby-lang.org](http://www.ruby-lang.org) * rubyforge.org * [www.rubyforge.org](http://www.rubyforge.org) * rubyonrails.org * [www.rubyonrails.org](http://www.rubyonrails.org) * rvm.io * get.rvm.io #### Package Managers - Rust * crates.io * [www.crates.io](http://www.crates.io) * index.crates.io * static.crates.io * rustup.rs * static.rust-lang.org * [www.rust-lang.org](http://www.rust-lang.org) #### Package Managers - Go * proxy.golang.org * sum.golang.org * index.golang.org * golang.org * [www.golang.org](http://www.golang.org) * goproxy.io * pkg.go.dev #### Package Managers - JVM * maven.org * repo.maven.org * central.maven.org * repo1.maven.org * jcenter.bintray.com * gradle.org * [www.gradle.org](http://www.gradle.org) * services.gradle.org * plugins.gradle.org * kotlin.org * [www.kotlin.org](http://www.kotlin.org) * spring.io * repo.spring.io #### Package Managers - Other Languages * packagist.org (PHP Composer) * [www.packagist.org](http://www.packagist.org) * repo.packagist.org * nuget.org (.NET NuGet) * [www.nuget.org](http://www.nuget.org) * api.nuget.org * pub.dev (Dart/Flutter) * api.pub.dev * hex.pm (Elixir/Erlang) * [www.hex.pm](http://www.hex.pm) * cpan.org (Perl CPAN) * [www.cpan.org](http://www.cpan.org) * metacpan.org * [www.metacpan.org](http://www.metacpan.org) * api.metacpan.org * cocoapods.org (iOS/macOS) * [www.cocoapods.org](http://www.cocoapods.org) * cdn.cocoapods.org * haskell.org * [www.haskell.org](http://www.haskell.org) * hackage.haskell.org * swift.org * [www.swift.org](http://www.swift.org) #### Linux Distributions * archive.ubuntu.com * security.ubuntu.com * ubuntu.com * [www.ubuntu.com](http://www.ubuntu.com) * \*.ubuntu.com * ppa.launchpad.net * launchpad.net * [www.launchpad.net](http://www.launchpad.net) #### Development Tools & Platforms * dl.k8s.io (Kubernetes) * pkgs.k8s.io * k8s.io * [www.k8s.io](http://www.k8s.io) * releases.hashicorp.com (HashiCorp) * apt.releases.hashicorp.com * rpm.releases.hashicorp.com * archive.releases.hashicorp.com * hashicorp.com * [www.hashicorp.com](http://www.hashicorp.com) * repo.anaconda.com (Anaconda/Conda) * conda.anaconda.org * anaconda.org * [www.anaconda.com](http://www.anaconda.com) * anaconda.com * continuum.io * apache.org (Apache) * [www.apache.org](http://www.apache.org) * archive.apache.org * downloads.apache.org * eclipse.org (Eclipse) * [www.eclipse.org](http://www.eclipse.org) * download.eclipse.org * nodejs.org (Node.js) * [www.nodejs.org](http://www.nodejs.org) #### Cloud Services & Monitoring * statsig.com * [www.statsig.com](http://www.statsig.com) * api.statsig.com * sentry.io * \*.sentry.io * http-intake.logs.datadoghq.com * \*.datadoghq.com * \*.datadoghq.eu #### Content Delivery & Mirrors * sourceforge.net * \*.sourceforge.net * packagecloud.io * \*.packagecloud.io #### Schema & Configuration * json-schema.org * [www.json-schema.org](http://www.json-schema.org) * json.schemastore.org * [www.schemastore.org](http://www.schemastore.org) #### Model Context Protocol * \*.modelcontextprotocol.io Domains marked with `*` indicate wildcard subdomain matching. For example, `*.gcr.io` allows access to any subdomain of `gcr.io`. ### Security best practices for customized network access 1. **Principle of least privilege**: Only enable the minimum network access required 2. **Audit regularly**: Review allowed domains periodically 3. **Use HTTPS**: Always prefer HTTPS endpoints over HTTP ## Security and isolation Claude Code on the web provides strong security guarantees: * **Isolated virtual machines**: Each session runs in an isolated, Anthropic-managed VM * **Network access controls**: Network access is limited by default, and can be disabled When running with network access disabled, Claude Code is allowed to communicate with the Anthropic API which may still allow data to exit the isolated Claude Code VM. * **Credential protection**: Sensitive credentials (such as git credentials or signing keys) are never inside the sandbox with Claude Code. Authentication is handled through a secure proxy using scoped credentials * **Secure analysis**: Code is analyzed and modified within isolated VMs before creating PRs ## Pricing and rate limits Claude Code on the web shares rate limits with all other Claude and Claude Code usage within your account. Running multiple tasks in parallel will consume more rate limits proportionately. ## Limitations * **Repository authentication**: You can only move sessions from web to local when you are authenticated to the same account * **Platform restrictions**: Claude Code on the web only works with code hosted in GitHub. GitLab and other non-GitHub repositories cannot be used with cloud sessions ## Best practices 1. **Use Claude Code hooks**: Configure [SessionStart hooks](/en/hooks#sessionstart) to automate environment setup and dependency installation. 2. **Document requirements**: Clearly specify dependencies and commands in your `CLAUDE.md` file. If you have an `AGENTS.md` file, you can source it in your `CLAUDE.md` using `@AGENTS.md` to maintain a single source of truth. ## Related resources * [Hooks configuration](/en/hooks) * [Settings reference](/en/settings) * [Security](/en/security) * [Data usage](/en/data-usage) --- # Source: https://code.claude.com/docs/en/cli-reference.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # CLI reference > Complete reference for Claude Code command-line interface, including commands and flags. ## CLI commands | Command | Description | Example | | :------------------------------ | :----------------------------------------------------- | :------------------------------------------------ | | `claude` | Start interactive REPL | `claude` | | `claude "query"` | Start REPL with initial prompt | `claude "explain this project"` | | `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` | | `cat file \| claude -p "query"` | Process piped content | `cat logs.txt \| claude -p "explain"` | | `claude -c` | Continue most recent conversation in current directory | `claude -c` | | `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` | | `claude -r "" "query"` | Resume session by ID or name | `claude -r "auth-refactor" "Finish this PR"` | | `claude update` | Update to latest version | `claude update` | | `claude mcp` | Configure Model Context Protocol (MCP) servers | See the [Claude Code MCP documentation](/en/mcp). | ## CLI flags Customize Claude Code's behavior with these command-line flags: | Flag | Description | Example | | :------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- | | `--add-dir` | Add additional working directories for Claude to access (validates each path exists as a directory) | `claude --add-dir ../apps ../lib` | | `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` | | `--agents` | Define custom [subagents](/en/sub-agents) dynamically via JSON (see below for format) | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` | | `--allow-dangerously-skip-permissions` | Enable permission bypassing as an option without immediately activating it. Allows composing with `--permission-mode` (use with caution) | `claude --permission-mode plan --allow-dangerously-skip-permissions` | | `--allowedTools` | Tools that execute without prompting for permission. See [permission rule syntax](/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log *)" "Bash(git diff *)" "Read"` | | `--append-system-prompt` | Append custom text to the end of the default system prompt (works in both interactive and print modes) | `claude --append-system-prompt "Always use TypeScript"` | | `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt (print mode only) | `claude -p --append-system-prompt-file ./extra-rules.txt "query"` | | `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` | | `--chrome` | Enable [Chrome browser integration](/en/chrome) for web automation and testing | `claude --chrome` | | `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` | | `--dangerously-skip-permissions` | Skip all permission prompts (use with caution) | `claude --dangerously-skip-permissions` | | `--debug` | Enable debug mode with optional category filtering (for example, `"api,hooks"` or `"!statsig,!file"`) | `claude --debug "api,mcp"` | | `--disable-slash-commands` | Disable all skills and slash commands for this session | `claude --disable-slash-commands` | | `--disallowedTools` | Tools that are removed from the model's context and cannot be used | `"Bash(git log *)" "Bash(git diff *)" "Edit"` | | `--fallback-model` | Enable automatic fallback to specified model when default model is overloaded (print mode only) | `claude -p --fallback-model sonnet "query"` | | `--fork-session` | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`) | `claude --resume abc123 --fork-session` | | `--from-pr` | Resume sessions linked to a specific GitHub PR. Accepts a PR number or URL. Sessions are automatically linked when created via `gh pr create` | `claude --from-pr 123` | | `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` | | `--init` | Run initialization hooks and start interactive mode | `claude --init` | | `--init-only` | Run initialization hooks and exit (no interactive session) | `claude --init-only` | | `--include-partial-messages` | Include partial streaming events in output (requires `--print` and `--output-format=stream-json`) | `claude -p --output-format stream-json --include-partial-messages "query"` | | `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` | | `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [Agent SDK Structured Outputs](https://docs.claude.com/en/docs/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` | | `--maintenance` | Run maintenance hooks and exit | `claude --maintenance` | | `--max-budget-usd` | Maximum dollar amount to spend on API calls before stopping (print mode only) | `claude -p --max-budget-usd 5.00 "query"` | | `--max-turns` | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default | `claude -p --max-turns 3 "query"` | | `--mcp-config` | Load MCP servers from JSON files or strings (space-separated) | `claude --mcp-config ./mcp.json` | | `--model` | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name | `claude --model claude-sonnet-4-5-20250929` | | `--no-chrome` | Disable [Chrome browser integration](/en/chrome) for this session | `claude --no-chrome` | | `--no-session-persistence` | Disable session persistence so sessions are not saved to disk and cannot be resumed (print mode only) | `claude -p --no-session-persistence "query"` | | `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` | | `--permission-mode` | Begin in a specified [permission mode](/en/permissions#permission-modes) | `claude --permission-mode plan` | | `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode | `claude -p --permission-prompt-tool mcp_auth_tool "query"` | | `--plugin-dir` | Load plugins from directories for this session only (repeatable) | `claude --plugin-dir ./my-plugins` | | `--print`, `-p` | Print response without interactive mode (see [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) for programmatic usage details) | `claude -p "query"` | | `--remote` | Create a new [web session](/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` | | `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session | `claude --resume auth-refactor` | | `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` | | `--setting-sources` | Comma-separated list of setting sources to load (`user`, `project`, `local`) | `claude --setting-sources user,project` | | `--settings` | Path to a settings JSON file or a JSON string to load additional settings from | `claude --settings ./settings.json` | | `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations | `claude --strict-mcp-config --mcp-config ./mcp.json` | | `--system-prompt` | Replace the entire system prompt with custom text (works in both interactive and print modes) | `claude --system-prompt "You are a Python expert"` | | `--system-prompt-file` | Load system prompt from a file, replacing the default prompt (print mode only) | `claude -p --system-prompt-file ./custom-prompt.txt "query"` | | `--teleport` | Resume a [web session](/en/claude-code-on-the-web) in your local terminal | `claude --teleport` | | `--tools` | Restrict which built-in tools Claude can use (works in both interactive and print modes). Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` | | `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` | | `--version`, `-v` | Output the version number | `claude -v` | The `--output-format json` flag is particularly useful for scripting and automation, allowing you to parse Claude's responses programmatically. ### Agents flag format The `--agents` flag accepts a JSON object that defines one or more custom subagents. Each subagent requires a unique name (as the key) and a definition object with the following fields: | Field | Required | Description | | :------------ | :------- | :---------------------------------------------------------------------------------------------------------------------------------- | | `description` | Yes | Natural language description of when the subagent should be invoked | | `prompt` | Yes | The system prompt that guides the subagent's behavior | | `tools` | No | Array of specific tools the subagent can use (for example, `["Read", "Edit", "Bash"]`). If omitted, inherits all tools | | `model` | No | Model alias to use: `sonnet`, `opus`, `haiku`, or `inherit`. If omitted, defaults to `inherit` (uses the main conversation's model) | Example: ```bash theme={null} claude --agents '{ "code-reviewer": { "description": "Expert code reviewer. Use proactively after code changes.", "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.", "tools": ["Read", "Grep", "Glob", "Bash"], "model": "sonnet" }, "debugger": { "description": "Debugging specialist for errors and test failures.", "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes." } }' ``` For more details on creating and using subagents, see the [subagents documentation](/en/sub-agents). ### System prompt flags Claude Code provides four flags for customizing the system prompt, each serving a different purpose: | Flag | Behavior | Modes | Use Case | | :---------------------------- | :------------------------------------------ | :------------------ | :------------------------------------------------------------------- | | `--system-prompt` | **Replaces** entire default prompt | Interactive + Print | Complete control over Claude's behavior and instructions | | `--system-prompt-file` | **Replaces** with file contents | Print only | Load prompts from files for reproducibility and version control | | `--append-system-prompt` | **Appends** to default prompt | Interactive + Print | Add specific instructions while keeping default Claude Code behavior | | `--append-system-prompt-file` | **Appends** file contents to default prompt | Print only | Load additional instructions from files while keeping defaults | **When to use each:** * **`--system-prompt`**: Use when you need complete control over Claude's system prompt. This removes all default Claude Code instructions, giving you a blank slate. ```bash theme={null} claude --system-prompt "You are a Python expert who only writes type-annotated code" ``` * **`--system-prompt-file`**: Use when you want to load a custom prompt from a file, useful for team consistency or version-controlled prompt templates. ```bash theme={null} claude -p --system-prompt-file ./prompts/code-review.txt "Review this PR" ``` * **`--append-system-prompt`**: Use when you want to add specific instructions while keeping Claude Code's default capabilities intact. This is the safest option for most use cases. ```bash theme={null} claude --append-system-prompt "Always use TypeScript and include JSDoc comments" ``` * **`--append-system-prompt-file`**: Use when you want to append instructions from a file while keeping Claude Code's defaults. Useful for version-controlled additions. ```bash theme={null} claude -p --append-system-prompt-file ./prompts/style-rules.txt "Review this PR" ``` `--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be used together with either replacement flag. For most use cases, `--append-system-prompt` or `--append-system-prompt-file` is recommended as they preserve Claude Code's built-in capabilities while adding your custom requirements. Use `--system-prompt` or `--system-prompt-file` only when you need complete control over the system prompt. ## See also * [Chrome extension](/en/chrome) - Browser automation and web testing * [Interactive mode](/en/interactive-mode) - Shortcuts, input modes, and interactive features * [Quickstart guide](/en/quickstart) - Getting started with Claude Code * [Common workflows](/en/common-workflows) - Advanced workflows and patterns * [Settings](/en/settings) - Configuration options * [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) - Programmatic usage and integrations --- # Source: https://code.claude.com/docs/en/common-workflows.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Common workflows > Step-by-step guides for exploring codebases, fixing bugs, refactoring, testing, and other everyday tasks with Claude Code. This page covers practical workflows for everyday development: exploring unfamiliar code, debugging, refactoring, writing tests, creating PRs, and managing sessions. Each section includes example prompts you can adapt to your own projects. For higher-level patterns and tips, see [Best practices](/en/best-practices). ## Understand new codebases ### Get a quick codebase overview Suppose you've just joined a new project and need to understand its structure quickly. ```bash theme={null} cd /path/to/project ``` ```bash theme={null} claude ``` ``` > give me an overview of this codebase ``` ``` > explain the main architecture patterns used here ``` ``` > what are the key data models? ``` ``` > how is authentication handled? ``` Tips: * Start with broad questions, then narrow down to specific areas * Ask about coding conventions and patterns used in the project * Request a glossary of project-specific terms ### Find relevant code Suppose you need to locate code related to a specific feature or functionality. ``` > find the files that handle user authentication ``` ``` > how do these authentication files work together? ``` ``` > trace the login process from front-end to database ``` Tips: * Be specific about what you're looking for * Use domain language from the project * Install a [code intelligence plugin](/en/discover-plugins#code-intelligence) for your language to give Claude precise "go to definition" and "find references" navigation *** ## Fix bugs efficiently Suppose you've encountered an error message and need to find and fix its source. ``` > I'm seeing an error when I run npm test ``` ``` > suggest a few ways to fix the @ts-ignore in user.ts ``` ``` > update user.ts to add the null check you suggested ``` Tips: * Tell Claude the command to reproduce the issue and get a stack trace * Mention any steps to reproduce the error * Let Claude know if the error is intermittent or consistent *** ## Refactor code Suppose you need to update old code to use modern patterns and practices. ``` > find deprecated API usage in our codebase ``` ``` > suggest how to refactor utils.js to use modern JavaScript features ``` ``` > refactor utils.js to use ES2024 features while maintaining the same behavior ``` ``` > run tests for the refactored code ``` Tips: * Ask Claude to explain the benefits of the modern approach * Request that changes maintain backward compatibility when needed * Do refactoring in small, testable increments *** ## Use specialized subagents Suppose you want to use specialized AI subagents to handle specific tasks more effectively. ``` > /agents ``` This shows all available subagents and lets you create new ones. Claude Code automatically delegates appropriate tasks to specialized subagents: ``` > review my recent code changes for security issues ``` ``` > run all tests and fix any failures ``` ``` > use the code-reviewer subagent to check the auth module ``` ``` > have the debugger subagent investigate why users can't log in ``` ``` > /agents ``` Then select "Create New subagent" and follow the prompts to define: * A unique identifier that describes the subagent's purpose (for example, `code-reviewer`, `api-designer`). * When Claude should use this agent * Which tools it can access * A system prompt describing the agent's role and behavior Tips: * Create project-specific subagents in `.claude/agents/` for team sharing * Use descriptive `description` fields to enable automatic delegation * Limit tool access to what each subagent actually needs * Check the [subagents documentation](/en/sub-agents) for detailed examples *** ## Use Plan Mode for safe code analysis Plan Mode instructs Claude to create a plan by analyzing the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely. In Plan Mode, Claude uses [`AskUserQuestion`](/en/settings#tools-available-to-claude) to gather requirements and clarify your goals before proposing a plan. ### When to use Plan Mode * **Multi-step implementation**: When your feature requires making edits to many files * **Code exploration**: When you want to research the codebase thoroughly before changing anything * **Interactive development**: When you want to iterate on the direction with Claude ### How to use Plan Mode **Turn on Plan Mode during a session** You can switch into Plan Mode during a session using **Shift+Tab** to cycle through permission modes. If you are in Normal Mode, **Shift+Tab** first switches into Auto-Accept Mode, indicated by `⏵⏵ accept edits on` at the bottom of the terminal. A subsequent **Shift+Tab** will switch into Plan Mode, indicated by `⏸ plan mode on`. **Start a new session in Plan Mode** To start a new session in Plan Mode, use the `--permission-mode plan` flag: ```bash theme={null} claude --permission-mode plan ``` **Run "headless" queries in Plan Mode** You can also run a query in Plan Mode directly with `-p` (that is, in ["headless mode"](/en/headless)): ```bash theme={null} claude --permission-mode plan -p "Analyze the authentication system and suggest improvements" ``` ### Example: Planning a complex refactor ```bash theme={null} claude --permission-mode plan ``` ``` > I need to refactor our authentication system to use OAuth2. Create a detailed migration plan. ``` Claude analyzes the current implementation and create a comprehensive plan. Refine with follow-ups: ``` > What about backward compatibility? > How should we handle database migration? ``` Press `Ctrl+G` to open the plan in your default text editor, where you can edit it directly before Claude proceeds. ### Configure Plan Mode as default ```json theme={null} // .claude/settings.json { "permissions": { "defaultMode": "plan" } } ``` See [settings documentation](/en/settings#available-settings) for more configuration options. *** ## Work with tests Suppose you need to add tests for uncovered code. ``` > find functions in NotificationsService.swift that are not covered by tests ``` ``` > add tests for the notification service ``` ``` > add test cases for edge conditions in the notification service ``` ``` > run the new tests and fix any failures ``` Claude can generate tests that follow your project's existing patterns and conventions. When asking for tests, be specific about what behavior you want to verify. Claude examines your existing test files to match the style, frameworks, and assertion patterns already in use. For comprehensive coverage, ask Claude to identify edge cases you might have missed. Claude can analyze your code paths and suggest tests for error conditions, boundary values, and unexpected inputs that are easy to overlook. *** ## Create pull requests You can create pull requests by asking Claude directly ("create a pr for my changes") or by using the `/commit-push-pr` skill, which commits, pushes, and opens a PR in one step. ``` > /commit-push-pr ``` If you have a Slack MCP server configured and specify channels in your CLAUDE.md (for example, "post PR URLs to #team-prs"), the skill automatically posts the PR URL to those channels. For more control over the process, guide Claude through it step-by-step or [create your own skill](/en/skills): ``` > summarize the changes I've made to the authentication module ``` ``` > create a pr ``` ``` > enhance the PR description with more context about the security improvements ``` When you create a PR using `gh pr create`, the session is automatically linked to that PR. You can resume it later with `claude --from-pr `. Review Claude's generated PR before submitting and ask Claude to highlight potential risks or considerations. ## Handle documentation Suppose you need to add or update documentation for your code. ``` > find functions without proper JSDoc comments in the auth module ``` ``` > add JSDoc comments to the undocumented functions in auth.js ``` ``` > improve the generated documentation with more context and examples ``` ``` > check if the documentation follows our project standards ``` Tips: * Specify the documentation style you want (JSDoc, docstrings, etc.) * Ask for examples in the documentation * Request documentation for public APIs, interfaces, and complex logic *** ## Work with images Suppose you need to work with images in your codebase, and you want Claude's help analyzing image content. You can use any of these methods: 1. Drag and drop an image into the Claude Code window 2. Copy an image and paste it into the CLI with ctrl+v (Do not use cmd+v) 3. Provide an image path to Claude. E.g., "Analyze this image: /path/to/your/image.png" ``` > What does this image show? ``` ``` > Describe the UI elements in this screenshot ``` ``` > Are there any problematic elements in this diagram? ``` ``` > Here's a screenshot of the error. What's causing it? ``` ``` > This is our current database schema. How should we modify it for the new feature? ``` ``` > Generate CSS to match this design mockup ``` ``` > What HTML structure would recreate this component? ``` Tips: * Use images when text descriptions would be unclear or cumbersome * Include screenshots of errors, UI designs, or diagrams for better context * You can work with multiple images in a conversation * Image analysis works with diagrams, screenshots, mockups, and more * When Claude references images (for example, `[Image #1]`), `Cmd+Click` (Mac) or `Ctrl+Click` (Windows/Linux) the link to open the image in your default viewer *** ## Reference files and directories Use @ to quickly include files or directories without waiting for Claude to read them. ``` > Explain the logic in @src/utils/auth.js ``` This includes the full content of the file in the conversation. ``` > What's the structure of @src/components? ``` This provides a directory listing with file information. ``` > Show me the data from @github:repos/owner/repo/issues ``` This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/en/mcp#use-mcp-resources) for details. Tips: * File paths can be relative or absolute * @ file references add `CLAUDE.md` in the file's directory and parent directories to context * Directory references show file listings, not contents * You can reference multiple files in a single message (for example, "@file1.js and @file2.js") *** ## Use extended thinking (thinking mode) [Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is enabled by default, reserving a portion of the output token budget (up to 31,999 tokens) for Claude to reason through complex problems step-by-step. This reasoning is visible in verbose mode, which you can toggle on with `Ctrl+O`. Extended thinking is particularly valuable for complex architectural decisions, challenging bugs, multi-step implementation planning, and evaluating tradeoffs between different approaches. It provides more space for exploring multiple solutions, analyzing edge cases, and self-correcting mistakes. Phrases like "think", "think hard", "ultrathink", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens. ### Configure thinking mode Thinking is enabled by default, but you can adjust or disable it. | Scope | How to configure | Details | | ---------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | | **Toggle shortcut** | Press `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle thinking on/off for the current session. May require [terminal configuration](/en/terminal-config) to enable Option key shortcuts | | **Global default** | Use `/config` to toggle thinking mode | Sets your default across all projects.
Saved as `alwaysThinkingEnabled` in `~/.claude/settings.json` | | **Limit token budget** | Set [`MAX_THINKING_TOKENS`](/en/settings#environment-variables) environment variable | Limit the thinking budget to a specific number of tokens. Example: `export MAX_THINKING_TOKENS=10000` | To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text. ### How extended thinking token budgets work Extended thinking uses a **token budget** that controls how much internal reasoning Claude can perform before responding. A larger thinking token budget provides: * More space to explore multiple solution approaches step-by-step * Room to analyze edge cases and evaluate tradeoffs thoroughly * Ability to revise reasoning and self-correct mistakes Token budgets for thinking mode: * When thinking is **enabled**, Claude can use up to **31,999 tokens** from your output budget for internal reasoning * When thinking is **disabled** (via toggle or `/config`), Claude uses **0 tokens** for thinking **Limit the thinking budget:** * Use the [`MAX_THINKING_TOKENS` environment variable](/en/settings#environment-variables) to cap the thinking budget * When set, this value limits the maximum tokens Claude can use for thinking * See the [extended thinking documentation](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for valid token ranges You're charged for all thinking tokens used, even though Claude 4 models show summarized thinking *** ## Resume previous conversations When starting Claude Code, you can resume a previous session: * `claude --continue` continues the most recent conversation in the current directory * `claude --resume` opens a conversation picker or resumes by name * `claude --from-pr 123` resumes sessions linked to a specific pull request From inside an active session, use `/resume` to switch to a different conversation. Sessions are stored per project directory. The `/resume` picker shows sessions from the same git repository, including worktrees. ### Name your sessions Give sessions descriptive names to find them later. This is a best practice when working on multiple tasks or features. Use `/rename` during a session to give it a memorable name: ``` > /rename auth-refactor ``` You can also rename any session from the picker: run `/resume`, navigate to a session, and press `R`. From the command line: ```bash theme={null} claude --resume auth-refactor ``` Or from inside an active session: ``` > /resume auth-refactor ``` ### Use the session picker The `/resume` command (or `claude --resume` without arguments) opens an interactive session picker with these features: **Keyboard shortcuts in the picker:** | Shortcut | Action | | :-------- | :------------------------------------------------ | | `↑` / `↓` | Navigate between sessions | | `→` / `←` | Expand or collapse grouped sessions | | `Enter` | Select and resume the highlighted session | | `P` | Preview the session content | | `R` | Rename the highlighted session | | `/` | Search to filter sessions | | `A` | Toggle between current directory and all projects | | `B` | Filter to sessions from your current git branch | | `Esc` | Exit the picker or search mode | **Session organization:** The picker displays sessions with helpful metadata: * Session name or initial prompt * Time elapsed since last activity * Message count * Git branch (if applicable) Forked sessions (created with `/rewind` or `--fork-session`) are grouped together under their root session, making it easier to find related conversations. Tips: * **Name sessions early**: Use `/rename` when starting work on a distinct task—it's much easier to find "payment-integration" than "explain this function" later * Use `--continue` for quick access to your most recent conversation in the current directory * Use `--resume session-name` when you know which session you need * Use `--resume` (without a name) when you need to browse and select * For scripts, use `claude --continue --print "prompt"` to resume in non-interactive mode * Press `P` in the picker to preview a session before resuming it * The resumed conversation starts with the same model and configuration as the original How it works: 1. **Conversation Storage**: All conversations are automatically saved locally with their full message history 2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context 3. **Tool State**: Tool usage and results from the previous conversation are preserved 4. **Context Restoration**: The conversation resumes with all previous context intact *** ## Run parallel Claude Code sessions with Git worktrees Suppose you need to work on multiple tasks simultaneously with complete code isolation between Claude Code instances. Git worktrees allow you to check out multiple branches from the same repository into separate directories. Each worktree has its own working directory with isolated files, while sharing the same Git history. Learn more in the [official Git worktree documentation](https://git-scm.com/docs/git-worktree). ```bash theme={null} # Create a new worktree with a new branch git worktree add ../project-feature-a -b feature-a # Or create a worktree with an existing branch git worktree add ../project-bugfix bugfix-123 ``` This creates a new directory with a separate working copy of your repository. ```bash theme={null} # Navigate to your worktree cd ../project-feature-a # Run Claude Code in this isolated environment claude ``` ```bash theme={null} cd ../project-bugfix claude ``` ```bash theme={null} # List all worktrees git worktree list # Remove a worktree when done git worktree remove ../project-feature-a ``` Tips: * Each worktree has its own independent file state, making it perfect for parallel Claude Code sessions * Changes made in one worktree won't affect others, preventing Claude instances from interfering with each other * All worktrees share the same Git history and remote connections * For long-running tasks, you can have Claude working in one worktree while you continue development in another * Use descriptive directory names to easily identify which task each worktree is for * Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include: * JavaScript projects: Running dependency installation (`npm install`, `yarn`) * Python projects: Setting up virtual environments or installing with package managers * Other languages: Following your project's standard setup process *** ## Use Claude as a unix-style utility ### Add Claude to your verification process Suppose you want to use Claude Code as a linter or code reviewer. **Add Claude to your build script:** ```json theme={null} // package.json { ... "scripts": { ... "lint:claude": "claude -p 'you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.'" } } ``` Tips: * Use Claude for automated code review in your CI/CD pipeline * Customize the prompt to check for specific issues relevant to your project * Consider creating multiple scripts for different types of verification ### Pipe in, pipe out Suppose you want to pipe data into Claude, and get back data in a structured format. **Pipe data through Claude:** ```bash theme={null} cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt ``` Tips: * Use pipes to integrate Claude into existing shell scripts * Combine with other Unix tools for powerful workflows * Consider using --output-format for structured output ### Control output format Suppose you need Claude's output in a specific format, especially when integrating Claude Code into scripts or other tools. ```bash theme={null} cat data.txt | claude -p 'summarize this data' --output-format text > summary.txt ``` This outputs just Claude's plain text response (default behavior). ```bash theme={null} cat code.py | claude -p 'analyze this code for bugs' --output-format json > analysis.json ``` This outputs a JSON array of messages with metadata including cost and duration. ```bash theme={null} cat log.txt | claude -p 'parse this log file for errors' --output-format stream-json ``` This outputs a series of JSON objects in real-time as Claude processes the request. Each message is a valid JSON object, but the entire output is not valid JSON if concatenated. Tips: * Use `--output-format text` for simple integrations where you just need Claude's response * Use `--output-format json` when you need the full conversation log * Use `--output-format stream-json` for real-time output of each conversation turn *** ## Ask Claude about its capabilities Claude has built-in access to its documentation and can answer questions about its own features and limitations. ### Example questions ``` > can Claude Code create pull requests? ``` ``` > how does Claude Code handle permissions? ``` ``` > what skills are available? ``` ``` > how do I use MCP with Claude Code? ``` ``` > how do I configure Claude Code for Amazon Bedrock? ``` ``` > what are the limitations of Claude Code? ``` Claude provides documentation-based answers to these questions. For executable examples and hands-on demonstrations, refer to the specific workflow sections above. Tips: * Claude always has access to the latest Claude Code documentation, regardless of the version you're using * Ask specific questions to get detailed answers * Claude can explain complex features like MCP integration, enterprise configurations, and advanced workflows *** ## Next steps Patterns for getting the most out of Claude Code Understand the agentic loop and context management Add skills, hooks, MCP, subagents, and plugins Clone our development container reference implementation --- # Source: https://code.claude.com/docs/en/costs.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Manage costs effectively > Track token usage, set team spend limits, and reduce Claude Code costs with context management, model selection, extended thinking settings, and preprocessing hooks. Claude Code consumes tokens for each interaction. Costs vary based on codebase size, query complexity, and conversation length. The average cost is \$6 per developer per day, with daily costs remaining below \$12 for 90% of users. For team usage, Claude Code charges by API token consumption. On average, Claude Code costs \~\$100-200/developer per month with Sonnet 4.5 though there is large variance depending on how many instances users are running and whether they're using it in automation. This page covers how to [track your costs](#track-your-costs), [manage costs for teams](#managing-costs-for-teams), and [reduce token usage](#reduce-token-usage). ## Track your costs ### Using the `/cost` command The `/cost` command shows API token usage and is intended for API users. Claude Max and Pro subscribers have usage included in their subscription, so `/cost` data isn't relevant for billing purposes. Subscribers can use `/stats` to view usage patterns. The `/cost` command provides detailed token usage statistics for your current session: ``` Total cost: $0.55 Total duration (API): 6m 19.7s Total duration (wall): 6h 33m 10.2s Total code changes: 0 lines added, 0 lines removed ``` ## Managing costs for teams When using Claude API, you can [set workspace spend limits](https://platform.claude.com/docs/en/build-with-claude/workspaces#workspace-limits) on the total Claude Code workspace spend. Admins can [view cost and usage reporting](https://platform.claude.com/docs/en/build-with-claude/workspaces#usage-and-cost-tracking) in the Console. When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization. You cannot create API keys for this workspace; it is exclusively for Claude Code authentication and usage. On Bedrock, Vertex, and Foundry, Claude Code does not send metrics from your cloud. To get cost metrics, several large enterprises reported using [LiteLLM](/en/llm-gateway#litellm-configuration), which is an open-source tool that helps companies [track spend by key](https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend). This project is unaffiliated with Anthropic and we have not audited its security. ### Rate limit recommendations When setting up Claude Code for teams, consider these Token Per Minute (TPM) and Request Per Minute (RPM) per-user recommendations based on your organization size: | Team size | TPM per user | RPM per user | | ------------- | ------------ | ------------ | | 1-5 users | 200k-300k | 5-7 | | 5-20 users | 100k-150k | 2.5-3.5 | | 20-50 users | 50k-75k | 1.25-1.75 | | 50-100 users | 25k-35k | 0.62-0.87 | | 100-500 users | 15k-20k | 0.37-0.47 | | 500+ users | 10k-15k | 0.25-0.35 | For example, if you have 200 users, you might request 20k TPM for each user, or 4 million total TPM (200\*20,000 = 4 million). The TPM per user decreases as team size grows because we expect fewer users to use Claude Code concurrently in larger organizations. These rate limits apply at the organization level, not per individual user, which means individual users can temporarily consume more than their calculated share when others aren't actively using the service. If you anticipate scenarios with unusually high concurrent usage (such as live training sessions with large groups), you may need higher TPM allocations per user. ## Reduce token usage Token costs scale with context size: the more context Claude processes, the more tokens you use. Claude Code automatically optimizes costs through prompt caching (which reduces costs for repeated content like system prompts) and auto-compaction (which summarizes conversation history when approaching context limits). The following strategies help you keep context small and reduce per-message costs. ### Manage context proactively Use `/cost` to check your current token usage, or [configure your status line](/en/statusline#context-window-usage) to display it continuously. * **Clear between tasks**: Use `/clear` to start fresh when switching to unrelated work. Stale context wastes tokens on every subsequent message. Use `/rename` before clearing so you can easily find the session later, then `/resume` to return to it. * **Add custom compaction instructions**: `/compact Focus on code samples and API usage` tells Claude what to preserve during summarization. You can also customize compaction behavior in your CLAUDE.md: ```markdown theme={null} # Compact instructions When you are using compact, please focus on test output and code changes ``` ### Choose the right model Sonnet handles most coding tasks well and costs less than Opus. Reserve Opus for complex architectural decisions or multi-step reasoning. Use `/model` to switch models mid-session, or set a default in `/config`. For simple subagent tasks, specify `model: haiku` in your [subagent configuration](/en/sub-agents#choose-a-model). ### Reduce MCP server overhead Each MCP server adds tool definitions to your context, even when idle. Run `/context` to see what's consuming space. * **Prefer CLI tools when available**: Tools like `gh`, `aws`, `gcloud`, and `sentry-cli` are more context-efficient than MCP servers because they don't add persistent tool definitions. Claude can run CLI commands directly without the overhead. * **Disable unused servers**: Run `/mcp` to see configured servers and disable any you're not actively using. * **Tool search is automatic**: When MCP tool descriptions exceed 10% of your context window, Claude Code automatically defers them and loads tools on-demand via [tool search](/en/mcp#scale-with-mcp-tool-search). Since deferred tools only enter context when actually used, a lower threshold means fewer idle tool definitions consuming space. Set a lower threshold with `ENABLE_TOOL_SEARCH=auto:` (for example, `auto:5` triggers when tools exceed 5% of your context window). ### Install code intelligence plugins for typed languages [Code intelligence plugins](/en/discover-plugins#code-intelligence) give Claude precise symbol navigation instead of text-based search, reducing unnecessary file reads when exploring unfamiliar code. A single "go to definition" call replaces what might otherwise be a grep followed by reading multiple candidate files. Installed language servers also report type errors automatically after edits, so Claude catches mistakes without running a compiler. ### Offload processing to hooks and skills Custom [hooks](/en/hooks) can preprocess data before Claude sees it. Instead of Claude reading a 10,000-line log file to find errors, a hook can grep for `ERROR` and return only matching lines, reducing context from tens of thousands of tokens to hundreds. A [skill](/en/skills) can give Claude domain knowledge so it doesn't have to explore. For example, a "codebase-overview" skill could describe your project's architecture, key directories, and naming conventions. When Claude invokes the skill, it gets this context immediately instead of spending tokens reading multiple files to understand the structure. For example, this PreToolUse hook filters test output to show only failures: Add this to your [settings.json](/en/settings#settings-files) to run the hook before every Bash command: ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "~/.claude/hooks/filter-test-output.sh" } ] } ] } } ``` The hook calls this script, which checks if the command is a test runner and modifies it to show only failures: ```bash theme={null} #!/bin/bash input=$(cat) cmd=$(echo "$input" | jq -r '.tool_input.command') # If running tests, filter to show only failures if [[ "$cmd" =~ ^(npm test|pytest|go test) ]]; then filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:)' | head -100" echo "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{\"command\":\"$filtered_cmd\"}}}" else echo "{}" fi ``` ### Move instructions from CLAUDE.md to skills Your [CLAUDE.md](/en/memory) file is loaded into context at session start. If it contains detailed instructions for specific workflows (like PR reviews or database migrations), those tokens are present even when you're doing unrelated work. [Skills](/en/skills) load on-demand only when invoked, so moving specialized instructions into skills keeps your base context smaller. Aim to keep CLAUDE.md under \~500 lines by including only essentials. ### Adjust extended thinking Extended thinking is enabled by default with a budget of 31,999 tokens because it significantly improves performance on complex planning and reasoning tasks. However, thinking tokens are billed as output tokens, so for simpler tasks where deep reasoning isn't needed, you can reduce costs by disabling it in `/config` or lowering the budget (for example, `MAX_THINKING_TOKENS=8000`). ### Delegate verbose operations to subagents Running tests, fetching documentation, or processing log files can consume significant context. Delegate these to [subagents](/en/sub-agents#isolate-high-volume-operations) so the verbose output stays in the subagent's context while only a summary returns to your main conversation. ### Write specific prompts Vague requests like "improve this codebase" trigger broad scanning. Specific requests like "add input validation to the login function in auth.ts" let Claude work efficiently with minimal file reads. ### Work efficiently on complex tasks For longer or more complex work, these habits help avoid wasted tokens from going down the wrong path: * **Use plan mode for complex tasks**: Press Shift+Tab to enter [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) before implementation. Claude explores the codebase and proposes an approach for your approval, preventing expensive re-work when the initial direction is wrong. * **Course-correct early**: If Claude starts heading the wrong direction, press Escape to stop immediately. Use `/rewind` or double-tap Escape to restore conversation and code to a previous checkpoint. * **Give verification targets**: Include test cases, paste screenshots, or define expected output in your prompt. When Claude can verify its own work, it catches issues before you need to request fixes. * **Test incrementally**: Write one file, test it, then continue. This catches issues early when they're cheap to fix. ## Background token usage Claude Code uses tokens for some background functionality even when idle: * **Conversation summarization**: Background jobs that summarize previous conversations for the `claude --resume` feature * **Command processing**: Some commands like `/cost` may generate requests to check status These background processes consume a small amount of tokens (typically under \$0.04 per session) even without active interaction. ## Understanding changes in Claude Code behavior Claude Code regularly receives updates that may change how features work, including cost reporting. Run `claude --version` to check your current version. For specific billing questions, contact Anthropic support through your [Console account](https://platform.claude.com/login). For team deployments, start with a small pilot group to establish usage patterns before wider rollout. --- # Source: https://code.claude.com/docs/en/data-usage.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Data usage > Learn about Anthropic's data usage policies for Claude ## Data policies ### Data training policy **Consumer users (Free, Pro, and Max plans)**: We give you the choice to allow your data to be used to improve future Claude models. We will train new models using data from Free, Pro, and Max accounts when this setting is on (including when you use Claude Code from these accounts). **Commercial users**: (Team and Enterprise plans, API, 3rd-party platforms, and Claude Gov) maintain existing policies: Anthropic does not train generative models using code or prompts sent to Claude Code under commercial terms, unless the customer has chosen to provide their data to us for model improvement (for example, the [Developer Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program)). ### Development Partner Program If you explicitly opt in to methods to provide us with materials to train on, such as via the [Development Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program), we may use those materials provided to train our models. An organization admin can expressly opt-in to the Development Partner Program for their organization. Note that this program is available only for Anthropic first-party API, and not for Bedrock or Vertex users. ### Feedback using the `/bug` command If you choose to send us feedback about Claude Code using the `/bug` command, we may use your feedback to improve our products and services. Transcripts shared via `/bug` are retained for 5 years. ### Session quality surveys When you see the "How is Claude doing this session?" prompt in Claude Code, responding to this survey (including selecting "Dismiss"), only your numeric rating (1, 2, 3, or dismiss) is recorded. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of this survey. Unlike thumbs up/down feedback or `/bug` reports, this session quality survey is a simple product satisfaction metric. Your responses to this survey do not impact your data training preferences and cannot be used to train our AI models. To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also automatically disabled when using third-party providers (Bedrock, Vertex, Foundry) or when telemetry is disabled. ### Data retention Anthropic retains Claude Code data based on your account type and preferences. **Consumer users (Free, Pro, and Max plans)**: * Users who allow data use for model improvement: 5-year retention period to support model development and safety improvements * Users who don't allow data use for model improvement: 30-day retention period * Privacy settings can be changed at any time at [claude.ai/settings/data-privacy-controls](https://claude.ai/settings/data-privacy-controls). **Commercial users (Team, Enterprise, and API)**: * Standard: 30-day retention period * Zero data retention: Available with appropriately configured API keys - Claude Code will not retain chat transcripts on servers * Local caching: Claude Code clients may store sessions locally for up to 30 days to enable session resumption (configurable) Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/). For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy). ## Data access For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in. ## Local Claude Code: Data flow and dependencies The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows. Diagram showing Claude Code's external connections: install/update connects to NPM, and user requests connect to Anthropic services including Console auth, public-api, and optionally Statsig, Sentry, and bug reporting Claude Code is installed from [NPM](https://www.npmjs.com/package/@anthropic-ai/claude-code). Claude Code runs locally. In order to interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs. The data is encrypted in transit via TLS and is not encrypted at rest. Claude Code is compatible with most popular VPNs and LLM proxies. Claude Code is built on Anthropic's APIs. For details regarding our API's security controls, including our API logging procedures, please refer to compliance artifacts offered in the [Anthropic Trust Center](https://trust.anthropic.com). ### Cloud execution: Data flow and dependencies When using [Claude Code on the web](/en/claude-code-on-the-web), sessions run in Anthropic-managed virtual machines instead of locally. In cloud environments: * **Code and data storage:** Your repository is cloned to an isolated VM. Code and session data are subject to the retention and usage policies for your account type (see Data retention section above) * **Credentials:** GitHub authentication is handled through a secure proxy; your GitHub credentials never enter the sandbox * **Network traffic:** All outbound traffic goes through a security proxy for audit logging and abuse prevention * **Session data:** Prompts, code changes, and outputs follow the same data policies as local Claude Code usage For security details about cloud execution, see [Security](/en/security#cloud-execution-security). ## Telemetry services Claude Code connects from users' machines to the Statsig service to log operational metrics such as latency, reliability, and usage patterns. This logging does not include any code or file paths. Data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Statsig security documentation](https://www.statsig.com/trust/security). To opt out of Statsig telemetry, set the `DISABLE_TELEMETRY` environment variable. Claude Code connects from users' machines to Sentry for operational error logging. The data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Sentry security documentation](https://sentry.io/security/). To opt out of error logging, set the `DISABLE_ERROR_REPORTING` environment variable. When users run the `/bug` command, a copy of their full conversation history including code is sent to Anthropic. The data is encrypted in transit and at rest. Optionally, a Github issue is created in our public repository. To opt out of bug reporting, set the `DISABLE_BUG_COMMAND` environment variable. ## Default behaviors by API provider By default, we disable all non-essential traffic (including error reporting, telemetry, bug reporting functionality, and session quality surveys) when using Bedrock, Vertex, or Foundry. You can also opt out of all of these at once by setting the `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` environment variable. Here are the full default behaviors: | Service | Claude API | Vertex API | Bedrock API | Foundry API | | ------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------ | | **Statsig (Metrics)** | Default on.
`DISABLE_TELEMETRY=1` to disable. | Default off.
`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.
`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.
`CLAUDE_CODE_USE_FOUNDRY` must be 1. | | **Sentry (Errors)** | Default on.
`DISABLE_ERROR_REPORTING=1` to disable. | Default off.
`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.
`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.
`CLAUDE_CODE_USE_FOUNDRY` must be 1. | | **Claude API (`/bug` reports)** | Default on.
`DISABLE_BUG_COMMAND=1` to disable. | Default off.
`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.
`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.
`CLAUDE_CODE_USE_FOUNDRY` must be 1. | | **Session quality surveys** | Default on.
`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default off.
`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.
`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.
`CLAUDE_CODE_USE_FOUNDRY` must be 1. | All environment variables can be checked into `settings.json` ([read more](/en/settings)). --- # Source: https://code.claude.com/docs/en/desktop.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code on desktop > Run Claude Code tasks locally or on secure cloud infrastructure with the Claude desktop app Claude Code on desktop is currently in preview. Claude Code is an AI coding assistant that works directly with your codebase. Unlike Claude.ai chat, it can read your project files, edit code, run terminal commands, and understand how different parts of your code connect. You watch changes happen in real time. You can use Claude Code through the terminal ([CLI](/en/quickstart)) or through the desktop app described here. Both provide the same core capabilities. The desktop app adds a graphical interface and visual session management. Start here to install and make your first edit See what's shared and what's different The desktop app has three tabs: * **Chat**: A conversational interface for general questions and tasks (like Claude.ai) * **Cowork**: An autonomous agent that works on tasks in the background * **Code**: An AI coding assistant that reads and edits your project files directly This documentation covers the **Code** tab. For the chat interface, see the [Claude Desktop support articles](https://support.claude.com/en/collections/16163169-claude-desktop). ## Installation and setup Download Claude for your platform. You'll need an Anthropic account ([sign up at claude.ai](https://claude.ai) if you don't have one). Universal build for Intel and Apple Silicon For x64 processors For Windows ARM64, [download here](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs). Local sessions are not available on ARM64 devices, so use remote sessions instead. Linux is not currently supported. Launch Claude from your Applications folder (macOS) or Start menu (Windows). Sign in with your Anthropic account. Click the **Code** tab in the top left. If clicking Code prompts you to sign in online, complete the sign-in and restart the app. ## Getting started If you already use the CLI, you can skip to [How Desktop relates to CLI](#how-desktop-relates-to-cli) for a quick overview of differences. Select **Local** to run Claude on your machine using your files directly. This is the best choice for getting started. Click **Select folder** and choose your project directory. You can also run [remote sessions](/en/claude-code-on-the-web) that continue in the cloud even if you close the app. Type what you want Claude to do: * "Find a TODO comment and fix it" * "Add tests for the main function" * "Create a CLAUDE.md with instructions for this codebase" A **session** is a conversation with Claude about your code. Each session tracks its own context and changes, so you can work on multiple tasks without them interfering with each other. By default, Code is in **Ask** mode, where Claude proposes changes and waits for your approval before applying them. You'll see: 1. **A diff view** showing exactly what will change in each file 2. **Accept/Reject buttons** to approve or decline each change 3. **Real-time updates** as Claude works through your request If you reject a change, Claude will ask how you'd like to proceed differently. Your files aren't modified until you accept. The sections below cover commands, permission modes, parallel sessions, and ways to extend Claude Code with custom workflows and integrations. ## What you can do Claude Code can edit files, run terminal commands, and understand how your code connects. Try prompts like: * `Fix the bug in the login function` * `Run the tests and fix any failures` * `How does the authentication flow work?` You can rename, resume, and archive sessions through the sidebar. ### Choose a permission mode Control how Claude works using the mode selector next to the send button: * **Ask** (recommended for new users): Claude asks for your approval before each file edit or command. You see a diff view and can accept or reject each change. * **Code**: Claude auto-accepts file edits but still asks before running terminal commands. Use this when you trust file changes and want faster iteration. * **Plan**: Claude creates a detailed plan for your approval before making any changes. Good for complex tasks where you want to review the approach first. To stop Claude mid-task, click the stop button. Remote sessions only support **Code** and **Plan** modes because they continue running in the background without requiring your active participation. See [permission modes](/en/permissions#permission-modes) for details on how these work internally. ### Work in parallel with sessions Click **+ New session** in the sidebar to work on multiple tasks in parallel. For Git repositories, each session gets its own isolated copy of your project using worktrees, so changes in one session don't affect another until you commit them. Worktrees are stored in `~/.claude-worktrees/` by default. Session isolation requires [Git](https://git-scm.com/downloads). Without Git, sessions in the same directory edit the same files, so changes in one session are immediately visible in others. To include files listed in your `.gitignore` (like `.env`) in new worktrees, create a `.worktreeinclude` file in your project root listing the file patterns to copy. To manage a session, click its dropdown in the sidebar to rename it, archive it, or check context usage. When context fills up, Claude automatically summarizes the conversation. You can also ask Claude to compact if you want to free up space earlier. ### Run long-running tasks remotely For large refactors, test suites, migrations, or other long-running tasks, select **Remote** instead of **Local** when starting a session. Remote sessions run on Anthropic's cloud infrastructure and continue even if you close the app or shut down your computer. Check back anytime to see progress or steer Claude in a different direction. Remote sessions support **Code** and **Plan** modes. See [Claude Code on the web](/en/claude-code-on-the-web) for details on configuring remote environments. ### Review changes with diff view After Claude makes changes to your code, the diff view lets you review modifications file by file before creating a pull request. When Claude changes files, a diff stats indicator appears showing the number of lines added and removed (for example, `+12 -1`). Click this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right. To comment on specific lines, click any line in the diff to open a comment box. Type your feedback and press **Enter** to send. In the full diff view, press **Enter** to accept each comment, then **Cmd+Enter** to send them all. Claude reads your comments and makes the requested changes, which appear as a new diff you can review. ## Extend Claude Code You can extend Claude Code with custom commands, automated workflows, and external integrations. ### Connect external tools For local sessions, click the **...** button before starting and select **Connectors** to add integrations like Google Calendar, Slack, GitHub, Linear, Notion, and more. Connectors must be configured before the session starts and are only available for local sessions. Once connected, Claude can read your calendar, send messages, create issues, and interact with your tools directly. You can ask Claude what connectors are configured in your session. Connectors are [MCP (Model Context Protocol) servers](/en/mcp) with built-in setup. You can also [create custom connectors](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp) or add MCP servers manually via [configuration files](/en/mcp#configure-mcp-servers). ### Create custom skills [Skills](/en/skills) are reusable prompts that extend Claude's capabilities. For example, you could create a `review` skill that runs your standard code review checklist, or a `deploy` skill that walks through your deployment steps. Skills are defined as markdown files in `.claude/skills/` and can include instructions, context, and even call other tools. Ask Claude what skills are available or to run a specific skill. Claude can also help you create a skill if you describe what you want, or see [skills](/en/skills) to learn how to write them yourself. ### Automate workflows with hooks [Hooks](/en/hooks) run shell commands automatically in response to Claude Code events. For example, you could run a linter after every file edit, auto-format code, or send notifications when tasks complete. Hooks are configured in your [settings files](/en/settings). See [hooks](/en/hooks) for available events and configuration examples. ## Environment configuration When starting a session, you choose between **Local** (runs on your machine) or **Remote** (runs on Anthropic's cloud). **Local sessions** inherit environment variables from your shell. If you need additional variables, set them in your shell profile (`~/.zshrc`, `~/.bashrc`) and restart the desktop app. See [environment variables](/en/settings#environment-variables) for the full list of supported variables. [Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. The thinking process runs in the background but isn't displayed in the Desktop interface. To disable it or adjust the budget, set `MAX_THINKING_TOKENS` in your shell profile (use `0` to disable). **Remote sessions** run on Anthropic's cloud infrastructure and continue even if you close the app. Usage counts toward your subscription plan limits with no separate compute charges. See [Claude Code on the web](/en/claude-code-on-the-web) for details on configuring remote environments. ## How Desktop relates to CLI If you already use the Claude Code CLI, Desktop runs the same underlying engine with a graphical interface. You can run both simultaneously on the same machine, even on the same project. Each maintains separate session history, but they share configuration and project memory (CLAUDE.md files). ### CLI flag equivalents If you're used to CLI flags, the table below shows the Desktop equivalent for each. Some flags have no Desktop equivalent because they're designed for scripting or automation. | CLI | Desktop equivalent | | ------------------------------------- | ---------------------------------------------- | | `--model sonnet` | **...** menu > Model (before starting session) | | `--resume`, `--continue` | Click a session in the sidebar | | `--allowedTools`, `--disallowedTools` | Not available in Desktop | | `--dangerously-skip-permissions` | Not available in Desktop | | `--print` | Not available (Desktop is interactive) | ### Shared configuration Desktop and CLI read the same configuration files, so your setup carries over: * **[CLAUDE.md](/en/memory)** and **CLAUDE.local.md** files in your project are used by both * **[MCP servers](/en/mcp)** configured in `~/.claude.json` or `.mcp.json` work in both * **[Hooks](/en/hooks)** and **[skills](/en/skills)** defined in settings apply to both * **[Settings](/en/settings)** in `~/.claude.json` and `~/.claude/settings.json` are shared * **Models** (Sonnet, Opus, Haiku) are available in both (Desktop requires selecting before starting a session) MCP servers configured for the **Claude Desktop chat app** (in `claude_desktop_config.json`) are separate from Claude Code. To use MCP servers in Claude Code, configure them in `~/.claude.json` or your project's `.mcp.json` file. See [MCP configuration](/en/mcp#configure-mcp-servers) for details. ### What's different **Desktop adds:** * Graphical interface with visual session management * Built-in connectors for common integrations * Automatic session isolation for Git repositories (each session gets its own worktree) **CLI adds:** * [Third-party API providers](/en/third-party-integrations) (Bedrock, Vertex, Foundry). If you use these, continue using CLI for those projects. * [CLI flags](/en/cli-reference) for scripting (`--print`, `--resume`, `--continue`) * [Programmatic usage](/en/headless) via the Agent SDK ## Troubleshooting Solutions to common issues with the Claude desktop app. For CLI issues, see [CLI troubleshooting](/en/troubleshooting). ### Check your version To see which version of the desktop app you're running: * **macOS**: Click **Claude** in the menu bar, then **About Claude** * **Windows**: Click **Help**, then **About** Click the version number to copy it to your clipboard. ### "Branch doesn't exist yet" when opening in CLI Remote sessions can create branches that don't exist on your local machine. Click the branch name in the session toolbar to copy it, then fetch it locally: ```bash theme={null} git fetch origin git checkout ``` ### "Failed to load session" error This error can occur for several reasons: * The selected folder no longer exists or is inaccessible * A Git repository requires Git LFS but it's not installed (see [Git LFS errors](#git-lfs-errors)) * File permissions prevent access to the project directory Try selecting a different folder or restarting the desktop app. ### App won't quit If the desktop app doesn't close properly: * **macOS**: Press Cmd+Q. If the app doesn't respond, use Force Quit (Cmd+Option+Esc, select Claude, click Force Quit). * **Windows**: Use Task Manager (Ctrl+Shift+Esc) to end the Claude process. ### Windows installation issues If the installer fails silently or doesn't complete properly: 1. **PATH not updated**: After installation, open a new terminal window. The PATH updates only apply to new terminal sessions. 2. **Concurrent installation error**: If you see an error about another installation in progress but there isn't one, try running the installer as Administrator. ### Session not finding installed tools If Claude can't find tools like `npm`, `node`, or other CLI commands: 1. Verify the tools work in your regular terminal 2. Check that your shell profile (`~/.zshrc`, `~/.bashrc`) properly sets up PATH 3. Restart the desktop app to reload environment variables ### MCP servers not working (Windows) If MCP server toggles don't respond or servers fail to connect on Windows: 1. Check that the MCP server is properly configured in your settings 2. Restart the desktop app after making changes 3. Verify the MCP server process is running (check Task Manager) 4. Review the server logs for connection errors ### Git LFS errors If you see "Git LFS is required by this repository but is not installed," your repository uses Git Large File Storage for large binary files. Install Git LFS before opening this repository: 1. Install Git LFS from [git-lfs.com](https://git-lfs.com/) 2. Run `git lfs install` in your terminal 3. Restart the desktop app ## Enterprise configuration Organizations can disable local Claude Code use in the desktop application with the `isClaudeCodeForDesktopEnabled` [enterprise policy option](https://support.claude.com/en/articles/12622667-enterprise-configuration#h_003283c7cb). Additionally, Claude Code on the web can be disabled in your [admin settings](https://claude.ai/admin-settings/claude-code). ## Related resources * [Claude Code on the web](/en/claude-code-on-the-web): Run remote sessions that continue in the cloud * [CLI reference](/en/cli-reference): Use Claude Code in your terminal with flags and scripting * [Common workflows](/en/common-workflows): Tutorials for debugging, refactoring, testing, and more * [Settings reference](/en/settings): Configure Claude Code behavior with settings files * [Claude Desktop support](https://support.claude.com/en/collections/16163169-claude-desktop): Help articles for the Chat tab and general desktop app usage * [Enterprise configuration](https://support.claude.com/en/articles/12622667-enterprise-configuration): Admin policies for organizational deployments --- # Source: https://code.claude.com/docs/en/devcontainer.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Development containers > Learn about the Claude Code development container for teams that need consistent, secure environments. The reference [devcontainer setup](https://github.com/anthropics/claude-code/tree/main/.devcontainer) and associated [Dockerfile](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) offer a preconfigured development container that you can use as is, or customize for your needs. This devcontainer works with the Visual Studio Code [Dev Containers extension](https://code.visualstudio.com/docs/devcontainers/containers) and similar tools. The container's enhanced security measures (isolation and firewall rules) allow you to run `claude --dangerously-skip-permissions` to bypass permission prompts for unattended operation. While the devcontainer provides substantial protections, no system is completely immune to all attacks. When executed with `--dangerously-skip-permissions`, devcontainers don't prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials. We recommend only using devcontainers when developing with trusted repositories. Always maintain good security practices and monitor Claude's activities. ## Key features * **Production-ready Node.js**: Built on Node.js 20 with essential development dependencies * **Security by design**: Custom firewall restricting network access to only necessary services * **Developer-friendly tools**: Includes git, ZSH with productivity enhancements, fzf, and more * **Seamless VS Code integration**: Pre-configured extensions and optimized settings * **Session persistence**: Preserves command history and configurations between container restarts * **Works everywhere**: Compatible with macOS, Windows, and Linux development environments ## Getting started in 4 steps 1. Install VS Code and the Remote - Containers extension 2. Clone the [Claude Code reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository 3. Open the repository in VS Code 4. When prompted, click "Reopen in Container" (or use Command Palette: Cmd+Shift+P → "Remote-Containers: Reopen in Container") ## Configuration breakdown The devcontainer setup consists of three primary components: * [**devcontainer.json**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json): Controls container settings, extensions, and volume mounts * [**Dockerfile**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile): Defines the container image and installed tools * [**init-firewall.sh**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh): Establishes network security rules ## Security features The container implements a multi-layered security approach with its firewall configuration: * **Precise access control**: Restricts outbound connections to whitelisted domains only (npm registry, GitHub, Claude API, etc.) * **Allowed outbound connections**: The firewall permits outbound DNS and SSH connections * **Default-deny policy**: Blocks all other external network access * **Startup verification**: Validates firewall rules when the container initializes * **Isolation**: Creates a secure development environment separated from your main system ## Customization options The devcontainer configuration is designed to be adaptable to your needs: * Add or remove VS Code extensions based on your workflow * Modify resource allocations for different hardware environments * Adjust network access permissions * Customize shell configurations and developer tooling ## Example use cases ### Secure client work Use devcontainers to isolate different client projects, ensuring code and credentials never mix between environments. ### Team onboarding New team members can get a fully configured development environment in minutes, with all necessary tools and settings pre-installed. ### Consistent CI/CD environments Mirror your devcontainer configuration in CI/CD pipelines to ensure development and production environments match. ## Related resources * [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers) * [Claude Code security best practices](/en/security) * [Enterprise network configuration](/en/network-config) --- # Source: https://code.claude.com/docs/en/discover-plugins.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Discover and install prebuilt plugins through marketplaces > Find and install plugins from marketplaces to extend Claude Code with new commands, agents, and capabilities. Plugins extend Claude Code with skills, agents, hooks, and MCP servers. Plugin marketplaces are catalogs that help you discover and install these extensions without building them yourself. Looking to create and distribute your own marketplace? See [Create and distribute a plugin marketplace](/en/plugin-marketplaces). ## How marketplaces work A marketplace is a catalog of plugins that someone else has created and shared. Using a marketplace is a two-step process: This registers the catalog with Claude Code so you can browse what's available. No plugins are installed yet. Browse the catalog and install the plugins you want. Think of it like adding an app store: adding the store gives you access to browse its collection, but you still choose which apps to download individually. ## Official Anthropic marketplace The official Anthropic marketplace (`claude-plugins-official`) is automatically available when you start Claude Code. Run `/plugin` and go to the **Discover** tab to browse what's available. To install a plugin from the official marketplace: ```shell theme={null} /plugin install plugin-name@claude-plugins-official ``` The official marketplace is maintained by Anthropic. To distribute your own plugins, [create your own marketplace](/en/plugin-marketplaces) and share it with users. The official marketplace includes several categories of plugins: ### Code intelligence Code intelligence plugins enable Claude Code's built-in LSP tool, giving Claude the ability to jump to definitions, find references, and see type errors immediately after edits. These plugins configure [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) connections, the same technology that powers VS Code's code intelligence. These plugins require the language server binary to be installed on your system. If you already have a language server installed, Claude may prompt you to install the corresponding plugin when you open a project. | Language | Plugin | Binary required | | :--------- | :------------------ | :--------------------------- | | C/C++ | `clangd-lsp` | `clangd` | | C# | `csharp-lsp` | `csharp-ls` | | Go | `gopls-lsp` | `gopls` | | Java | `jdtls-lsp` | `jdtls` | | Kotlin | `kotlin-lsp` | `kotlin-language-server` | | Lua | `lua-lsp` | `lua-language-server` | | PHP | `php-lsp` | `intelephense` | | Python | `pyright-lsp` | `pyright-langserver` | | Rust | `rust-analyzer-lsp` | `rust-analyzer` | | Swift | `swift-lsp` | `sourcekit-lsp` | | TypeScript | `typescript-lsp` | `typescript-language-server` | You can also [create your own LSP plugin](/en/plugins-reference#lsp-servers) for other languages. If you see `Executable not found in $PATH` in the `/plugin` Errors tab after installing a plugin, install the required binary from the table above. #### What Claude gains from code intelligence plugins Once a code intelligence plugin is installed and its language server binary is available, Claude gains two capabilities: * **Automatic diagnostics**: after every file edit Claude makes, the language server analyzes the changes and reports errors and warnings back automatically. Claude sees type errors, missing imports, and syntax issues without needing to run a compiler or linter. If Claude introduces an error, it notices and fixes the issue in the same turn. This requires no configuration beyond installing the plugin. You can see diagnostics inline by pressing **Ctrl+O** when the "diagnostics found" indicator appears. * **Code navigation**: Claude can use the language server to jump to definitions, find references, get type info on hover, list symbols, find implementations, and trace call hierarchies. These operations give Claude more precise navigation than grep-based search, though availability may vary by language and environment. If you run into issues, see [Code intelligence troubleshooting](#code-intelligence-issues). ### External integrations These plugins bundle pre-configured [MCP servers](/en/mcp) so you can connect Claude to external services without manual setup: * **Source control**: `github`, `gitlab` * **Project management**: `atlassian` (Jira/Confluence), `asana`, `linear`, `notion` * **Design**: `figma` * **Infrastructure**: `vercel`, `firebase`, `supabase` * **Communication**: `slack` * **Monitoring**: `sentry` ### Development workflows Plugins that add commands and agents for common development tasks: * **commit-commands**: Git commit workflows including commit, push, and PR creation * **pr-review-toolkit**: Specialized agents for reviewing pull requests * **agent-sdk-dev**: Tools for building with the Claude Agent SDK * **plugin-dev**: Toolkit for creating your own plugins ### Output styles Customize how Claude responds: * **explanatory-output-style**: Educational insights about implementation choices * **learning-output-style**: Interactive learning mode for skill building ## Try it: add the demo marketplace Anthropic also maintains a [demo plugins marketplace](https://github.com/anthropics/claude-code/tree/main/plugins) (`claude-code-plugins`) with example plugins that show what's possible with the plugin system. Unlike the official marketplace, you need to add this one manually. From within Claude Code, run the `plugin marketplace add` command for the `anthropics/claude-code` marketplace: ```shell theme={null} /plugin marketplace add anthropics/claude-code ``` This downloads the marketplace catalog and makes its plugins available to you. Run `/plugin` to open the plugin manager. This opens a tabbed interface with four tabs you can cycle through using **Tab** (or **Shift+Tab** to go backward): * **Discover**: browse available plugins from all your marketplaces * **Installed**: view and manage your installed plugins * **Marketplaces**: add, remove, or update your added marketplaces * **Errors**: view any plugin loading errors Go to the **Discover** tab to see plugins from the marketplace you just added. Select a plugin to view its details, then choose an installation scope: * **User scope**: install for yourself across all projects * **Project scope**: install for all collaborators on this repository * **Local scope**: install for yourself in this repository only For example, select **commit-commands** (a plugin that adds git workflow commands) and install it to your user scope. You can also install directly from the command line: ```shell theme={null} /plugin install commit-commands@anthropics-claude-code ``` See [Configuration scopes](/en/settings#configuration-scopes) to learn more about scopes. After installing, the plugin's commands are immediately available. Plugin commands are namespaced by the plugin name, so **commit-commands** provides commands like `/commit-commands:commit`. Try it out by making a change to a file and running: ```shell theme={null} /commit-commands:commit ``` This stages your changes, generates a commit message, and creates the commit. Each plugin works differently. Check the plugin's description in the **Discover** tab or its homepage to learn what commands and capabilities it provides. The rest of this guide covers all the ways you can add marketplaces, install plugins, and manage your configuration. ## Add marketplaces Use the `/plugin marketplace add` command to add marketplaces from different sources. **Shortcuts**: You can use `/plugin market` instead of `/plugin marketplace`, and `rm` instead of `remove`. * **GitHub repositories**: `owner/repo` format (for example, `anthropics/claude-code`) * **Git URLs**: any git repository URL (GitLab, Bitbucket, self-hosted) * **Local paths**: directories or direct paths to `marketplace.json` files * **Remote URLs**: direct URLs to hosted `marketplace.json` files ### Add from GitHub Add a GitHub repository that contains a `.claude-plugin/marketplace.json` file using the `owner/repo` format—where `owner` is the GitHub username or organization and `repo` is the repository name. For example, `anthropics/claude-code` refers to the `claude-code` repository owned by `anthropics`: ```shell theme={null} /plugin marketplace add anthropics/claude-code ``` ### Add from other Git hosts Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers: Using HTTPS: ```shell theme={null} /plugin marketplace add https://gitlab.com/company/plugins.git ``` Using SSH: ```shell theme={null} /plugin marketplace add git@gitlab.com:company/plugins.git ``` To add a specific branch or tag, append `#` followed by the ref: ```shell theme={null} /plugin marketplace add https://gitlab.com/company/plugins.git#v1.0.0 ``` ### Add from local paths Add a local directory that contains a `.claude-plugin/marketplace.json` file: ```shell theme={null} /plugin marketplace add ./my-marketplace ``` You can also add a direct path to a `marketplace.json` file: ```shell theme={null} /plugin marketplace add ./path/to/marketplace.json ``` ### Add from remote URLs Add a remote `marketplace.json` file via URL: ```shell theme={null} /plugin marketplace add https://example.com/marketplace.json ``` URL-based marketplaces have some limitations compared to Git-based marketplaces. If you encounter "path not found" errors when installing plugins, see [Troubleshooting](/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces). ## Install plugins Once you've added marketplaces, you can install plugins directly (installs to user scope by default): ```shell theme={null} /plugin install plugin-name@marketplace-name ``` To choose a different [installation scope](/en/settings#configuration-scopes), use the interactive UI: run `/plugin`, go to the **Discover** tab, and press **Enter** on a plugin. You'll see options for: * **User scope** (default): install for yourself across all projects * **Project scope**: install for all collaborators on this repository (adds to `.claude/settings.json`) * **Local scope**: install for yourself in this repository only (not shared with collaborators) You may also see plugins with **managed** scope—these are installed by administrators via [managed settings](/en/settings#settings-files) and cannot be modified. Run `/plugin` and go to the **Installed** tab to see your plugins grouped by scope. Make sure you trust a plugin before installing it. Anthropic does not control what MCP servers, files, or other software are included in plugins and cannot verify that they work as intended. Check each plugin's homepage for more information. ## Manage installed plugins Run `/plugin` and go to the **Installed** tab to view, enable, disable, or uninstall your plugins. Type to filter the list by plugin name or description. You can also manage plugins with direct commands. Disable a plugin without uninstalling: ```shell theme={null} /plugin disable plugin-name@marketplace-name ``` Re-enable a disabled plugin: ```shell theme={null} /plugin enable plugin-name@marketplace-name ``` Completely remove a plugin: ```shell theme={null} /plugin uninstall plugin-name@marketplace-name ``` The `--scope` option lets you target a specific scope with CLI commands: ```shell theme={null} claude plugin install formatter@your-org --scope project claude plugin uninstall formatter@your-org --scope project ``` ## Manage marketplaces You can manage marketplaces through the interactive `/plugin` interface or with CLI commands. ### Use the interactive interface Run `/plugin` and go to the **Marketplaces** tab to: * View all your added marketplaces with their sources and status * Add new marketplaces * Update marketplace listings to fetch the latest plugins * Remove marketplaces you no longer need ### Use CLI commands You can also manage marketplaces with direct commands. List all configured marketplaces: ```shell theme={null} /plugin marketplace list ``` Refresh plugin listings from a marketplace: ```shell theme={null} /plugin marketplace update marketplace-name ``` Remove a marketplace: ```shell theme={null} /plugin marketplace remove marketplace-name ``` Removing a marketplace will uninstall any plugins you installed from it. ### Configure auto-updates Claude Code can automatically update marketplaces and their installed plugins at startup. When auto-update is enabled for a marketplace, Claude Code refreshes the marketplace data and updates installed plugins to their latest versions. If any plugins were updated, you'll see a notification suggesting you restart Claude Code. Toggle auto-update for individual marketplaces through the UI: 1. Run `/plugin` to open the plugin manager 2. Select **Marketplaces** 3. Choose a marketplace from the list 4. Select **Enable auto-update** or **Disable auto-update** Official Anthropic marketplaces have auto-update enabled by default. Third-party and local development marketplaces have auto-update disabled by default. To disable all automatic updates entirely for both Claude Code and all plugins, set the `DISABLE_AUTOUPDATER` environment variable. See [Auto updates](/en/setup#auto-updates) for details. To keep plugin auto-updates enabled while disabling Claude Code auto-updates, set `FORCE_AUTOUPDATE_PLUGINS=true` along with `DISABLE_AUTOUPDATER`: ```shell theme={null} export DISABLE_AUTOUPDATER=true export FORCE_AUTOUPDATE_PLUGINS=true ``` This is useful when you want to manage Claude Code updates manually but still receive automatic plugin updates. ## Configure team marketplaces Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins. For full configuration options including `extraKnownMarketplaces` and `enabledPlugins`, see [Plugin settings](/en/settings#plugin-settings). ## Troubleshooting ### /plugin command not recognized If you see "unknown command" or the `/plugin` command doesn't appear: 1. **Check your version**: Run `claude --version`. Plugins require version 1.0.33 or later. 2. **Update Claude Code**: * **Homebrew**: `brew upgrade claude-code` * **npm**: `npm update -g @anthropic-ai/claude-code` * **Native installer**: Re-run the install command from [Setup](/en/setup) 3. **Restart Claude Code**: After updating, restart your terminal and run `claude` again. ### Common issues * **Marketplace not loading**: Verify the URL is accessible and that `.claude-plugin/marketplace.json` exists at the path * **Plugin installation failures**: Check that plugin source URLs are accessible and repositories are public (or you have access) * **Files not found after installation**: Plugins are copied to a cache, so paths referencing files outside the plugin directory won't work * **Plugin skills not appearing**: Clear the cache with `rm -rf ~/.claude/plugins/cache`, restart Claude Code, and reinstall the plugin. For detailed troubleshooting with solutions, see [Troubleshooting](/en/plugin-marketplaces#troubleshooting) in the marketplace guide. For debugging tools, see [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools). ### Code intelligence issues * **Language server not starting**: verify the binary is installed and available in your `$PATH`. Check the `/plugin` Errors tab for details. * **High memory usage**: language servers like `rust-analyzer` and `pyright` can consume significant memory on large projects. If you experience memory issues, disable the plugin with `/plugin disable ` and rely on Claude's built-in search tools instead. * **False positive diagnostics in monorepos**: language servers may report unresolved import errors for internal packages if the workspace isn't configured correctly. These don't affect Claude's ability to edit code. ## Next steps * **Build your own plugins**: See [Plugins](/en/plugins) to create skills, agents, and hooks * **Create a marketplace**: See [Create a plugin marketplace](/en/plugin-marketplaces) to distribute plugins to your team or community * **Technical reference**: See [Plugins reference](/en/plugins-reference) for complete specifications --- # Source: https://code.claude.com/docs/en/features-overview.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Extend Claude Code > Understand when to use CLAUDE.md, Skills, subagents, hooks, MCP, and plugins. Claude Code combines a model that reasons about your code with [built-in tools](/en/how-claude-code-works#tools) for file operations, search, execution, and web access. The built-in tools cover most coding tasks. This guide covers the extension layer: features you add to customize what Claude knows, connect it to external services, and automate workflows. For how the core agentic loop works, see [How Claude Code works](/en/how-claude-code-works). **New to Claude Code?** Start with [CLAUDE.md](/en/memory) for project conventions. Add other extensions as you need them. ## Overview Extensions plug into different parts of the agentic loop: * **[CLAUDE.md](/en/memory)** adds persistent context Claude sees every session * **[Skills](/en/skills)** add reusable knowledge and invocable workflows * **[MCP](/en/mcp)** connects Claude to external services and tools * **[Subagents](/en/sub-agents)** run their own loops in isolated context, returning summaries * **[Hooks](/en/hooks)** run outside the loop entirely as deterministic scripts * **[Plugins](/en/plugins)** and **[marketplaces](/en/plugin-marketplaces)** package and distribute these features [Skills](/en/skills) are the most flexible extension. A skill is a markdown file containing knowledge, workflows, or instructions. You can invoke skills with a slash command like `/deploy`, or Claude can load them automatically when relevant. Skills can run in your current conversation or in an isolated context via subagents. ## Match features to your goal Features range from always-on context that Claude sees every session, to on-demand capabilities you or Claude can invoke, to background automation that runs on specific events. The table below shows what's available and when each one makes sense. | Feature | What it does | When to use it | Example | | ------------- | ---------------------------------------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------- | | **CLAUDE.md** | Persistent context loaded every conversation | Project conventions, "always do X" rules | "Use pnpm, not npm. Run tests before committing." | | **Skill** | Instructions, knowledge, and workflows Claude can use | Reusable content, reference docs, repeatable tasks | `/review` runs your code review checklist; API docs skill with endpoint patterns | | **Subagent** | Isolated execution context that returns summarized results | Context isolation, parallel tasks, specialized workers | Research task that reads many files but returns only key findings | | **MCP** | Connect to external services | External data or actions | Query your database, post to Slack, control a browser | | **Hook** | Deterministic script that runs on events | Predictable automation, no LLM involved | Run ESLint after every file edit | **[Plugins](/en/plugins)** are the packaging layer. A plugin bundles skills, hooks, subagents, and MCP servers into a single installable unit. Plugin skills are namespaced (like `/my-plugin:review`) so multiple plugins can coexist. Use plugins when you want to reuse the same setup across multiple repositories or distribute to others via a **[marketplace](/en/plugin-marketplaces)**. ### Compare similar features Some features can seem similar. Here's how to tell them apart. Skills and subagents solve different problems: * **Skills** are reusable content you can load into any context * **Subagents** are isolated workers that run separately from your main conversation | Aspect | Skill | Subagent | | --------------- | ---------------------------------------------- | ---------------------------------------------------------------- | | **What it is** | Reusable instructions, knowledge, or workflows | Isolated worker with its own context | | **Key benefit** | Share content across contexts | Context isolation. Work happens separately, only summary returns | | **Best for** | Reference material, invocable workflows | Tasks that read many files, parallel work, specialized workers | **Skills can be reference or action.** Reference skills provide knowledge Claude uses throughout your session (like your API style guide). Action skills tell Claude to do something specific (like `/deploy` that runs your deployment workflow). **Use a subagent** when you need context isolation or when your context window is getting full. The subagent might read dozens of files or run extensive searches, but your main conversation only receives a summary. Since subagent work doesn't consume your main context, this is also useful when you don't need the intermediate work to remain visible. Custom subagents can have their own instructions and can preload skills. **They can combine.** A subagent can preload specific skills (`skills:` field). A skill can run in isolated context using `context: fork`. See [Skills](/en/skills) for details. Both store instructions, but they load differently and serve different purposes. | Aspect | CLAUDE.md | Skill | | ------------------------- | ---------------------------- | --------------------------------------- | | **Loads** | Every session, automatically | On demand | | **Can include files** | Yes, with `@path` imports | Yes, with `@path` imports | | **Can trigger workflows** | No | Yes, with `/` | | **Best for** | "Always do X" rules | Reference material, invocable workflows | **Put it in CLAUDE.md** if Claude should always know it: coding conventions, build commands, project structure, "never do X" rules. **Put it in a skill** if it's reference material Claude needs sometimes (API docs, style guides) or a workflow you trigger with `/` (deploy, review, release). **Rule of thumb:** Keep CLAUDE.md under \~500 lines. If it's growing, move reference content to skills. MCP connects Claude to external services. Skills extend what Claude knows, including how to use those services effectively. | Aspect | MCP | Skill | | -------------- | ---------------------------------------------------- | ------------------------------------------------------- | | **What it is** | Protocol for connecting to external services | Knowledge, workflows, and reference material | | **Provides** | Tools and data access | Knowledge, workflows, reference material | | **Examples** | Slack integration, database queries, browser control | Code review checklist, deploy workflow, API style guide | These solve different problems and work well together: **MCP** gives Claude the ability to interact with external systems. Without MCP, Claude can't query your database or post to Slack. **Skills** give Claude knowledge about how to use those tools effectively, plus workflows you can trigger with `/`. A skill might include your team's database schema and query patterns, or a `/post-to-slack` workflow with your team's message formatting rules. Example: An MCP server connects Claude to your database. A skill teaches Claude your data model, common query patterns, and which tables to use for different tasks. ### Understand how features layer Features can be defined at multiple levels: user-wide, per-project, via plugins, or through managed policies. You can also nest CLAUDE.md files in subdirectories or place skills in specific packages of a monorepo. When the same feature exists at multiple levels, here's how they layer: * **CLAUDE.md files** are additive: all levels contribute content to Claude's context simultaneously. Files from your working directory and above load at launch; subdirectories load as you work in them. When instructions conflict, Claude uses judgment to reconcile them, with more specific instructions typically taking precedence. See [how Claude looks up memories](/en/memory#how-claude-looks-up-memories). * **Skills and subagents** override by name: when the same name exists at multiple levels, one definition wins based on priority (managed > user > project for skills; managed > CLI flag > project > user > plugin for subagents). Plugin skills are [namespaced](/en/plugins#add-skills-to-your-plugin) to avoid conflicts. See [skill discovery](/en/skills#where-skills-live) and [subagent scope](/en/sub-agents#choose-the-subagent-scope). * **MCP servers** override by name: local > project > user. See [MCP scope](/en/mcp#scope-hierarchy-and-precedence). * **Hooks** merge: all registered hooks fire for their matching events regardless of source. See [hooks](/en/hooks). ### Combine features Each extension solves a different problem: CLAUDE.md handles always-on context, skills handle on-demand knowledge and workflows, MCP handles external connections, subagents handle isolation, and hooks handle automation. Real setups combine them based on your workflow. For example, you might use CLAUDE.md for project conventions, a skill for your deployment workflow, MCP to connect to your database, and a hook to run linting after every edit. Each feature handles what it's best at. | Pattern | How it works | Example | | ---------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | **Skill + MCP** | MCP provides the connection; a skill teaches Claude how to use it well | MCP connects to your database, a skill documents your schema and query patterns | | **Skill + Subagent** | A skill spawns subagents for parallel work | `/review` skill kicks off security, performance, and style subagents that work in isolated context | | **CLAUDE.md + Skills** | CLAUDE.md holds always-on rules; skills hold reference material loaded on demand | CLAUDE.md says "follow our API conventions," a skill contains the full API style guide | | **Hook + MCP** | A hook triggers external actions through MCP | Post-edit hook sends a Slack notification when Claude modifies critical files | ## Understand context costs Every feature you add consumes some of Claude's context. Too much can fill up your context window, but it can also add noise that makes Claude less effective; skills may not trigger correctly, or Claude may lose track of your conventions. Understanding these trade-offs helps you build an effective setup. ### Context cost by feature Each feature has a different loading strategy and context cost: | Feature | When it loads | What loads | Context cost | | --------------- | ------------------------- | --------------------------------------------- | -------------------------------------------- | | **CLAUDE.md** | Session start | Full content | Every request | | **Skills** | Session start + when used | Descriptions at start, full content when used | Low (descriptions every request)\* | | **MCP servers** | Session start | All tool definitions and schemas | Every request | | **Subagents** | When spawned | Fresh context with specified skills | Isolated from main session | | **Hooks** | On trigger | Nothing (runs externally) | Zero, unless hook returns additional context | \*By default, skill descriptions load at session start so Claude can decide when to use them. Set `disable-model-invocation: true` in a skill's frontmatter to hide it from Claude entirely until you invoke it manually. This reduces context cost to zero for skills you only trigger yourself. ### Understand how features load Each feature loads at different points in your session. The tabs below explain when each one loads and what goes into context. Context loading: CLAUDE.md and MCP load at session start and stay in every request. Skills load descriptions at start, full content on invocation. Subagents get isolated context. Hooks run externally. **When:** Session start **What loads:** Full content of all CLAUDE.md files (managed, user, and project levels). **Inheritance:** Claude reads CLAUDE.md files from your working directory up to the root, and discovers nested ones in subdirectories as it accesses those files. See [How Claude looks up memories](/en/memory#how-claude-looks-up-memories) for details. Keep CLAUDE.md under \~500 lines. Move reference material to skills, which load on-demand. Skills are extra capabilities in Claude's toolkit. They can be reference material (like an API style guide) or invocable workflows you trigger with `/` (like `/deploy`). Some are built-in; you can also create your own. Claude uses skills when appropriate, or you can invoke one directly. **When:** Depends on the skill's configuration. By default, descriptions load at session start and full content loads when used. For user-only skills (`disable-model-invocation: true`), nothing loads until you invoke them. **What loads:** For model-invocable skills, Claude sees names and descriptions in every request. When you invoke a skill with `/` or Claude loads it automatically, the full content loads into your conversation. **How Claude chooses skills:** Claude matches your task against skill descriptions to decide which are relevant. If descriptions are vague or overlap, Claude may load the wrong skill or miss one that would help. To tell Claude to use a specific skill, invoke it with `/`. Skills with `disable-model-invocation: true` are invisible to Claude until you invoke them. **Context cost:** Low until used. User-only skills have zero cost until invoked. **In subagents:** Skills work differently in subagents. Instead of on-demand loading, skills passed to a subagent are fully preloaded into its context at launch. Subagents don't inherit skills from the main session; you must specify them explicitly. Use `disable-model-invocation: true` for skills with side effects. This saves context and ensures only you trigger them. **When:** Session start. **What loads:** All tool definitions and JSON schemas from connected servers. **Context cost:** [Tool search](/en/mcp#scale-with-mcp-tool-search) (enabled by default) loads MCP tools up to 10% of context and defers the rest until needed. **Reliability note:** MCP connections can fail silently mid-session. If a server disconnects, its tools disappear without warning. Claude may try to use a tool that no longer exists. If you notice Claude failing to use an MCP tool it previously could access, check the connection with `/mcp`. Run `/mcp` to see token costs per server. Disconnect servers you're not actively using. **When:** On demand, when you or Claude spawns one for a task. **What loads:** Fresh, isolated context containing: * The system prompt (shared with parent for cache efficiency) * Full content of skills listed in the agent's `skills:` field * CLAUDE.md and git status (inherited from parent) * Whatever context the lead agent passes in the prompt **Context cost:** Isolated from main session. Subagents don't inherit your conversation history or invoked skills. Use subagents for work that doesn't need your full conversation context. Their isolation prevents bloating your main session. **When:** On trigger. Hooks fire at specific lifecycle events like tool execution, session boundaries, prompt submission, permission requests, and compaction. See [Hooks](/en/hooks) for the full list. **What loads:** Nothing by default. Hooks run as external scripts. **Context cost:** Zero, unless the hook returns output that gets added as messages to your conversation. Hooks are ideal for side effects (linting, logging) that don't need to affect Claude's context. ## Learn more Each feature has its own guide with setup instructions, examples, and configuration options. Store project context, conventions, and instructions Give Claude domain expertise and reusable workflows Offload work to isolated context Connect Claude to external services Automate workflows with hooks Bundle and share feature sets Host and distribute plugin collections --- # Source: https://code.claude.com/docs/en/github-actions.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code GitHub Actions > Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards. Claude Code GitHub Actions is built on top of the [Claude Code SDK](https://docs.claude.com/en/docs/agent-sdk), which enables programmatic integration of Claude Code into your applications. You can use the SDK to build custom automation workflows beyond GitHub Actions. **Claude Opus 4.5 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.5, configure the [model parameter](#breaking-changes-reference) to use `claude-opus-4-5-20251101`. ## Why use Claude Code GitHub Actions? * **Instant PR creation**: Describe what you need, and Claude creates a complete PR with all necessary changes * **Automated code implementation**: Turn issues into working code with a single command * **Follows your standards**: Claude respects your `CLAUDE.md` guidelines and existing code patterns * **Simple setup**: Get started in minutes with our installer and API key * **Secure by default**: Your code stays on Github's runners ## What can Claude do? Claude Code provides a powerful GitHub Action that transforms how you work with code: ### Claude Code Action This GitHub Action allows you to run Claude Code within your GitHub Actions workflows. You can use this to build any custom workflow on top of Claude Code. [View repository →](https://github.com/anthropics/claude-code-action) ## Setup ## Quick setup The easiest way to set up this action is through Claude Code in the terminal. Just open claude and run `/install-github-app`. This command will guide you through setting up the GitHub app and required secrets. * You must be a repository admin to install the GitHub app and add secrets * The GitHub app will request read & write permissions for Contents, Issues, and Pull requests * This quickstart method is only available for direct Claude API users. If you're using AWS Bedrock or Google Vertex AI, please see the [Using with AWS Bedrock & Google Vertex AI](#using-with-aws-bedrock-%26-google-vertex-ai) section. ## Manual setup If the `/install-github-app` command fails or you prefer manual setup, please follow these manual setup instructions: 1. **Install the Claude GitHub app** to your repository: [https://github.com/apps/claude](https://github.com/apps/claude) The Claude GitHub app requires the following repository permissions: * **Contents**: Read & write (to modify repository files) * **Issues**: Read & write (to respond to issues) * **Pull requests**: Read & write (to create PRs and push changes) For more details on security and permissions, see the [security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md). 2. **Add ANTHROPIC\_API\_KEY** to your repository secrets ([Learn how to use secrets in GitHub Actions](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions)) 3. **Copy the workflow file** from [examples/claude.yml](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) into your repository's `.github/workflows/` After completing either the quickstart or manual setup, test the action by tagging `@claude` in an issue or PR comment. ## Upgrading from Beta Claude Code GitHub Actions v1.0 introduces breaking changes that require updating your workflow files in order to upgrade to v1.0 from the beta version. If you're currently using the beta version of Claude Code GitHub Actions, we recommend that you update your workflows to use the GA version. The new version simplifies configuration while adding powerful new features like automatic mode detection. ### Essential changes All beta users must make these changes to their workflow files in order to upgrade: 1. **Update the action version**: Change `@beta` to `@v1` 2. **Remove mode configuration**: Delete `mode: "tag"` or `mode: "agent"` (now auto-detected) 3. **Update prompt inputs**: Replace `direct_prompt` with `prompt` 4. **Move CLI options**: Convert `max_turns`, `model`, `custom_instructions`, etc. to `claude_args` ### Breaking Changes Reference | Old Beta Input | New v1.0 Input | | --------------------- | ------------------------------------- | | `mode` | *(Removed - auto-detected)* | | `direct_prompt` | `prompt` | | `override_prompt` | `prompt` with GitHub variables | | `custom_instructions` | `claude_args: --append-system-prompt` | | `max_turns` | `claude_args: --max-turns` | | `model` | `claude_args: --model` | | `allowed_tools` | `claude_args: --allowedTools` | | `disallowed_tools` | `claude_args: --disallowedTools` | | `claude_env` | `settings` JSON format | ### Before and After Example **Beta version:** ```yaml theme={null} - uses: anthropics/claude-code-action@beta with: mode: "tag" direct_prompt: "Review this PR for security issues" anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} custom_instructions: "Follow our coding standards" max_turns: "10" model: "claude-sonnet-4-5-20250929" ``` **GA version (v1.0):** ```yaml theme={null} - uses: anthropics/claude-code-action@v1 with: prompt: "Review this PR for security issues" anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} claude_args: | --append-system-prompt "Follow our coding standards" --max-turns 10 --model claude-sonnet-4-5-20250929 ``` The action now automatically detects whether to run in interactive mode (responds to `@claude` mentions) or automation mode (runs immediately with a prompt) based on your configuration. ## Example use cases Claude Code GitHub Actions can help you with a variety of tasks. The [examples directory](https://github.com/anthropics/claude-code-action/tree/main/examples) contains ready-to-use workflows for different scenarios. ### Basic workflow ```yaml theme={null} name: Claude Code on: issue_comment: types: [created] pull_request_review_comment: types: [created] jobs: claude: runs-on: ubuntu-latest steps: - uses: anthropics/claude-code-action@v1 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} # Responds to @claude mentions in comments ``` ### Using skills ```yaml theme={null} name: Code Review on: pull_request: types: [opened, synchronize] jobs: review: runs-on: ubuntu-latest steps: - uses: anthropics/claude-code-action@v1 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} prompt: "/review" claude_args: "--max-turns 5" ``` ### Custom automation with prompts ```yaml theme={null} name: Daily Report on: schedule: - cron: "0 9 * * *" jobs: report: runs-on: ubuntu-latest steps: - uses: anthropics/claude-code-action@v1 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} prompt: "Generate a summary of yesterday's commits and open issues" claude_args: "--model claude-opus-4-5-20251101" ``` ### Common use cases In issue or PR comments: ``` @claude implement this feature based on the issue description @claude how should I implement user authentication for this endpoint? @claude fix the TypeError in the user dashboard component ``` Claude will automatically analyze the context and respond appropriately. ## Best practices ### CLAUDE.md configuration Create a `CLAUDE.md` file in your repository root to define code style guidelines, review criteria, project-specific rules, and preferred patterns. This file guides Claude's understanding of your project standards. ### Security considerations Never commit API keys directly to your repository. For comprehensive security guidance including permissions, authentication, and best practices, see the [Claude Code Action security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md). Always use GitHub Secrets for API keys: * Add your API key as a repository secret named `ANTHROPIC_API_KEY` * Reference it in workflows: `anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}` * Limit action permissions to only what's necessary * Review Claude's suggestions before merging Always use GitHub Secrets (for example, `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files. ### Optimizing performance Use issue templates to provide context, keep your `CLAUDE.md` concise and focused, and configure appropriate timeouts for your workflows. ### CI costs When using Claude Code GitHub Actions, be aware of the associated costs: **GitHub Actions costs:** * Claude Code runs on GitHub-hosted runners, which consume your GitHub Actions minutes * See [GitHub's billing documentation](https://docs.github.com/en/billing/managing-billing-for-your-products/managing-billing-for-github-actions/about-billing-for-github-actions) for detailed pricing and minute limits **API costs:** * Each Claude interaction consumes API tokens based on the length of prompts and responses * Token usage varies by task complexity and codebase size * See [Claude's pricing page](https://claude.com/platform/api) for current token rates **Cost optimization tips:** * Use specific `@claude` commands to reduce unnecessary API calls * Configure appropriate `--max-turns` in `claude_args` to prevent excessive iterations * Set workflow-level timeouts to avoid runaway jobs * Consider using GitHub's concurrency controls to limit parallel runs ## Configuration examples The Claude Code Action v1 simplifies configuration with unified parameters: ```yaml theme={null} - uses: anthropics/claude-code-action@v1 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} prompt: "Your instructions here" # Optional claude_args: "--max-turns 5" # Optional CLI arguments ``` Key features: * **Unified prompt interface** - Use `prompt` for all instructions * **Commands** - Prebuilt prompts like `/review` or `/fix` * **CLI passthrough** - Any Claude Code CLI argument via `claude_args` * **Flexible triggers** - Works with any GitHub event Visit the [examples directory](https://github.com/anthropics/claude-code-action/tree/main/examples) for complete workflow files. When responding to issue or PR comments, Claude automatically responds to @claude mentions. For other events, use the `prompt` parameter to provide instructions. ## Using with AWS Bedrock & Google Vertex AI For enterprise environments, you can use Claude Code GitHub Actions with your own cloud infrastructure. This approach gives you control over data residency and billing while maintaining the same functionality. ### Prerequisites Before setting up Claude Code GitHub Actions with cloud providers, you need: #### For Google Cloud Vertex AI: 1. A Google Cloud Project with Vertex AI enabled 2. Workload Identity Federation configured for GitHub Actions 3. A service account with the required permissions 4. A GitHub App (recommended) or use the default GITHUB\_TOKEN #### For AWS Bedrock: 1. An AWS account with Amazon Bedrock enabled 2. GitHub OIDC Identity Provider configured in AWS 3. An IAM role with Bedrock permissions 4. A GitHub App (recommended) or use the default GITHUB\_TOKEN For best control and security when using 3P providers like Vertex AI or Bedrock, we recommend creating your own GitHub App: 1. Go to [https://github.com/settings/apps/new](https://github.com/settings/apps/new) 2. Fill in the basic information: * **GitHub App name**: Choose a unique name (e.g., "YourOrg Claude Assistant") * **Homepage URL**: Your organization's website or the repository URL 3. Configure the app settings: * **Webhooks**: Uncheck "Active" (not needed for this integration) 4. Set the required permissions: * **Repository permissions**: * Contents: Read & Write * Issues: Read & Write * Pull requests: Read & Write 5. Click "Create GitHub App" 6. After creation, click "Generate a private key" and save the downloaded `.pem` file 7. Note your App ID from the app settings page 8. Install the app to your repository: * From your app's settings page, click "Install App" in the left sidebar * Select your account or organization * Choose "Only select repositories" and select the specific repository * Click "Install" 9. Add the private key as a secret to your repository: * Go to your repository's Settings → Secrets and variables → Actions * Create a new secret named `APP_PRIVATE_KEY` with the contents of the `.pem` file 10. Add the App ID as a secret: * Create a new secret named `APP_ID` with your GitHub App's ID This app will be used with the [actions/create-github-app-token](https://github.com/actions/create-github-app-token) action to generate authentication tokens in your workflows. **Alternative for Claude API or if you don't want to setup your own Github app**: Use the official Anthropic app: 1. Install from: [https://github.com/apps/claude](https://github.com/apps/claude) 2. No additional configuration needed for authentication Choose your cloud provider and set up secure authentication: **Configure AWS to allow GitHub Actions to authenticate securely without storing credentials.** > **Security Note**: Use repository-specific configurations and grant only the minimum required permissions. **Required Setup**: 1. **Enable Amazon Bedrock**: * Request access to Claude models in Amazon Bedrock * For cross-region models, request access in all required regions 2. **Set up GitHub OIDC Identity Provider**: * Provider URL: `https://token.actions.githubusercontent.com` * Audience: `sts.amazonaws.com` 3. **Create IAM Role for GitHub Actions**: * Trusted entity type: Web identity * Identity provider: `token.actions.githubusercontent.com` * Permissions: `AmazonBedrockFullAccess` policy * Configure trust policy for your specific repository **Required Values**: After setup, you'll need: * **AWS\_ROLE\_TO\_ASSUME**: The ARN of the IAM role you created OIDC is more secure than using static AWS access keys because credentials are temporary and automatically rotated. See [AWS documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html) for detailed OIDC setup instructions. **Configure Google Cloud to allow GitHub Actions to authenticate securely without storing credentials.** > **Security Note**: Use repository-specific configurations and grant only the minimum required permissions. **Required Setup**: 1. **Enable APIs** in your Google Cloud project: * IAM Credentials API * Security Token Service (STS) API * Vertex AI API 2. **Create Workload Identity Federation resources**: * Create a Workload Identity Pool * Add a GitHub OIDC provider with: * Issuer: `https://token.actions.githubusercontent.com` * Attribute mappings for repository and owner * **Security recommendation**: Use repository-specific attribute conditions 3. **Create a Service Account**: * Grant only `Vertex AI User` role * **Security recommendation**: Create a dedicated service account per repository 4. **Configure IAM bindings**: * Allow the Workload Identity Pool to impersonate the service account * **Security recommendation**: Use repository-specific principal sets **Required Values**: After setup, you'll need: * **GCP\_WORKLOAD\_IDENTITY\_PROVIDER**: The full provider resource name * **GCP\_SERVICE\_ACCOUNT**: The service account email address Workload Identity Federation eliminates the need for downloadable service account keys, improving security. For detailed setup instructions, consult the [Google Cloud Workload Identity Federation documentation](https://cloud.google.com/iam/docs/workload-identity-federation). Add the following secrets to your repository (Settings → Secrets and variables → Actions): #### For Claude API (Direct): 1. **For API Authentication**: * `ANTHROPIC_API_KEY`: Your Claude API key from [console.anthropic.com](https://console.anthropic.com) 2. **For GitHub App (if using your own app)**: * `APP_ID`: Your GitHub App's ID * `APP_PRIVATE_KEY`: The private key (.pem) content #### For Google Cloud Vertex AI 1. **For GCP Authentication**: * `GCP_WORKLOAD_IDENTITY_PROVIDER` * `GCP_SERVICE_ACCOUNT` 2. **For GitHub App (if using your own app)**: * `APP_ID`: Your GitHub App's ID * `APP_PRIVATE_KEY`: The private key (.pem) content #### For AWS Bedrock 1. **For AWS Authentication**: * `AWS_ROLE_TO_ASSUME` 2. **For GitHub App (if using your own app)**: * `APP_ID`: Your GitHub App's ID * `APP_PRIVATE_KEY`: The private key (.pem) content Create GitHub Actions workflow files that integrate with your cloud provider. The examples below show complete configurations for both AWS Bedrock and Google Vertex AI: **Prerequisites:** * AWS Bedrock access enabled with Claude model permissions * GitHub configured as an OIDC identity provider in AWS * IAM role with Bedrock permissions that trusts GitHub Actions **Required GitHub secrets:** | Secret Name | Description | | -------------------- | ------------------------------------------------- | | `AWS_ROLE_TO_ASSUME` | ARN of the IAM role for Bedrock access | | `APP_ID` | Your GitHub App ID (from app settings) | | `APP_PRIVATE_KEY` | The private key you generated for your GitHub App | ```yaml theme={null} name: Claude PR Action permissions: contents: write pull-requests: write issues: write id-token: write on: issue_comment: types: [created] pull_request_review_comment: types: [created] issues: types: [opened, assigned] jobs: claude-pr: if: | (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || (github.event_name == 'issues' && contains(github.event.issue.body, '@claude')) runs-on: ubuntu-latest env: AWS_REGION: us-west-2 steps: - name: Checkout repository uses: actions/checkout@v4 - name: Generate GitHub App token id: app-token uses: actions/create-github-app-token@v2 with: app-id: ${{ secrets.APP_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - name: Configure AWS Credentials (OIDC) uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} aws-region: us-west-2 - uses: anthropics/claude-code-action@v1 with: github_token: ${{ steps.app-token.outputs.token }} use_bedrock: "true" claude_args: '--model us.anthropic.claude-sonnet-4-5-20250929-v1:0 --max-turns 10' ``` The model ID format for Bedrock includes the region prefix (e.g., `us.anthropic.claude...`) and version suffix. **Prerequisites:** * Vertex AI API enabled in your GCP project * Workload Identity Federation configured for GitHub * Service account with Vertex AI permissions **Required GitHub secrets:** | Secret Name | Description | | -------------------------------- | ------------------------------------------------- | | `GCP_WORKLOAD_IDENTITY_PROVIDER` | Workload identity provider resource name | | `GCP_SERVICE_ACCOUNT` | Service account email with Vertex AI access | | `APP_ID` | Your GitHub App ID (from app settings) | | `APP_PRIVATE_KEY` | The private key you generated for your GitHub App | ```yaml theme={null} name: Claude PR Action permissions: contents: write pull-requests: write issues: write id-token: write on: issue_comment: types: [created] pull_request_review_comment: types: [created] issues: types: [opened, assigned] jobs: claude-pr: if: | (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || (github.event_name == 'issues' && contains(github.event.issue.body, '@claude')) runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Generate GitHub App token id: app-token uses: actions/create-github-app-token@v2 with: app-id: ${{ secrets.APP_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - name: Authenticate to Google Cloud id: auth uses: google-github-actions/auth@v2 with: workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }} service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }} - uses: anthropics/claude-code-action@v1 with: github_token: ${{ steps.app-token.outputs.token }} trigger_phrase: "@claude" use_vertex: "true" claude_args: '--model claude-sonnet-4@20250514 --max-turns 10' env: ANTHROPIC_VERTEX_PROJECT_ID: ${{ steps.auth.outputs.project_id }} CLOUD_ML_REGION: us-east5 VERTEX_REGION_CLAUDE_3_7_SONNET: us-east5 ``` The project ID is automatically retrieved from the Google Cloud authentication step, so you don't need to hardcode it. ## Troubleshooting ### Claude not responding to @claude commands Verify the GitHub App is installed correctly, check that workflows are enabled, ensure API key is set in repository secrets, and confirm the comment contains `@claude` (not `/claude`). ### CI not running on Claude's commits Ensure you're using the GitHub App or custom app (not Actions user), check workflow triggers include the necessary events, and verify app permissions include CI triggers. ### Authentication errors Confirm API key is valid and has sufficient permissions. For Bedrock/Vertex, check credentials configuration and ensure secrets are named correctly in workflows. ## Advanced configuration ### Action parameters The Claude Code Action v1 uses a simplified configuration: | Parameter | Description | Required | | ------------------- | ------------------------------------------------------ | -------- | | `prompt` | Instructions for Claude (text or skill like `/review`) | No\* | | `claude_args` | CLI arguments passed to Claude Code | No | | `anthropic_api_key` | Claude API key | Yes\*\* | | `github_token` | GitHub token for API access | No | | `trigger_phrase` | Custom trigger phrase (default: "@claude") | No | | `use_bedrock` | Use AWS Bedrock instead of Claude API | No | | `use_vertex` | Use Google Vertex AI instead of Claude API | No | \*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase\ \*\*Required for direct Claude API, not for Bedrock/Vertex #### Pass CLI arguments The `claude_args` parameter accepts any Claude Code CLI arguments: ```yaml theme={null} claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929 --mcp-config /path/to/config.json" ``` Common arguments: * `--max-turns`: Maximum conversation turns (default: 10) * `--model`: Model to use (for example, `claude-sonnet-4-5-20250929`) * `--mcp-config`: Path to MCP configuration * `--allowed-tools`: Comma-separated list of allowed tools * `--debug`: Enable debug output ### Alternative integration methods While the `/install-github-app` command is the recommended approach, you can also: * **Custom GitHub App**: For organizations needing branded usernames or custom authentication flows. Create your own GitHub App with required permissions (contents, issues, pull requests) and use the actions/create-github-app-token action to generate tokens in your workflows. * **Manual GitHub Actions**: Direct workflow configuration for maximum flexibility * **MCP Configuration**: Dynamic loading of Model Context Protocol servers See the [Claude Code Action documentation](https://github.com/anthropics/claude-code-action/blob/main/docs) for detailed guides on authentication, security, and advanced configuration. ### Customizing Claude's behavior You can configure Claude's behavior in two ways: 1. **CLAUDE.md**: Define coding standards, review criteria, and project-specific rules in a `CLAUDE.md` file at the root of your repository. Claude will follow these guidelines when creating PRs and responding to requests. Check out our [Memory documentation](/en/memory) for more details. 2. **Custom prompts**: Use the `prompt` parameter in the workflow file to provide workflow-specific instructions. This allows you to customize Claude's behavior for different workflows or tasks. Claude will follow these guidelines when creating PRs and responding to requests. --- # Source: https://code.claude.com/docs/en/gitlab-ci-cd.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code GitLab CI/CD > Learn about integrating Claude Code into your development workflow with GitLab CI/CD Claude Code for GitLab CI/CD is currently in beta. Features and functionality may evolve as we refine the experience. This integration is maintained by GitLab. For support, see the following [GitLab issue](https://gitlab.com/gitlab-org/gitlab/-/issues/573776). This integration is built on top of the [Claude Code CLI and SDK](https://docs.claude.com/en/docs/agent-sdk), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows. ## Why use Claude Code with GitLab? * **Instant MR creation**: Describe what you need, and Claude proposes a complete MR with changes and explanation * **Automated implementation**: Turn issues into working code with a single command or mention * **Project-aware**: Claude follows your `CLAUDE.md` guidelines and existing code patterns * **Simple setup**: Add one job to `.gitlab-ci.yml` and a masked CI/CD variable * **Enterprise-ready**: Choose Claude API, AWS Bedrock, or Google Vertex AI to meet data residency and procurement needs * **Secure by default**: Runs in your GitLab runners with your branch protection and approvals ## How it works Claude Code uses GitLab CI/CD to run AI tasks in isolated jobs and commit results back via MRs: 1. **Event-driven orchestration**: GitLab listens for your chosen triggers (for example, a comment that mentions `@claude` in an issue, MR, or review thread). The job collects context from the thread and repository, builds prompts from that input, and runs Claude Code. 2. **Provider abstraction**: Use the provider that fits your environment: * Claude API (SaaS) * AWS Bedrock (IAM-based access, cross-region options) * Google Vertex AI (GCP-native, Workload Identity Federation) 3. **Sandboxed execution**: Each interaction runs in a container with strict network and filesystem rules. Claude Code enforces workspace-scoped permissions to constrain writes. Every change flows through an MR so reviewers see the diff and approvals still apply. Pick regional endpoints to reduce latency and meet data-sovereignty requirements while using existing cloud agreements. ## What can Claude do? Claude Code enables powerful CI/CD workflows that transform how you work with code: * Create and update MRs from issue descriptions or comments * Analyze performance regressions and propose optimizations * Implement features directly in a branch, then open an MR * Fix bugs and regressions identified by tests or comments * Respond to follow-up comments to iterate on requested changes ## Setup ### Quick setup The fastest way to get started is to add a minimal job to your `.gitlab-ci.yml` and set your API key as a masked variable. 1. **Add a masked CI/CD variable** * Go to **Settings** → **CI/CD** → **Variables** * Add `ANTHROPIC_API_KEY` (masked, protected as needed) 2. **Add a Claude job to `.gitlab-ci.yml`** ```yaml theme={null} stages: - ai claude: stage: ai image: node:24-alpine3.21 # Adjust rules to fit how you want to trigger the job: # - manual runs # - merge request events # - web/API triggers when a comment contains '@claude' rules: - if: '$CI_PIPELINE_SOURCE == "web"' - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' variables: GIT_STRATEGY: fetch before_script: - apk update - apk add --no-cache git curl bash - curl -fsSL https://claude.ai/install.sh | bash script: # Optional: start a GitLab MCP server if your setup provides one - /bin/gitlab-mcp-server || true # Use AI_FLOW_* variables when invoking via web/API triggers with context payloads - echo "$AI_FLOW_INPUT for $AI_FLOW_CONTEXT on $AI_FLOW_EVENT" - > claude -p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}" --permission-mode acceptEdits --allowedTools "Bash Read Edit Write mcp__gitlab" --debug ``` After adding the job and your `ANTHROPIC_API_KEY` variable, test by running the job manually from **CI/CD** → **Pipelines**, or trigger it from an MR to let Claude propose updates in a branch and open an MR if needed. To run on AWS Bedrock or Google Vertex AI instead of the Claude API, see the [Using with AWS Bedrock & Google Vertex AI](#using-with-aws-bedrock--google-vertex-ai) section below for authentication and environment setup. ### Manual setup (recommended for production) If you prefer a more controlled setup or need enterprise providers: 1. **Configure provider access**: * **Claude API**: Create and store `ANTHROPIC_API_KEY` as a masked CI/CD variable * **AWS Bedrock**: **Configure GitLab** → **AWS OIDC** and create an IAM role for Bedrock * **Google Vertex AI**: **Configure Workload Identity Federation for GitLab** → **GCP** 2. **Add project credentials for GitLab API operations**: * Use `CI_JOB_TOKEN` by default, or create a Project Access Token with `api` scope * Store as `GITLAB_ACCESS_TOKEN` (masked) if using a PAT 3. **Add the Claude job to `.gitlab-ci.yml`** (see examples below) 4. **(Optional) Enable mention-driven triggers**: * Add a project webhook for "Comments (notes)" to your event listener (if you use one) * Have the listener call the pipeline trigger API with variables like `AI_FLOW_INPUT` and `AI_FLOW_CONTEXT` when a comment contains `@claude` ## Example use cases ### Turn issues into MRs In an issue comment: ``` @claude implement this feature based on the issue description ``` Claude analyzes the issue and codebase, writes changes in a branch, and opens an MR for review. ### Get implementation help In an MR discussion: ``` @claude suggest a concrete approach to cache the results of this API call ``` Claude proposes changes, adds code with appropriate caching, and updates the MR. ### Fix bugs quickly In an issue or MR comment: ``` @claude fix the TypeError in the user dashboard component ``` Claude locates the bug, implements a fix, and updates the branch or opens a new MR. ## Using with AWS Bedrock & Google Vertex AI For enterprise environments, you can run Claude Code entirely on your cloud infrastructure with the same developer experience. ### Prerequisites Before setting up Claude Code with AWS Bedrock, you need: 1. An AWS account with Amazon Bedrock access to the desired Claude models 2. GitLab configured as an OIDC identity provider in AWS IAM 3. An IAM role with Bedrock permissions and a trust policy restricted to your GitLab project/refs 4. GitLab CI/CD variables for role assumption: * `AWS_ROLE_TO_ASSUME` (role ARN) * `AWS_REGION` (Bedrock region) ### Setup instructions Configure AWS to allow GitLab CI jobs to assume an IAM role via OIDC (no static keys). **Required setup:** 1. Enable Amazon Bedrock and request access to your target Claude models 2. Create an IAM OIDC provider for GitLab if not already present 3. Create an IAM role trusted by the GitLab OIDC provider, restricted to your project and protected refs 4. Attach least-privilege permissions for Bedrock invoke APIs **Required values to store in CI/CD variables:** * `AWS_ROLE_TO_ASSUME` * `AWS_REGION` Add variables in Settings → CI/CD → Variables: ```yaml theme={null} # For AWS Bedrock: - AWS_ROLE_TO_ASSUME - AWS_REGION ``` Use the AWS Bedrock job example above to exchange the GitLab job token for temporary AWS credentials at runtime. ### Prerequisites Before setting up Claude Code with Google Vertex AI, you need: 1. A Google Cloud project with: * Vertex AI API enabled * Workload Identity Federation configured to trust GitLab OIDC 2. A dedicated service account with only the required Vertex AI roles 3. GitLab CI/CD variables for WIF: * `GCP_WORKLOAD_IDENTITY_PROVIDER` (full resource name) * `GCP_SERVICE_ACCOUNT` (service account email) ### Setup instructions Configure Google Cloud to allow GitLab CI jobs to impersonate a service account via Workload Identity Federation. **Required setup:** 1. Enable IAM Credentials API, STS API, and Vertex AI API 2. Create a Workload Identity Pool and provider for GitLab OIDC 3. Create a dedicated service account with Vertex AI roles 4. Grant the WIF principal permission to impersonate the service account **Required values to store in CI/CD variables:** * `GCP_WORKLOAD_IDENTITY_PROVIDER` * `GCP_SERVICE_ACCOUNT` Add variables in Settings → CI/CD → Variables: ```yaml theme={null} # For Google Vertex AI: - GCP_WORKLOAD_IDENTITY_PROVIDER - GCP_SERVICE_ACCOUNT - CLOUD_ML_REGION (for example, us-east5) ``` Use the Google Vertex AI job example above to authenticate without storing keys. ## Configuration examples Below are ready-to-use snippets you can adapt to your pipeline. ### Basic .gitlab-ci.yml (Claude API) ```yaml theme={null} stages: - ai claude: stage: ai image: node:24-alpine3.21 rules: - if: '$CI_PIPELINE_SOURCE == "web"' - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' variables: GIT_STRATEGY: fetch before_script: - apk update - apk add --no-cache git curl bash - curl -fsSL https://claude.ai/install.sh | bash script: - /bin/gitlab-mcp-server || true - > claude -p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}" --permission-mode acceptEdits --allowedTools "Bash Read Edit Write mcp__gitlab" --debug # Claude Code will use ANTHROPIC_API_KEY from CI/CD variables ``` ### AWS Bedrock job example (OIDC) **Prerequisites:** * Amazon Bedrock enabled with access to your chosen Claude model(s) * GitLab OIDC configured in AWS with a role that trusts your GitLab project and refs * IAM role with Bedrock permissions (least privilege recommended) **Required CI/CD variables:** * `AWS_ROLE_TO_ASSUME`: ARN of the IAM role for Bedrock access * `AWS_REGION`: Bedrock region (for example, `us-west-2`) ```yaml theme={null} claude-bedrock: stage: ai image: node:24-alpine3.21 rules: - if: '$CI_PIPELINE_SOURCE == "web"' before_script: - apk add --no-cache bash curl jq git python3 py3-pip - pip install --no-cache-dir awscli - curl -fsSL https://claude.ai/install.sh | bash # Exchange GitLab OIDC token for AWS credentials - export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}" - if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi - > aws sts assume-role-with-web-identity --role-arn "$AWS_ROLE_TO_ASSUME" --role-session-name "gitlab-claude-$(date +%s)" --web-identity-token "file://$AWS_WEB_IDENTITY_TOKEN_FILE" --duration-seconds 3600 > /tmp/aws_creds.json - export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId /tmp/aws_creds.json)" - export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey /tmp/aws_creds.json)" - export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken /tmp/aws_creds.json)" script: - /bin/gitlab-mcp-server || true - > claude -p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}" --permission-mode acceptEdits --allowedTools "Bash Read Edit Write mcp__gitlab" --debug variables: AWS_REGION: "us-west-2" ``` Model IDs for Bedrock include region-specific prefixes and version suffixes (for example, `us.anthropic.claude-sonnet-4-5-20250929-v1:0`). Pass the desired model via your job configuration or prompt if your workflow supports it. ### Google Vertex AI job example (Workload Identity Federation) **Prerequisites:** * Vertex AI API enabled in your GCP project * Workload Identity Federation configured to trust GitLab OIDC * A service account with Vertex AI permissions **Required CI/CD variables:** * `GCP_WORKLOAD_IDENTITY_PROVIDER`: Full provider resource name * `GCP_SERVICE_ACCOUNT`: Service account email * `CLOUD_ML_REGION`: Vertex region (for example, `us-east5`) ```yaml theme={null} claude-vertex: stage: ai image: gcr.io/google.com/cloudsdktool/google-cloud-cli:slim rules: - if: '$CI_PIPELINE_SOURCE == "web"' before_script: - apt-get update && apt-get install -y git && apt-get clean - curl -fsSL https://claude.ai/install.sh | bash # Authenticate to Google Cloud via WIF (no downloaded keys) - > gcloud auth login --cred-file=<(cat < CLOUD_ML_REGION="${CLOUD_ML_REGION:-us-east5}" claude -p "${AI_FLOW_INPUT:-'Review and update code as requested'}" --permission-mode acceptEdits --allowedTools "Bash Read Edit Write mcp__gitlab" --debug variables: CLOUD_ML_REGION: "us-east5" ``` With Workload Identity Federation, you do not need to store service account keys. Use repository-specific trust conditions and least-privilege service accounts. ## Best practices ### CLAUDE.md configuration Create a `CLAUDE.md` file at the repository root to define coding standards, review criteria, and project-specific rules. Claude reads this file during runs and follows your conventions when proposing changes. ### Security considerations **Never commit API keys or cloud credentials to your repository**. Always use GitLab CI/CD variables: * Add `ANTHROPIC_API_KEY` as a masked variable (and protect it if needed) * Use provider-specific OIDC where possible (no long-lived keys) * Limit job permissions and network egress * Review Claude's MRs like any other contributor ### Optimizing performance * Keep `CLAUDE.md` focused and concise * Provide clear issue/MR descriptions to reduce iterations * Configure sensible job timeouts to avoid runaway runs * Cache npm and package installs in runners where possible ### CI costs When using Claude Code with GitLab CI/CD, be aware of associated costs: * **GitLab Runner time**: * Claude runs on your GitLab runners and consumes compute minutes * See your GitLab plan's runner billing for details * **API costs**: * Each Claude interaction consumes tokens based on prompt and response size * Token usage varies by task complexity and codebase size * See [Anthropic pricing](https://docs.claude.com/en/docs/about-claude/pricing) for details * **Cost optimization tips**: * Use specific `@claude` commands to reduce unnecessary turns * Set appropriate `max_turns` and job timeout values * Limit concurrency to control parallel runs ## Security and governance * Each job runs in an isolated container with restricted network access * Claude's changes flow through MRs so reviewers see every diff * Branch protection and approval rules apply to AI-generated code * Claude Code uses workspace-scoped permissions to constrain writes * Costs remain under your control because you bring your own provider credentials ## Troubleshooting ### Claude not responding to @claude commands * Verify your pipeline is being triggered (manually, MR event, or via a note event listener/webhook) * Ensure CI/CD variables (`ANTHROPIC_API_KEY` or cloud provider settings) are present and unmasked * Check that the comment contains `@claude` (not `/claude`) and that your mention trigger is configured ### Job can't write comments or open MRs * Ensure `CI_JOB_TOKEN` has sufficient permissions for the project, or use a Project Access Token with `api` scope * Check the `mcp__gitlab` tool is enabled in `--allowedTools` * Confirm the job runs in the context of the MR or has enough context via `AI_FLOW_*` variables ### Authentication errors * **For Claude API**: Confirm `ANTHROPIC_API_KEY` is valid and unexpired * **For Bedrock/Vertex**: Verify OIDC/WIF configuration, role impersonation, and secret names; confirm region and model availability ## Advanced configuration ### Common parameters and variables Claude Code supports these commonly used inputs: * `prompt` / `prompt_file`: Provide instructions inline (`-p`) or via a file * `max_turns`: Limit the number of back-and-forth iterations * `timeout_minutes`: Limit total execution time * `ANTHROPIC_API_KEY`: Required for the Claude API (not used for Bedrock/Vertex) * Provider-specific environment: `AWS_REGION`, project/region vars for Vertex Exact flags and parameters may vary by version of `@anthropic-ai/claude-code`. Run `claude --help` in your job to see supported options. ### Customizing Claude's behavior You can guide Claude in two primary ways: 1. **CLAUDE.md**: Define coding standards, security requirements, and project conventions. Claude reads this during runs and follows your rules. 2. **Custom prompts**: Pass task-specific instructions via `prompt`/`prompt_file` in the job. Use different prompts for different jobs (for example, review, implement, refactor). --- # Source: https://code.claude.com/docs/en/google-vertex-ai.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code on Google Vertex AI > Learn about configuring Claude Code through Google Vertex AI, including setup, IAM configuration, and troubleshooting. ## Prerequisites Before configuring Claude Code with Vertex AI, ensure you have: * A Google Cloud Platform (GCP) account with billing enabled * A GCP project with Vertex AI API enabled * Access to desired Claude models (for example, Claude Sonnet 4.5) * Google Cloud SDK (`gcloud`) installed and configured * Quota allocated in desired GCP region ## Region Configuration Claude Code can be used with both Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai) and regional endpoints. Vertex AI may not support the Claude Code default models on all regions. You may need to switch to a [supported region or model](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models). Vertex AI may not support the Claude Code default models on global endpoints. You may need to switch to a regional endpoint or [supported model](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models). ## Setup ### 1. Enable Vertex AI API Enable the Vertex AI API in your GCP project: ```bash theme={null} # Set your project ID gcloud config set project YOUR-PROJECT-ID # Enable Vertex AI API gcloud services enable aiplatform.googleapis.com ``` ### 2. Request model access Request access to Claude models in Vertex AI: 1. Navigate to the [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) 2. Search for "Claude" models 3. Request access to desired Claude models (for example, Claude Sonnet 4.5) 4. Wait for approval (may take 24-48 hours) ### 3. Configure GCP credentials Claude Code uses standard Google Cloud authentication. For more information, see [Google Cloud authentication documentation](https://cloud.google.com/docs/authentication). When authenticating, Claude Code will automatically use the project ID from the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable. To override this, set one of these environment variables: `GCLOUD_PROJECT`, `GOOGLE_CLOUD_PROJECT`, or `GOOGLE_APPLICATION_CREDENTIALS`. ### 4. Configure Claude Code Set the following environment variables: ```bash theme={null} # Enable Vertex AI integration export CLAUDE_CODE_USE_VERTEX=1 export CLOUD_ML_REGION=global export ANTHROPIC_VERTEX_PROJECT_ID=YOUR-PROJECT-ID # Optional: Disable prompt caching if needed export DISABLE_PROMPT_CACHING=1 # When CLOUD_ML_REGION=global, override region for unsupported models export VERTEX_REGION_CLAUDE_3_5_HAIKU=us-east5 # Optional: Override regions for other specific models export VERTEX_REGION_CLAUDE_3_5_SONNET=us-east5 export VERTEX_REGION_CLAUDE_3_7_SONNET=us-east5 export VERTEX_REGION_CLAUDE_4_0_OPUS=europe-west1 export VERTEX_REGION_CLAUDE_4_0_SONNET=us-east5 export VERTEX_REGION_CLAUDE_4_1_OPUS=europe-west1 ``` [Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) is automatically supported when you specify the `cache_control` ephemeral flag. To disable it, set `DISABLE_PROMPT_CACHING=1`. For heightened rate limits, contact Google Cloud support. When using Vertex AI, the `/login` and `/logout` commands are disabled since authentication is handled through Google Cloud credentials. ### 5. Model configuration Claude Code uses these default models for Vertex AI: | Model type | Default value | | :--------------- | :--------------------------- | | Primary model | `claude-sonnet-4-5@20250929` | | Small/fast model | `claude-haiku-4-5@20251001` | For Vertex AI users, Claude Code will not automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (for example, `claude-haiku-4-5@20251001`). To customize models: ```bash theme={null} export ANTHROPIC_MODEL='claude-opus-4-1@20250805' export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001' ``` ## IAM configuration Assign the required IAM permissions: The `roles/aiplatform.user` role includes the required permissions: * `aiplatform.endpoints.predict` - Required for model invocation and token counting For more restrictive permissions, create a custom role with only the permissions above. For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/docs/general/access-control). We recommend creating a dedicated GCP project for Claude Code to simplify cost tracking and access control. ## 1M token context window Claude Sonnet 4 and Sonnet 4.5 support the [1M token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window) on Vertex AI. The 1M token context window is currently in beta. To use the extended context window, include the `context-1m-2025-08-07` beta header in your Vertex AI requests. ## Troubleshooting If you encounter quota issues: * Check current quotas or request quota increase through [Cloud Console](https://cloud.google.com/docs/quotas/view-manage) If you encounter "model not found" 404 errors: * Confirm model is Enabled in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) * Verify you have access to the specified region * If using `CLOUD_ML_REGION=global`, check that your models support global endpoints in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) under "Supported features". For models that don't support global endpoints, either: * Specify a supported model via `ANTHROPIC_MODEL` or `ANTHROPIC_SMALL_FAST_MODEL`, or * Set a regional endpoint using `VERTEX_REGION_` environment variables If you encounter 429 errors: * For regional endpoints, ensure the primary model and small/fast model are supported in your selected region * Consider switching to `CLOUD_ML_REGION=global` for better availability ## Additional resources * [Vertex AI documentation](https://cloud.google.com/vertex-ai/docs) * [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) * [Vertex AI quotas and limits](https://cloud.google.com/vertex-ai/docs/quotas) --- # Source: https://code.claude.com/docs/en/headless.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Run Claude Code programmatically > Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript. The [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) gives you the same tools, agent loop, and context management that power Claude Code. It's available as a CLI for scripts and CI/CD, or as [Python](https://platform.claude.com/docs/en/agent-sdk/python) and [TypeScript](https://platform.claude.com/docs/en/agent-sdk/typescript) packages for full programmatic control. The CLI was previously called "headless mode." The `-p` flag and all CLI options work the same way. To run Claude Code programmatically from the CLI, pass `-p` with your prompt and any [CLI options](/en/cli-reference): ```bash theme={null} claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash" ``` This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview). ## Basic usage Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. All [CLI options](/en/cli-reference) work with `-p`, including: * `--continue` for [continuing conversations](#continue-conversations) * `--allowedTools` for [auto-approving tools](#auto-approve-tools) * `--output-format` for [structured output](#get-structured-output) This example asks Claude a question about your codebase and prints the response: ```bash theme={null} claude -p "What does the auth module do?" ``` ## Examples These examples highlight common CLI patterns. ### Get structured output Use `--output-format` to control how responses are returned: * `text` (default): plain text output * `json`: structured JSON with result, session ID, and metadata * `stream-json`: newline-delimited JSON for real-time streaming This example returns a project summary as JSON with session metadata, with the text result in the `result` field: ```bash theme={null} claude -p "Summarize this project" --output-format json ``` To get output conforming to a specific schema, use `--output-format json` with `--json-schema` and a [JSON Schema](https://json-schema.org/) definition. The response includes metadata about the request (session ID, usage, etc.) with the structured output in the `structured_output` field. This example extracts function names and returns them as an array of strings: ```bash theme={null} claude -p "Extract the main function names from auth.py" \ --output-format json \ --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' ``` Use a tool like [jq](https://jqlang.github.io/jq/) to parse the response and extract specific fields: ```bash theme={null} # Extract the text result claude -p "Summarize this project" --output-format json | jq -r '.result' # Extract structured output claude -p "Extract function names from auth.py" \ --output-format json \ --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \ | jq '.structured_output' ``` ### Stream responses Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they're generated. Each line is a JSON object representing an event: ```bash theme={null} claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages ``` The following example uses [jq](https://jqlang.github.io/jq/) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: ```bash theme={null} claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text' ``` For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](https://platform.claude.com/docs/en/agent-sdk/streaming-output) in the Agent SDK documentation. ### Auto-approve tools Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission: ```bash theme={null} claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" ``` ### Create a commit This example reviews staged changes and creates a commit with an appropriate message: ```bash theme={null} claude -p "Look at my staged changes and create an appropriate commit" \ --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)" ``` The `--allowedTools` flag uses [permission rule syntax](/en/settings#permission-rule-syntax). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. User-invoked [skills](/en/skills) like `/commit` and [built-in commands](/en/interactive-mode#built-in-commands) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead. ### Customize the system prompt Use `--append-system-prompt` to add instructions while keeping Claude Code's default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities: ```bash theme={null} gh pr diff "$1" | claude -p \ --append-system-prompt "You are a security engineer. Review for vulnerabilities." \ --output-format json ``` See [system prompt flags](/en/cli-reference#system-prompt-flags) for more options including `--system-prompt` to fully replace the default prompt. ### Continue conversations Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. This example runs a review, then sends follow-up prompts: ```bash theme={null} # First request claude -p "Review this codebase for performance issues" # Continue the most recent conversation claude -p "Now focus on the database queries" --continue claude -p "Generate a summary of all issues found" --continue ``` If you're running multiple conversations, capture the session ID to resume a specific one: ```bash theme={null} session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id') claude -p "Continue that review" --resume "$session_id" ``` ## Next steps Build your first agent with Python or TypeScript Explore all CLI flags and options Use the Agent SDK in GitHub workflows Use the Agent SDK in GitLab pipelines --- # Source: https://code.claude.com/docs/en/hooks-guide.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Automate workflows with hooks > Run shell commands automatically when Claude Code edits files, finishes tasks, or needs input. Format code, send notifications, validate commands, and enforce project rules. Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. They provide deterministic control over Claude Code's behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools. For decisions that require judgment rather than deterministic rules, you can also use [prompt-based hooks](#prompt-based-hooks) or [agent-based hooks](#agent-based-hooks) that use a Claude model to evaluate conditions. For other ways to extend Claude Code, see [skills](/en/skills) for giving Claude additional instructions and executable commands, [subagents](/en/sub-agents) for running tasks in isolated contexts, and [plugins](/en/plugins) for packaging extensions to share across projects. This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](/en/hooks). ## Set up your first hook The fastest way to create a hook is through the `/hooks` interactive menu in Claude Code. This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal. Type `/hooks` in the Claude Code CLI. You'll see a list of all available hook events, plus an option to disable all hooks. Each event corresponds to a point in Claude's lifecycle where you can run custom code. Select `Notification` to create a hook that fires when Claude needs your attention. The menu shows a list of matchers, which filter when the hook fires. Set the matcher to `*` to fire on all notification types. You can narrow it later by changing the matcher to a specific value like `permission_prompt` or `idle_prompt`. Select `+ Add new hook…`. The menu prompts you for a shell command to run when the event fires. Hooks run any shell command you provide, so you can use your platform's built-in notification tool. Copy the command for your OS: Uses [`osascript`](https://ss64.com/mac/osascript.html) to trigger a native macOS notification through AppleScript: ``` osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"' ``` Uses `notify-send`, which is pre-installed on most Linux desktops with a notification daemon: ``` notify-send 'Claude Code' 'Claude Code needs your attention' ``` Uses PowerShell to show a native message box through .NET's Windows Forms: ``` powershell.exe -Command "[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')" ``` The menu asks where to save the hook configuration. Select `User settings` to store it in `~/.claude/settings.json`, which applies the hook to all your projects. You could also choose `Project settings` to scope it to the current project. See [Configure hook location](#configure-hook-location) for all available scopes. Press `Esc` to return to the CLI. Ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification. ## What you can automate Hooks let you run code at key points in Claude Code's lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](/en/hooks#hook-lifecycle). Each example includes a ready-to-use configuration block that you add to a [settings file](#configure-hook-location). The most common patterns: * [Get notified when Claude needs input](#get-notified-when-claude-needs-input) * [Auto-format code after edits](#auto-format-code-after-edits) * [Block edits to protected files](#block-edits-to-protected-files) * [Re-inject context after compaction](#re-inject-context-after-compaction) ### Get notified when Claude needs input Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which fires when Claude is waiting for input or permission. Each tab below uses the platform's native notification command. Add this to `~/.claude/settings.json`, or use the [interactive walkthrough](#set-up-your-first-hook) above to configure it with `/hooks`: ```json theme={null} { "hooks": { "Notification": [ { "matcher": "", "hooks": [ { "type": "command", "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'" } ] } ] } } ``` ```json theme={null} { "hooks": { "Notification": [ { "matcher": "", "hooks": [ { "type": "command", "command": "notify-send 'Claude Code' 'Claude Code needs your attention'" } ] } ] } } ``` ```json theme={null} { "hooks": { "Notification": [ { "matcher": "", "hooks": [ { "type": "command", "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\"" } ] } ] } } ``` ### Auto-format code after edits Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](https://jqlang.github.io/jq/) and passes it to Prettier. Add this to `.claude/settings.json` in your project root: ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" } ] } ] } } ``` The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` (macOS), `apt-get install jq` (Debian/Ubuntu), or see [`jq` downloads](https://jqlang.github.io/jq/download/). ### Block edits to protected files Prevent Claude from modifying sensitive files like `.env`, `package-lock.json`, or anything in `.git/`. Claude receives feedback explaining why the edit was blocked, so it can adjust its approach. This example uses a separate script file that the hook calls. The script checks the target file path against a list of protected patterns and exits with code 2 to block the edit. Save this to `.claude/hooks/protect-files.sh`: ```bash theme={null} #!/bin/bash # protect-files.sh INPUT=$(cat) FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/") for pattern in "${PROTECTED_PATTERNS[@]}"; do if [[ "$FILE_PATH" == *"$pattern"* ]]; then echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2 exit 2 fi done exit 0 ``` Hook scripts must be executable for Claude Code to run them: ```bash theme={null} chmod +x .claude/hooks/protect-files.sh ``` Add a `PreToolUse` hook to `.claude/settings.json` that runs the script before any `Edit` or `Write` tool call: ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" } ] } ] } } ``` ### Re-inject context after compaction When Claude's context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction. Any text your command writes to stdout is added to Claude's context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root: ```json theme={null} { "hooks": { "SessionStart": [ { "matcher": "compact", "hooks": [ { "type": "command", "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'" } ] } ] } } ``` You can replace the `echo` with any command that produces dynamic output, like `git log --oneline -5` to show recent commits. For injecting context on every session start, consider using [CLAUDE.md](/en/memory) instead. For environment variables, see [`CLAUDE_ENV_FILE`](/en/hooks#persist-environment-variables) in the reference. ## How hooks work Hook events fire at specific lifecycle points in Claude Code. When an event fires, all matching hooks run in parallel, and identical hook commands are automatically deduplicated. The table below shows each event and when it triggers: | Event | When it fires | | :------------------- | :--------------------------------------------------- | | `SessionStart` | When a session begins or resumes | | `UserPromptSubmit` | When you submit a prompt, before Claude processes it | | `PreToolUse` | Before a tool call executes. Can block it | | `PermissionRequest` | When a permission dialog appears | | `PostToolUse` | After a tool call succeeds | | `PostToolUseFailure` | After a tool call fails | | `Notification` | When Claude Code sends a notification | | `SubagentStart` | When a subagent is spawned | | `SubagentStop` | When a subagent finishes | | `Stop` | When Claude finishes responding | | `PreCompact` | Before context compaction | | `SessionEnd` | When a session terminates | Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Two other options use a Claude model to make decisions: `"type": "prompt"` for single-turn evaluation and `"type": "agent"` for multi-turn verification with tool access. See [Prompt-based hooks](#prompt-based-hooks) and [Agent-based hooks](#agent-based-hooks) for details. ### Read input and return output Hooks communicate with Claude Code through stdin, stdout, stderr, and exit codes. When an event fires, Claude Code passes event-specific data as JSON to your script's stdin. Your script reads that data, does its work, and tells Claude Code what to do next via the exit code. #### Hook input Every event includes common fields like `session_id` and `cwd`, but each event type adds different data. For example, when Claude runs a Bash command, a `PreToolUse` hook receives something like this on stdin: ```json theme={null} { "session_id": "abc123", // unique ID for this session "cwd": "/Users/sarah/myproject", // working directory when the event fired "hook_event_name": "PreToolUse", // which event triggered this hook "tool_name": "Bash", // the tool Claude is about to use "tool_input": { // the arguments Claude passed to the tool "command": "npm test" // for Bash, this is the shell command } } ``` Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get the `source` (startup, resume, compact), and so on. See [Common input fields](/en/hooks#common-input-fields) in the reference for shared fields, and each event's section for event-specific schemas. #### Hook output Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. For example, a `PreToolUse` hook that wants to block a command: ```bash theme={null} #!/bin/bash INPUT=$(cat) COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command') if echo "$COMMAND" | grep -q "drop table"; then echo "Blocked: dropping tables is not allowed" >&2 # stderr becomes Claude's feedback exit 2 # exit 2 = block the action fi exit 0 # exit 0 = let it proceed ``` The exit code determines what happens next: * **Exit 0**: the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude's context. * **Exit 2**: the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. * **Any other exit code**: the action proceeds. Stderr is logged but not shown to Claude. Toggle verbose mode with `Ctrl+O` to see these messages in the transcript. #### Structured JSON output Exit codes give you two options: allow or block. For more control, exit 0 and print a JSON object to stdout instead. Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Don't mix them: Claude Code ignores JSON when you exit 2. For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval: ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Use rg instead of grep for better performance" } } ``` Claude Code reads `permissionDecision` and cancels the tool call, then feeds `permissionDecisionReason` back to Claude as feedback. These three options are specific to `PreToolUse`: * `"allow"`: proceed without showing a permission prompt * `"deny"`: cancel the tool call and send the reason to Claude * `"ask"`: show the permission prompt to the user as normal Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](/en/hooks#decision-control) in the reference for a full breakdown by event. For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude's context. Prompt-based hooks (`type: "prompt"`) handle output differently: see [Prompt-based hooks](#prompt-based-hooks). ### Filter hooks with matchers Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits (not after every tool call), add a matcher to your `PostToolUse` hook: ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "prettier --write ..." } ] } ] } } ``` The `"Edit|Write"` matcher is a regex pattern that matches the tool name. The hook only fires when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. Each event type matches on a specific field. Matchers support exact strings and regex patterns: | Event | What the matcher filters | Example matcher values | | :--------------------------------------------------------------------- | :------------------------ | :----------------------------------------------------------------------- | | `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` | | `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` | | `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `other` | | `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` | | `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names | | `PreCompact` | what triggered compaction | `manual`, `auto` | | `UserPromptSubmit`, `Stop` | no matcher support | always fires on every occurrence | | `SubagentStop` | agent type | same values as `SubagentStart` | A few more examples showing matchers on different event types: Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts just the command string, which `>>` appends to the log file: ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt" } ] } ] } } ``` MCP tools use a different naming convention than built-in tools: `mcp____`, where `` is the MCP server name and `` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](/en/hooks#match-mcp-tools) in the reference for the full list of examples. The command below extracts the tool name from the hook's JSON input with `jq` and writes it to stderr, where it shows up in verbose mode (`Ctrl+O`): ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": "mcp__github__.*", "hooks": [ { "type": "command", "command": "echo \"GitHub tool called: $(jq -r '.tool_name')\" >&2" } ] } ] } } ``` The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on `clear` (when you run `/clear`), not on normal exits: ```json theme={null} { "hooks": { "SessionEnd": [ { "matcher": "clear", "hooks": [ { "type": "command", "command": "rm -f /tmp/claude-scratch-*.txt" } ] } ] } } ``` For full matcher syntax, see the [Hooks reference](/en/hooks#configuration). ### Configure hook location Where you add a hook determines its scope: | Location | Scope | Shareable | | :--------------------------------------------------------- | :--------------------------------- | :--------------------------------- | | `~/.claude/settings.json` | All your projects | No, local to your machine | | `.claude/settings.json` | Single project | Yes, can be committed to the repo | | `.claude/settings.local.json` | Single project | No, gitignored | | Managed policy settings | Organization-wide | Yes, admin-controlled | | [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin | | [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the skill or agent is active | Yes, defined in the component file | You can also use the [`/hooks` menu](/en/hooks#the-hooks-menu) in Claude Code to add, delete, and view hooks interactively. To disable all hooks at once, use the toggle at the bottom of the `/hooks` menu or set `"disableAllHooks": true` in your settings file. Hooks added through the `/hooks` menu take effect immediately. If you edit settings files directly while Claude Code is running, the changes won't take effect until you review them in the `/hooks` menu or restart your session. ## Prompt-based hooks For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook's input data to a Claude model (Haiku by default) to make the decision. You can specify a different model with the `model` field if you need more capability. The model's only job is to return a yes/no decision as JSON: * `"ok": true`: the action proceeds * `"ok": false`: the action is blocked. The model's `"reason"` is fed back to Claude so it can adjust. This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false`, Claude keeps working and uses the `reason` as its next instruction: ```json theme={null} { "hooks": { "Stop": [ { "hooks": [ { "type": "prompt", "prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}." } ] } ] } } ``` For full configuration options, see [Prompt-based hooks](/en/hooks#prompt-based-hooks) in the reference. ## Agent-based hooks When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision. Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. This example verifies that tests pass before allowing Claude to stop: ```json theme={null} { "hooks": { "Stop": [ { "hooks": [ { "type": "agent", "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS", "timeout": 120 } ] } ] } } ``` Use prompt hooks when the hook input data alone is enough to make a decision. Use agent hooks when you need to verify something against the actual state of the codebase. For full configuration options, see [Agent-based hooks](/en/hooks#agent-based-hooks) in the reference. ## Limitations and troubleshooting ### Limitations * Hooks communicate through stdout, stderr, and exit codes only. They cannot trigger slash commands or tool calls directly. * Hook timeout is 10 minutes by default, configurable per hook with the `timeout` field (in seconds). * `PostToolUse` hooks cannot undo actions since the tool has already executed. * `PermissionRequest` hooks do not fire in [non-interactive mode](/en/headless) (`-p`). Use `PreToolUse` hooks for automated permission decisions. * `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts. ### Hook not firing The hook is configured but never executes. * Run `/hooks` and confirm the hook appears under the correct event * Check that the matcher pattern matches the tool name exactly (matchers are case-sensitive) * Verify you're triggering the right event type (e.g., `PreToolUse` fires before tool execution, `PostToolUse` fires after) * If using `PermissionRequest` hooks in non-interactive mode (`-p`), switch to `PreToolUse` instead ### Hook error in output You see a message like "PreToolUse hook error: ..." in the transcript. * Your script exited with a non-zero code unexpectedly. Test it manually by piping sample JSON: ```bash theme={null} echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh echo $? # Check the exit code ``` * If you see "command not found", use absolute paths or `$CLAUDE_PROJECT_DIR` to reference scripts * If you see "jq: command not found", install `jq` or use Python/Node.js for JSON parsing * If the script isn't running at all, make it executable: `chmod +x ./my-hook.sh` ### `/hooks` shows no hooks configured You edited a settings file but the hooks don't appear in the menu. * Restart your session or open `/hooks` to reload. Hooks added through the `/hooks` menu take effect immediately, but manual file edits require a reload. * Verify your JSON is valid (trailing commas and comments are not allowed) * Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks ### Stop hook runs forever Claude keeps working in an infinite loop instead of stopping. Your Stop hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it's `true`: ```bash theme={null} #!/bin/bash INPUT=$(cat) if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then exit 0 # Allow Claude to stop fi # ... rest of your hook logic ``` ### JSON validation failed Claude Code shows a JSON parsing error even though your hook script outputs valid JSON. When Claude Code runs a hook, it spawns a shell that sources your profile (`~/.zshrc` or `~/.bashrc`). If your profile contains unconditional `echo` statements, that output gets prepended to your hook's JSON: ``` Shell ready on arm64 {"decision": "block", "reason": "Not allowed"} ``` Claude Code tries to parse this as JSON and fails. To fix this, wrap echo statements in your shell profile so they only run in interactive shells: ```bash theme={null} # In ~/.zshrc or ~/.bashrc if [[ $- == *i* ]]; then echo "Shell ready" fi ``` The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped. ### Debug techniques Toggle verbose mode with `Ctrl+O` to see hook output in the transcript, or run `claude --debug` for full execution details including which hooks matched and their exit codes. ## Learn more * [Hooks reference](/en/hooks): full event schemas, JSON output format, async hooks, and MCP tool hooks * [Security considerations](/en/hooks#security-considerations): review before deploying hooks in shared or production environments * [Bash command validator example](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py): complete reference implementation --- # Source: https://code.claude.com/docs/en/hooks.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Hooks reference > Reference for Claude Code hook events, configuration schema, JSON input/output formats, exit codes, async hooks, prompt hooks, and MCP tool hooks. For a quickstart guide with examples, see [Automate workflows with hooks](/en/hooks-guide). Hooks are user-defined shell commands or LLM prompts that execute automatically at specific points in Claude Code's lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks and MCP tool hooks. If you're setting up hooks for the first time, start with the [guide](/en/hooks-guide) instead. ## Hook lifecycle Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, this arrives on stdin. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:
Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop to SessionEnd
The table below summarizes when each event fires. The [Hook events](#hook-events) section documents the full input schema and decision control options for each one. | Event | When it fires | | :------------------- | :--------------------------------------------------- | | `SessionStart` | When a session begins or resumes | | `UserPromptSubmit` | When you submit a prompt, before Claude processes it | | `PreToolUse` | Before a tool call executes. Can block it | | `PermissionRequest` | When a permission dialog appears | | `PostToolUse` | After a tool call succeeds | | `PostToolUseFailure` | After a tool call fails | | `Notification` | When Claude Code sends a notification | | `SubagentStart` | When a subagent is spawned | | `SubagentStop` | When a subagent finishes | | `Stop` | When Claude finishes responding | | `PreCompact` | Before context compaction | | `SessionEnd` | When a session terminates | ### How a hook resolves To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The hook runs `block-rm.sh` before every Bash tool call: ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": ".claude/hooks/block-rm.sh" } ] } ] } } ``` The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`: ```bash theme={null} #!/bin/bash # .claude/hooks/block-rm.sh COMMAND=$(jq -r '.tool_input.command') if echo "$COMMAND" | grep -q 'rm -rf'; then jq -n '{ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: "Destructive command blocked by hook" } }' else exit 0 # allow the command fi ``` Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens: Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook: ```json theme={null} { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... } ``` The matcher `"Bash"` matches the tool name, so `block-rm.sh` runs. If you omit the matcher or use `"*"`, the hook runs on every occurrence of the event. Hooks only skip when a matcher is defined and doesn't match. The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout: ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Destructive command blocked by hook" } } ``` If the command had been safe (like `npm test`), the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action. Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason. The [Configuration](#configuration) section below documents the full schema, and each [hook event](#hook-events) section documents what input your command receives and what output it can return. ## Configuration Hooks are defined in JSON settings files. The configuration has three levels of nesting: 1. Choose a [hook event](#hook-events) to respond to, like `PreToolUse` or `Stop` 2. Add a [matcher group](#matcher-patterns) to filter when it fires, like "only for the Bash tool" 3. Define one or more [hook handlers](#hook-handler-fields) to run when matched See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example. This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, prompt, or agent that runs. "Hook" on its own refers to the general feature. ### Hook locations Where you define a hook determines its scope: | Location | Scope | Shareable | | :--------------------------------------------------------- | :---------------------------- | :--------------------------------- | | `~/.claude/settings.json` | All your projects | No, local to your machine | | `.claude/settings.json` | Single project | Yes, can be committed to the repo | | `.claude/settings.local.json` | Single project | No, gitignored | | Managed policy settings | Organization-wide | Yes, admin-controlled | | [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin | | [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file | For details on settings file resolution, see [settings](/en/settings). Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](/en/settings#hook-configuration). ### Matcher patterns The `matcher` field is a regex string that filters when hooks fire. Use `"*"`, `""`, or omit `matcher` entirely to match all occurrences. Each event type matches on a different field: | Event | What the matcher filters | Example matcher values | | :--------------------------------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------- | | `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` | | `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` | | `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` | | `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` | | `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names | | `PreCompact` | what triggered compaction | `manual`, `auto` | | `SubagentStop` | agent type | same values as `SubagentStart` | | `UserPromptSubmit`, `Stop` | no matcher support | always fires on every occurrence | The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file: ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "/path/to/lint-check.sh" } ] } ] } } ``` `UserPromptSubmit` and `Stop` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. #### Match MCP tools [MCP](/en/mcp) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`), so you can match them the same way you match any other tool name. MCP tools follow the naming pattern `mcp____`, for example: * `mcp__memory__create_entities`: Memory server's create entities tool * `mcp__filesystem__read_file`: Filesystem server's read file tool * `mcp__github__search_repositories`: GitHub server's search tool Use regex patterns to target specific MCP tools or groups of tools: * `mcp__memory__.*` matches all tools from the `memory` server * `mcp__.*__write.*` matches any tool containing "write" from any server This example logs all memory server operations and validates write operations from any MCP server: ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": "mcp__memory__.*", "hooks": [ { "type": "command", "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log" } ] }, { "matcher": "mcp__.*__write.*", "hooks": [ { "type": "command", "command": "/home/user/scripts/validate-mcp-write.py" } ] } ] } } ``` ### Hook handler fields Each object in the inner `hooks` array is a hook handler: the shell command, LLM prompt, or agent that runs when the matcher matches. There are three types: * **[Command hooks](#command-hook-fields)** (`type: "command"`): run a shell command. Your script receives the event's [JSON input](#hook-input-and-output) on stdin and communicates results back through exit codes and stdout. * **[Prompt hooks](#prompt-and-agent-hook-fields)** (`type: "prompt"`): send a prompt to a Claude model for single-turn evaluation. The model returns a yes/no decision as JSON. See [Prompt-based hooks](#prompt-based-hooks). * **[Agent hooks](#prompt-and-agent-hook-fields)** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. See [Agent-based hooks](#agent-based-hooks). #### Common fields These fields apply to all hook types: | Field | Required | Description | | :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | yes | `"command"`, `"prompt"`, or `"agent"` | | `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent | | `statusMessage` | no | Custom spinner message displayed while the hook runs | | `once` | no | If `true`, runs only once per session then is removed. Skills only, not agents. See [Hooks in skills and agents](#hooks-in-skills-and-agents) | #### Command hook fields In addition to the [common fields](#common-fields), command hooks accept these fields: | Field | Required | Description | | :-------- | :------- | :------------------------------------------------------------------------------------------------------------------ | | `command` | yes | Shell command to execute | | `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) | #### Prompt and agent hook fields In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields: | Field | Required | Description | | :------- | :------- | :------------------------------------------------------------------------------------------ | | `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON | | `model` | no | Model to use for evaluation. Defaults to a fast model | All matching hooks run in parallel, and identical handlers are deduplicated automatically. Handlers run in the current directory with Claude Code's environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI. ### Reference scripts by path Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs: * `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces. * `${CLAUDE_PLUGIN_ROOT}`: the plugin's root directory, for scripts bundled with a [plugin](/en/plugins). This example uses `$CLAUDE_PROJECT_DIR` to run a style checker from the project's `.claude/hooks/` directory after any `Write` or `Edit` tool call: ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh" } ] } ] } } ``` Define plugin hooks in `hooks/hooks.json` with an optional top-level `description` field. When a plugin is enabled, its hooks merge with your user and project hooks. This example runs a formatting script bundled with the plugin: ```json theme={null} { "description": "Automatic code formatting", "hooks": { "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh", "timeout": 30 } ] } ] } } ``` See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks. ### Hooks in skills and agents In addition to settings files and plugins, hooks can be defined directly in [skills](/en/skills) and [subagents](/en/sub-agents) using frontmatter. These hooks are scoped to the component's lifecycle and only run when that component is active. All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes. Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes. This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command: ```yaml theme={null} --- name: secure-operations description: Perform operations with security checks hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/security-check.sh" --- ``` Agents use the same format in their YAML frontmatter. ### The `/hooks` menu Type `/hooks` in Claude Code to open the interactive hooks manager, where you can view, add, and delete hooks without editing settings files directly. For a step-by-step walkthrough, see [Set up your first hook](/en/hooks-guide#set-up-your-first-hook) in the guide. Each hook in the menu is labeled with a bracket prefix indicating its source: * `[User]`: from `~/.claude/settings.json` * `[Project]`: from `.claude/settings.json` * `[Local]`: from `.claude/settings.local.json` * `[Plugin]`: from a plugin's `hooks/hooks.json`, read-only ### Disable or remove hooks To remove a hook, delete its entry from the settings JSON file, or use the `/hooks` menu and select the hook to delete it. To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file or use the toggle in the `/hooks` menu. There is no way to disable an individual hook while keeping it in the configuration. Direct edits to hooks in settings files don't take effect immediately. Claude Code captures a snapshot of hooks at startup and uses it throughout the session. This prevents malicious or accidental hook modifications from taking effect mid-session without your review. If hooks are modified externally, Claude Code warns you and requires review in the `/hooks` menu before changes apply. ## Hook input and output Hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. This section covers fields and behavior common to all events. Each event's section under [Hook events](#hook-events) includes its specific input schema and decision control options. ### Common input fields All hook events receive these fields via stdin as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section: | Field | Description | | :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- | | `session_id` | Current session identifier | | `transcript_path` | Path to conversation JSON | | `cwd` | Current working directory when the hook is invoked | | `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` | | `hook_event_name` | Name of the event that fired | For example, a `PreToolUse` hook for a Bash command receives this on stdin: ```json theme={null} { "session_id": "abc123", "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl", "cwd": "/home/user/my-project", "permission_mode": "default", "hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": { "command": "npm test" } } ``` The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event. ### Exit code output The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for [JSON output fields](#json-output). JSON output is only processed on exit 0. For most events, stdout is only shown in verbose mode (`Ctrl+O`). The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on. **Exit 2** means a blocking error. Claude Code ignores stdout and any JSON in it. Instead, stderr text is fed back to Claude as an error message. The effect depends on the event: `PreToolUse` blocks the tool call, `UserPromptSubmit` rejects the prompt, and so on. See [exit code 2 behavior](#exit-code-2-behavior-per-event) for the full list. **Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues. For example, a hook command script that blocks dangerous Bash commands: ```bash theme={null} #!/bin/bash # Reads JSON input from stdin, checks the command command=$(jq -r '.tool_input.command' < /dev/stdin) if [[ "$command" == rm* ]]; then echo "Blocked: rm commands are not allowed" >&2 exit 2 # Blocking error: tool call is prevented fi exit 0 # Success: tool call proceeds ``` #### Exit code 2 behavior per event Exit code 2 is the way a hook signals "stop, don't do this." The effect depends on the event, because some events represent actions that can be blocked (like a tool call that hasn't happened yet) and others represent things that already happened or can't be prevented. | Hook event | Can block? | What happens on exit 2 | | :------------------- | :--------- | :-------------------------------------------------------- | | `PreToolUse` | Yes | Blocks the tool call | | `PermissionRequest` | Yes | Denies the permission | | `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt | | `Stop` | Yes | Prevents Claude from stopping, continues the conversation | | `SubagentStop` | Yes | Prevents the subagent from stopping | | `PostToolUse` | No | Shows stderr to Claude (tool already ran) | | `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) | | `Notification` | No | Shows stderr to user only | | `SubagentStart` | No | Shows stderr to user only | | `SessionStart` | No | Shows stderr to user only | | `SessionEnd` | No | Shows stderr to user only | | `PreCompact` | No | Shows stderr to user only | ### JSON output Exit codes let you allow or block, but JSON output gives you finer-grained control. Instead of exiting with code 2 to block, exit 0 and print a JSON object to stdout. Claude Code reads specific fields from that JSON to control behavior, including [decision control](#decision-control) for blocking, allowing, or escalating to the user. You must choose one approach per hook, not both: either use exit codes alone for signaling, or exit 0 and print JSON for structured control. Claude Code only processes JSON on exit 0. If you exit 2, any JSON is ignored. Your hook's stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](/en/hooks-guide#json-validation-failed) in the troubleshooting guide. The JSON object supports three kinds of fields: * **Universal fields** like `continue` work across all events. These are listed in the table below. * **Top-level `decision` and `reason`** are used by some events to block or provide feedback. * **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name. | Field | Default | Description | | :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- | | `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields | | `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude | | `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output | | `systemMessage` | none | Warning message shown to the user | To stop Claude entirely regardless of event type: ```json theme={null} { "continue": false, "stopReason": "Build failed, fix errors before continuing" } ``` #### Decision control Not every event supports blocking or controlling behavior through JSON. The events that do each use a different set of fields to express that decision. Use this table as a quick reference before writing a hook: | Events | Decision pattern | Key fields | | :-------------------------------------------------------------------- | :------------------- | :---------------------------------------------------------------- | | UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop | Top-level `decision` | `decision: "block"`, `reason` | | PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` | | PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) | Here are examples of each pattern in action: Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, and `SubagentStop`. The only value is `"block"` — to allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all: ```json theme={null} { "decision": "block", "reason": "Test suite must pass before proceeding" } ``` Uses `hookSpecificOutput` for richer control: allow, deny, or escalate to the user. You can also modify tool input before it runs or inject additional context for Claude. See [PreToolUse decision control](#pretooluse-decision-control) for the full set of options. ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Database writes are not allowed" } } ``` Uses `hookSpecificOutput` to allow or deny a permission request on behalf of the user. When allowing, you can also modify the tool's input or apply permission rules so the user isn't prompted again. See [PermissionRequest decision control](#permissionrequest-decision-control) for the full set of options. ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PermissionRequest", "decision": { "behavior": "allow", "updatedInput": { "command": "npm run lint" } } } } ``` For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](/en/hooks-guide#what-you-can-automate) in the guide and the [Bash command validator reference implementation](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py). ## Hook events Each event corresponds to a point in Claude Code's lifecycle where hooks can run. The sections below are ordered to match the lifecycle: from session setup through the agentic loop to session end. Each section describes when the event fires, what matchers it supports, the JSON input it receives, and how to control behavior through output. ### SessionStart Runs when Claude Code starts a new session or resumes an existing session. Useful for loading development context like existing issues or recent changes to your codebase, or setting up environment variables. For static context that does not require a script, use [CLAUDE.md](/en/memory) instead. SessionStart runs on every session, so keep these hooks fast. The matcher value corresponds to how the session was initiated: | Matcher | When it fires | | :-------- | :------------------------------------- | | `startup` | New session | | `resume` | `--resume`, `--continue`, or `/resume` | | `clear` | `/clear` | | `compact` | Auto or manual compaction | #### SessionStart input In addition to the [common input fields](#common-input-fields), SessionStart hooks receive `source`, `model`, and optionally `agent_type`. The `source` field indicates how the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction. The `model` field contains the model identifier. If you start Claude Code with `claude --agent `, an `agent_type` field contains the agent name. ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "SessionStart", "source": "startup", "model": "claude-sonnet-4-5-20250929" } ``` #### SessionStart decision control Any text your hook script prints to stdout is added as context for Claude. In addition to the [JSON output fields](#json-output) available to all hooks, you can return these event-specific fields: | Field | Description | | :------------------ | :------------------------------------------------------------------------ | | `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated | ```json theme={null} { "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": "My additional context here" } } ``` #### Persist environment variables SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent Bash commands. To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks: ```bash theme={null} #!/bin/bash if [ -n "$CLAUDE_ENV_FILE" ]; then echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE" echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE" echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE" fi exit 0 ``` To capture all environment changes from setup commands, compare the exported variables before and after: ```bash theme={null} #!/bin/bash ENV_BEFORE=$(export -p | sort) # Run your setup commands that modify the environment source ~/.nvm/nvm.sh nvm use 20 if [ -n "$CLAUDE_ENV_FILE" ]; then ENV_AFTER=$(export -p | sort) comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE" fi exit 0 ``` Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session. `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable. ### UserPromptSubmit Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. #### UserPromptSubmit input In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted. ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "UserPromptSubmit", "prompt": "Write a function to calculate the factorial of a number" } ``` #### UserPromptSubmit decision control `UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available. There are two ways to add context to the conversation on exit code 0: * **Plain text stdout**: any non-JSON text written to stdout is added as context * **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely. To block a prompt, return a JSON object with `decision` set to `"block"`: | Field | Description | | :------------------ | :----------------------------------------------------------------------------------------------------------------- | | `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed | | `reason` | Shown to the user when `decision` is `"block"`. Not added to context | | `additionalContext` | String added to Claude's context | ```json theme={null} { "decision": "block", "reason": "Explanation for decision", "hookSpecificOutput": { "hookEventName": "UserPromptSubmit", "additionalContext": "My additional context here" } } ``` The JSON format isn't required for simple use cases. To add context, you can print plain text to stdout with exit code 0. Use JSON when you need to block prompts or want more structured control. ### PreToolUse Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Task`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools). Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool. #### PreToolUse input In addition to the [common input fields](#common-input-fields), PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. The `tool_input` fields depend on the tool: ##### Bash Executes shell commands. | Field | Type | Example | Description | | :------------------ | :------ | :----------------- | :-------------------------------------------- | | `command` | string | `"npm test"` | The shell command to execute | | `description` | string | `"Run test suite"` | Optional description of what the command does | | `timeout` | number | `120000` | Optional timeout in milliseconds | | `run_in_background` | boolean | `false` | Whether to run the command in background | ##### Write Creates or overwrites a file. | Field | Type | Example | Description | | :---------- | :----- | :-------------------- | :--------------------------------- | | `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write | | `content` | string | `"file content"` | Content to write to the file | ##### Edit Replaces a string in an existing file. | Field | Type | Example | Description | | :------------ | :------ | :-------------------- | :--------------------------------- | | `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit | | `old_string` | string | `"original text"` | Text to find and replace | | `new_string` | string | `"replacement text"` | Replacement text | | `replace_all` | boolean | `false` | Whether to replace all occurrences | ##### Read Reads file contents. | Field | Type | Example | Description | | :---------- | :----- | :-------------------- | :----------------------------------------- | | `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read | | `offset` | number | `10` | Optional line number to start reading from | | `limit` | number | `50` | Optional number of lines to read | ##### Glob Finds files matching a glob pattern. | Field | Type | Example | Description | | :-------- | :----- | :--------------- | :--------------------------------------------------------------------- | | `pattern` | string | `"**/*.ts"` | Glob pattern to match files against | | `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory | ##### Grep Searches file contents with regular expressions. | Field | Type | Example | Description | | :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ | | `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for | | `path` | string | `"/path/to/dir"` | Optional file or directory to search in | | `glob` | string | `"*.ts"` | Optional glob pattern to filter files | | `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` | | `-i` | boolean | `true` | Case insensitive search | | `multiline` | boolean | `false` | Enable multiline matching | ##### WebFetch Fetches and processes web content. | Field | Type | Example | Description | | :------- | :----- | :---------------------------- | :----------------------------------- | | `url` | string | `"https://example.com/api"` | URL to fetch content from | | `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content | ##### WebSearch Searches the web. | Field | Type | Example | Description | | :---------------- | :----- | :----------------------------- | :------------------------------------------------ | | `query` | string | `"react hooks best practices"` | Search query | | `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains | | `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains | ##### Task Spawns a [subagent](/en/sub-agents). | Field | Type | Example | Description | | :-------------- | :----- | :------------------------- | :------------------------------------------- | | `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform | | `description` | string | `"Find API endpoints"` | Short description of the task | | `subagent_type` | string | `"Explore"` | Type of specialized agent to use | | `model` | string | `"sonnet"` | Optional model alias to override the default | #### PreToolUse decision control `PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: three outcomes (allow, deny, or ask) plus the ability to modify tool input before execution. | Field | Description | | :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- | | `permissionDecision` | `"allow"` bypasses the permission system, `"deny"` prevents the tool call, `"ask"` prompts the user to confirm | | `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude | | `updatedInput` | Modifies the tool's input parameters before execution. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user | | `additionalContext` | String added to Claude's context before the tool executes | ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "allow", "permissionDecisionReason": "My reason here", "updatedInput": { "field_to_modify": "new value" }, "additionalContext": "Current environment: production. Proceed with caution." } } ``` PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format. ### PermissionRequest Runs when the user is shown a permission dialog. Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user. Matches on tool name, same values as PreToolUse. #### PermissionRequest input PermissionRequest hooks receive `tool_name` and `tool_input` fields like PreToolUse hooks, but without `tool_use_id`. An optional `permission_suggestions` array contains the "always allow" options the user would normally see in the permission dialog. The difference is when the hook fires: PermissionRequest hooks run when a permission dialog is about to be shown to the user, while PreToolUse hooks run before tool execution regardless of permission status. ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "PermissionRequest", "tool_name": "Bash", "tool_input": { "command": "rm -rf node_modules", "description": "Remove node_modules directory" }, "permission_suggestions": [ { "type": "toolAlwaysAllow", "tool": "Bash" } ] } ``` #### PermissionRequest decision control `PermissionRequest` hooks can allow or deny permission requests. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return a `decision` object with these event-specific fields: | Field | Description | | :------------------- | :------------------------------------------------------------------------------------------------------------- | | `behavior` | `"allow"` grants the permission, `"deny"` denies it | | `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution | | `updatedPermissions` | For `"allow"` only: applies permission rule updates, equivalent to the user selecting an "always allow" option | | `message` | For `"deny"` only: tells Claude why the permission was denied | | `interrupt` | For `"deny"` only: if `true`, stops Claude | ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PermissionRequest", "decision": { "behavior": "allow", "updatedInput": { "command": "npm run lint" } } } } ``` ### PostToolUse Runs immediately after a tool completes successfully. Matches on tool name, same values as PreToolUse. #### PostToolUse input `PostToolUse` hooks fire after a tool has already executed successfully. The input includes both `tool_input`, the arguments sent to the tool, and `tool_response`, the result it returned. The exact schema for both depends on the tool. ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "PostToolUse", "tool_name": "Write", "tool_input": { "file_path": "/path/to/file.txt", "content": "file content" }, "tool_response": { "filePath": "/path/to/file.txt", "success": true }, "tool_use_id": "toolu_01ABC123..." } ``` #### PostToolUse decision control `PostToolUse` hooks can provide feedback to Claude after tool execution. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields: | Field | Description | | :--------------------- | :----------------------------------------------------------------------------------------- | | `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed | | `reason` | Explanation shown to Claude when `decision` is `"block"` | | `additionalContext` | Additional context for Claude to consider | | `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value | ```json theme={null} { "decision": "block", "reason": "Explanation for decision", "hookSpecificOutput": { "hookEventName": "PostToolUse", "additionalContext": "Additional information for Claude" } } ``` ### PostToolUseFailure Runs when a tool execution fails. This event fires for tool calls that throw errors or return failure results. Use this to log failures, send alerts, or provide corrective feedback to Claude. Matches on tool name, same values as PreToolUse. #### PostToolUseFailure input PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields: ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "PostToolUseFailure", "tool_name": "Bash", "tool_input": { "command": "npm test", "description": "Run test suite" }, "tool_use_id": "toolu_01ABC123...", "error": "Command exited with non-zero status code 1", "is_interrupt": false } ``` | Field | Description | | :------------- | :------------------------------------------------------------------------------ | | `error` | String describing what went wrong | | `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption | #### PostToolUseFailure decision control `PostToolUseFailure` hooks can provide context to Claude after a tool failure. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields: | Field | Description | | :------------------ | :------------------------------------------------------------ | | `additionalContext` | Additional context for Claude to consider alongside the error | ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PostToolUseFailure", "additionalContext": "Additional information about the failure for Claude" } } ``` ### Notification Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`. Omit the matcher to run hooks for all notification types. Use separate matchers to run different handlers depending on the notification type. This configuration triggers a permission-specific alert script when Claude needs permission approval and a different notification when Claude has been idle: ```json theme={null} { "hooks": { "Notification": [ { "matcher": "permission_prompt", "hooks": [ { "type": "command", "command": "/path/to/permission-alert.sh" } ] }, { "matcher": "idle_prompt", "hooks": [ { "type": "command", "command": "/path/to/idle-notification.sh" } ] } ] } } ``` #### Notification input In addition to the [common input fields](#common-input-fields), Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired. ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "Notification", "message": "Claude needs your permission to use Bash", "title": "Permission needed", "notification_type": "permission_prompt" } ``` Notification hooks cannot block or modify notifications. In addition to the [JSON output fields](#json-output) available to all hooks, you can return `additionalContext` to add context to the conversation: | Field | Description | | :------------------ | :------------------------------- | | `additionalContext` | String added to Claude's context | ### SubagentStart Runs when a Claude Code subagent is spawned via the Task tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`). #### SubagentStart input In addition to the [common input fields](#common-input-fields), SubagentStart hooks receive `agent_id` with the unique identifier for the subagent and `agent_type` with the agent name (built-in agents like `"Bash"`, `"Explore"`, `"Plan"`, or custom agent names). ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "SubagentStart", "agent_id": "agent-abc123", "agent_type": "Explore" } ``` SubagentStart hooks cannot block subagent creation, but they can inject context into the subagent. In addition to the [JSON output fields](#json-output) available to all hooks, you can return: | Field | Description | | :------------------ | :------------------------------------- | | `additionalContext` | String added to the subagent's context | ```json theme={null} { "hookSpecificOutput": { "hookEventName": "SubagentStart", "additionalContext": "Follow security guidelines for this task" } } ``` ### SubagentStop Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart. #### SubagentStop input In addition to the [common input fields](#common-input-fields), SubagentStop hooks receive `stop_hook_active`, `agent_id`, `agent_type`, and `agent_transcript_path`. The `agent_type` field is the value used for matcher filtering. The `transcript_path` is the main session's transcript, while `agent_transcript_path` is the subagent's own transcript stored in a nested `subagents/` folder. ```json theme={null} { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../abc123.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "SubagentStop", "stop_hook_active": false, "agent_id": "def456", "agent_type": "Explore", "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl" } ``` SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control). ### Stop Runs when the main Claude Code agent has finished responding. Does not run if the stoppage occurred due to a user interrupt. #### Stop input In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active`. This field is `true` when Claude Code is already continuing as a result of a stop hook. Check this value or process the transcript to prevent Claude Code from running indefinitely. ```json theme={null} { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "Stop", "stop_hook_active": true } ``` #### Stop decision control `Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields: | Field | Description | | :--------- | :------------------------------------------------------------------------- | | `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop | | `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue | ```json theme={null} { "decision": "block", "reason": "Must be provided when Claude is blocked from stopping" } ``` ### PreCompact Runs before Claude Code is about to run a compact operation. The matcher value indicates whether compaction was triggered manually or automatically: | Matcher | When it fires | | :------- | :------------------------------------------- | | `manual` | `/compact` | | `auto` | Auto-compact when the context window is full | #### PreCompact input In addition to the [common input fields](#common-input-fields), PreCompact hooks receive `trigger` and `custom_instructions`. For `manual`, `custom_instructions` contains what the user passes into `/compact`. For `auto`, `custom_instructions` is empty. ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "PreCompact", "trigger": "manual", "custom_instructions": "" } ``` ### SessionEnd Runs when a Claude Code session ends. Useful for cleanup tasks, logging session statistics, or saving session state. Supports matchers to filter by exit reason. The `reason` field in the hook input indicates why the session ended: | Reason | Description | | :---------------------------- | :----------------------------------------- | | `clear` | Session cleared with `/clear` command | | `logout` | User logged out | | `prompt_input_exit` | User exited while prompt input was visible | | `bypass_permissions_disabled` | Bypass permissions mode was disabled | | `other` | Other exit reasons | #### SessionEnd input In addition to the [common input fields](#common-input-fields), SessionEnd hooks receive a `reason` field indicating why the session ended. See the [reason table](#sessionend) above for all values. ```json theme={null} { "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "SessionEnd", "reason": "other" } ``` SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks. ## Prompt-based hooks In addition to Bash command hooks (`type: "command"`), Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action. Prompt-based hooks work with the following events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `UserPromptSubmit`, `Stop`, and `SubagentStop`. ### How prompt-based hooks work Instead of executing a Bash command, prompt-based hooks: 1. Send the hook input and your prompt to a Claude model, Haiku by default 2. The LLM responds with structured JSON containing a decision 3. Claude Code processes the decision automatically ### Prompt hook configuration Set `type` to `"prompt"` and provide a `prompt` string instead of a `command`. Use the `$ARGUMENTS` placeholder to inject the hook's JSON input data into your prompt text. Claude Code sends the combined prompt and input to a fast Claude model, which returns a JSON decision. This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish: ```json theme={null} { "hooks": { "Stop": [ { "hooks": [ { "type": "prompt", "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete." } ] } ] } } ``` | Field | Required | Description | | :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `type` | yes | Must be `"prompt"` | | `prompt` | yes | The prompt text to send to the LLM. Use `$ARGUMENTS` as a placeholder for the hook input JSON. If `$ARGUMENTS` is not present, input JSON is appended to the prompt | | `model` | no | Model to use for evaluation. Defaults to a fast model | | `timeout` | no | Timeout in seconds. Default: 30 | ### Response schema The LLM must respond with JSON containing: ```json theme={null} { "ok": true | false, "reason": "Explanation for the decision" } ``` | Field | Description | | :------- | :--------------------------------------------------------- | | `ok` | `true` allows the action, `false` prevents it | | `reason` | Required when `ok` is `false`. Explanation shown to Claude | ### Example: Multi-criteria Stop hook This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction. `SubagentStop` hooks use the same format to evaluate whether a [subagent](/en/sub-agents) should stop: ```json theme={null} { "hooks": { "Stop": [ { "hooks": [ { "type": "prompt", "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"your explanation\"} to continue working.", "timeout": 30 } ] } ] } } ``` ## Agent-based hooks Agent-based hooks (`type: "agent"`) are like prompt-based hooks but with multi-turn tool access. Instead of a single LLM call, an agent hook spawns a subagent that can read files, search code, and inspect the codebase to verify conditions. Agent hooks support the same events as prompt-based hooks. ### How agent hooks work When an agent hook fires: 1. Claude Code spawns a subagent with your prompt and the hook's JSON input 2. The subagent can use tools like Read, Grep, and Glob to investigate 3. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision 4. Claude Code processes the decision the same way as a prompt hook Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone. ### Agent hook configuration Set `type` to `"agent"` and provide a `prompt` string. The configuration fields are the same as [prompt hooks](#prompt-hook-configuration), with a longer default timeout: | Field | Required | Description | | :-------- | :------- | :------------------------------------------------------------------------------------------ | | `type` | yes | Must be `"agent"` | | `prompt` | yes | Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON | | `model` | no | Model to use. Defaults to a fast model | | `timeout` | no | Timeout in seconds. Default: 60 | The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block. This `Stop` hook verifies that all unit tests pass before allowing Claude to finish: ```json theme={null} { "hooks": { "Stop": [ { "hooks": [ { "type": "agent", "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS", "timeout": 120 } ] } ] } } ``` ## Run hooks in the background By default, hooks block Claude's execution until they complete. For long-running tasks like deployments, test suites, or external API calls, set `"async": true` to run the hook in the background while Claude continues working. Async hooks cannot block or control Claude's behavior: response fields like `decision`, `permissionDecision`, and `continue` have no effect, because the action they would have controlled has already completed. ### Configure an async hook Add `"async": true` to a command hook's configuration to run it in the background without blocking Claude. This field is only available on `type: "command"` hooks. This hook runs a test script after every `Write` tool call. Claude continues working immediately while `run-tests.sh` executes for up to 120 seconds. When the script finishes, its output is delivered on the next conversation turn: ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Write", "hooks": [ { "type": "command", "command": "/path/to/run-tests.sh", "async": true, "timeout": 120 } ] } ] } } ``` The `timeout` field sets the maximum time in seconds for the background process. If not specified, async hooks use the same 10-minute default as sync hooks. ### How async hooks execute When an async hook fires, Claude Code starts the hook process and immediately continues without waiting for it to finish. The hook receives the same JSON input via stdin as a synchronous hook. After the background process exits, if the hook produced a JSON response with a `systemMessage` or `additionalContext` field, that content is delivered to Claude as context on the next conversation turn. ### Example: run tests after file changes This hook starts a test suite in the background whenever Claude writes a file, then reports the results back to Claude when the tests finish. Save this script to `.claude/hooks/run-tests-async.sh` in your project and make it executable with `chmod +x`: ```bash theme={null} #!/bin/bash # run-tests-async.sh # Read hook input from stdin INPUT=$(cat) FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') # Only run tests for source files if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then exit 0 fi # Run tests and report results via systemMessage RESULT=$(npm test 2>&1) EXIT_CODE=$? if [ $EXIT_CODE -eq 0 ]; then echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}" else echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}" fi ``` Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run: ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh", "async": true, "timeout": 300 } ] } ] } } ``` ### Limitations Async hooks have several constraints compared to synchronous hooks: * Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously. * Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded. * Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction. * Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook. ## Security considerations ### Disclaimer Hooks run with your system user's full permissions. Hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration. ### Security best practices Keep these practices in mind when writing hooks: * **Validate and sanitize inputs**: never trust input data blindly * **Always quote shell variables**: use `"$VAR"` not `$VAR` * **Block path traversal**: check for `..` in file paths * **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root * **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc. ## Debug hooks Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output. Toggle verbose mode with `Ctrl+O` to see hook progress in the transcript. ``` [DEBUG] Executing hooks for PostToolUse:Write [DEBUG] Getting matching hook commands for PostToolUse with query: Write [DEBUG] Found 1 hook matchers in settings [DEBUG] Matched 1 hooks for query "Write" [DEBUG] Found 1 hook commands to execute [DEBUG] Executing hook command: with timeout 600000ms [DEBUG] Hook command completed with status 0: ``` For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](/en/hooks-guide#limitations-and-troubleshooting) in the guide. --- # Source: https://code.claude.com/docs/en/how-claude-code-works.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # How Claude Code works > Understand the agentic loop, built-in tools, and how Claude Code interacts with your project. Claude Code is an agentic assistant that runs in your terminal. While it excels at coding, it can help with anything you can do from the command line: writing docs, running builds, searching files, researching topics, and more. This guide covers the core architecture, built-in capabilities, and [tips for working effectively](#work-effectively-with-claude-code). For step-by-step walkthroughs, see [Common workflows](/en/common-workflows). For extensibility features like skills, MCP, and hooks, see [Extend Claude Code](/en/features-overview). ## The agentic loop When you give Claude a task, it works through three phases: **gather context**, **take action**, and **verify results**. These phases blend together. Claude uses tools throughout, whether searching files to understand your code, editing to make changes, or running tests to check its work. The agentic loop: Your prompt leads to Claude gathering context, taking action, verifying results, and repeating until task complete. You can interrupt at any point. The loop adapts to what you ask. A question about your codebase might only need context gathering. A bug fix cycles through all three phases repeatedly. A refactor might involve extensive verification. Claude decides what each step requires based on what it learned from the previous step, chaining dozens of actions together and course-correcting along the way. You're part of this loop too. You can interrupt at any point to steer Claude in a different direction, provide additional context, or ask it to try a different approach. Claude works autonomously but stays responsive to your input. The agentic loop is powered by two components: [models](#models) that reason and [tools](#tools) that act. Claude Code serves as the **agentic harness** around Claude: it provides the tools, context management, and execution environment that turn a language model into a capable coding agent. ### Models Claude Code uses Claude models to understand your code and reason about tasks. Claude can read code in any language, understand how components connect, and figure out what needs to change to accomplish your goal. For complex tasks, it breaks work into steps, executes them, and adjusts based on what it learns. [Multiple models](/en/model-config) are available with different tradeoffs. Sonnet handles most coding tasks well. Opus provides stronger reasoning for complex architectural decisions. Switch with `/model` during a session or start with `claude --model `. When this guide says "Claude chooses" or "Claude decides," it's the model doing the reasoning. ### Tools Tools are what make Claude Code agentic. Without tools, Claude can only respond with text. With tools, Claude can act: read your code, edit files, run commands, search the web, and interact with external services. Each tool use returns information that feeds back into the loop, informing Claude's next decision. The built-in tools generally fall into four categories, each representing a different kind of agency. | Category | What Claude can do | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **File operations** | Read files, edit code, create new files, rename and reorganize | | **Search** | Find files by pattern, search content with regex, explore codebases | | **Execution** | Run shell commands, start servers, run tests, use git | | **Web** | Search the web, fetch documentation, look up error messages | | **Code intelligence** | See type errors and warnings after edits, jump to definitions, find references (requires [code intelligence plugins](/en/discover-plugins#code-intelligence)) | These are the primary capabilities. Claude also has tools for spawning subagents, asking you questions, and other orchestration tasks. See [Tools available to Claude](/en/settings#tools-available-to-claude) for the complete list. Claude chooses which tools to use based on your prompt and what it learns along the way. When you say "fix the failing tests," Claude might: 1. Run the test suite to see what's failing 2. Read the error output 3. Search for the relevant source files 4. Read those files to understand the code 5. Edit the files to fix the issue 6. Run the tests again to verify Each tool use gives Claude new information that informs the next step. This is the agentic loop in action. **Extending the base capabilities:** The built-in tools are the foundation. You can extend what Claude knows with [skills](/en/skills), connect to external services with [MCP](/en/mcp), automate workflows with [hooks](/en/hooks), and offload tasks to [subagents](/en/sub-agents). These extensions form a layer on top of the core agentic loop. See [Extend Claude Code](/en/features-overview) for guidance on choosing the right extension for your needs. ## What Claude can access This guide focuses on the terminal. Claude Code also runs in [VS Code, JetBrains IDEs, and other environments](/en/ide-integrations). When you run `claude` in a directory, Claude Code gains access to: * **Your project.** Files in your directory and subdirectories, plus files elsewhere with your permission. * **Your terminal.** Any command you could run: build tools, git, package managers, system utilities, scripts. If you can do it from the command line, Claude can too. * **Your git state.** Current branch, uncommitted changes, and recent commit history. * **Your [CLAUDE.md](/en/memory).** A markdown file where you store project-specific instructions, conventions, and context that Claude should know every session. * **Extensions you configure.** [MCP servers](/en/mcp) for external services, [skills](/en/skills) for workflows, [subagents](/en/sub-agents) for delegated work, and [Claude in Chrome](/en/chrome) for browser interaction. Because Claude sees your whole project, it can work across it. When you ask Claude to "fix the authentication bug," it searches for relevant files, reads multiple files to understand context, makes coordinated edits across them, runs tests to verify the fix, and commits the changes if you ask. This is different from inline code assistants that only see the current file. ## Work with sessions Claude Code saves your conversation locally as you work. Each message, tool use, and result is stored, which enables [rewinding](#undo-changes-with-checkpoints), [resuming, and forking](#resume-or-fork-sessions) sessions. Before Claude makes code changes, it also snapshots the affected files so you can revert if needed. **Sessions are ephemeral.** Unlike claude.ai, Claude Code has no persistent memory between sessions. Each new session starts fresh. Claude doesn't "learn" your preferences over time or remember what you worked on last week. If you want Claude to know something across sessions, put it in your [CLAUDE.md](/en/memory). ### Work across branches Each Claude Code conversation is a session tied to your current directory. When you resume, you only see sessions from that directory. Claude sees your current branch's files. When you switch branches, Claude sees the new branch's files, but your conversation history stays the same. Claude remembers what you discussed even after switching. Since sessions are tied to directories, you can run parallel Claude sessions by using [git worktrees](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees), which create separate directories for individual branches. ### Resume or fork sessions When you resume a session with `claude --continue` or `claude --resume`, you pick up where you left off using the same session ID. New messages append to the existing conversation. Your full conversation history is restored, but session-scoped permissions are not. You'll need to re-approve those. Session continuity: resume continues the same session, fork creates a new branch with a new ID. To branch off and try a different approach without affecting the original session, use the `--fork-session` flag: ```bash theme={null} claude --continue --fork-session ``` This creates a new session ID while preserving the conversation history up to that point. The original session remains unchanged. Like resume, forked sessions don't inherit session-scoped permissions. **Same session in multiple terminals**: If you resume the same session in multiple terminals, both terminals write to the same session file. Messages from both get interleaved, like two people writing in the same notebook. Nothing corrupts, but the conversation becomes jumbled. Each terminal only sees its own messages during the session, but if you resume that session later, you'll see everything interleaved. For parallel work from the same starting point, use `--fork-session` to give each terminal its own clean session. ### The context window Claude's context window holds your conversation history, file contents, command outputs, [CLAUDE.md](/en/memory), loaded skills, and system instructions. As you work, context fills up. Claude compacts automatically, but instructions from early in the conversation can get lost. Put persistent rules in CLAUDE.md, and run `/context` to see what's using space. #### When context fills up Claude Code manages context automatically as you approach the limit. It clears older tool outputs first, then summarizes the conversation if needed. Your requests and key code snippets are preserved; detailed instructions from early in the conversation may be lost. Put persistent rules in CLAUDE.md rather than relying on conversation history. To control what's preserved during compaction, add a "Compact Instructions" section to CLAUDE.md or run `/compact` with a focus (like `/compact focus on the API changes`). Run `/context` to see what's using space. MCP servers add tool definitions to every request, so a few servers can consume significant context before you start working. Run `/mcp` to check per-server costs. #### Manage context with skills and subagents Beyond compaction, you can use other features to control what loads into context. [Skills](/en/skills) load on demand. Claude sees skill descriptions at session start, but the full content only loads when a skill is used. For skills you invoke manually, set `disable-model-invocation: true` to keep descriptions out of context until you need them. [Subagents](/en/sub-agents) get their own fresh context, completely separate from your main conversation. Their work doesn't bloat your context. When done, they return a summary. This isolation is why subagents help with long sessions. See [context costs](/en/features-overview#understand-context-costs) for what each feature costs, and [reduce token usage](/en/costs#reduce-token-usage) for tips on managing context. ## Stay safe with checkpoints and permissions Claude has two safety mechanisms: checkpoints let you undo file changes, and permissions control what Claude can do without asking. ### Undo changes with checkpoints **Every file edit is reversible.** Before Claude edits any file, it snapshots the current contents. If something goes wrong, press `Esc` twice to rewind to a previous state, or ask Claude to undo. Checkpoints are local to your session, separate from git. They only cover file changes. Actions that affect remote systems (databases, APIs, deployments) can't be checkpointed, which is why Claude asks before running commands with external side effects. ### Control what Claude can do Press `Shift+Tab` to cycle through permission modes: * **Default**: Claude asks before file edits and shell commands * **Auto-accept edits**: Claude edits files without asking, still asks for commands * **Plan mode**: Claude uses read-only tools only, creating a plan you can approve before execution You can also allow specific commands in `.claude/settings.json` so Claude doesn't ask each time. This is useful for trusted commands like `npm test` or `git status`. Settings can be scoped from organization-wide policies down to personal preferences. See [Permissions](/en/permissions) for details. *** ## Work effectively with Claude Code These tips help you get better results from Claude Code. ### Ask Claude Code for help Claude Code can teach you how to use it. Ask questions like "how do I set up hooks?" or "what's the best way to structure my CLAUDE.md?" and Claude will explain. Built-in commands also guide you through setup: * `/init` walks you through creating a CLAUDE.md for your project * `/agents` helps you configure custom subagents * `/doctor` diagnoses common issues with your installation ### It's a conversation Claude Code is conversational. You don't need perfect prompts. Start with what you want, then refine: ``` > Fix the login bug [Claude investigates, tries something] > That's not quite right. The issue is in the session handling. [Claude adjusts approach] ``` When the first attempt isn't right, you don't start over. You iterate. #### Interrupt and steer You can interrupt Claude at any point. If it's going down the wrong path, just type your correction and press Enter. Claude will stop what it's doing and adjust its approach based on your input. You don't have to wait for it to finish or start over. ### Be specific upfront The more precise your initial prompt, the fewer corrections you'll need. Reference specific files, mention constraints, and point to example patterns. ``` > The checkout flow is broken for users with expired cards. > Check src/payments/ for the issue, especially token refresh. > Write a failing test first, then fix it. ``` Vague prompts like "fix the login bug" work, but you'll spend more time steering. Specific prompts like the above often succeed on the first attempt. ### Give Claude something to verify against Claude performs better when it can check its own work. Include test cases, paste screenshots of expected UI, or define the output you want. ``` > Implement validateEmail. Test cases: 'user@example.com' → true, > 'invalid' → false, 'user@.com' → false. Run the tests after. ``` For visual work, paste a screenshot of the design and ask Claude to compare its implementation against it. ### Explore before implementing For complex problems, separate research from coding. Use plan mode (`Shift+Tab` twice) to analyze the codebase first: ``` > Read src/auth/ and understand how we handle sessions. > Then create a plan for adding OAuth support. ``` Review the plan, refine it through conversation, then let Claude implement. This two-phase approach produces better results than jumping straight to code. ### Delegate, don't dictate Think of delegating to a capable colleague. Give context and direction, then trust Claude to figure out the details: ``` > The checkout flow is broken for users with expired cards. > The relevant code is in src/payments/. Can you investigate and fix it? ``` You don't need to specify which files to read or what commands to run. Claude figures that out. ## What's next Add Skills, MCP connections, and custom commands Step-by-step guides for typical tasks --- # Source: https://code.claude.com/docs/en/iam.md # Identity and Access Management > Learn how to configure user authentication, authorization, and access controls for Claude Code in your organization. ## Authentication methods Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of four ways: * Claude API via the Claude Console * Amazon Bedrock * Microsoft Foundry * Google Vertex AI ### Claude API authentication **To set up Claude Code access for your team via Claude API:** 1. Use your existing Claude Console account or create a new Claude Console account 2. You can add users through either method below: * Bulk invite users from within the Console (Console -> Settings -> Members -> Invite) * [Set up SSO](https://support.claude.com/en/articles/10280258-setting-up-single-sign-on-on-the-api-console) 3. When inviting users, they need one of the following roles: * "Claude Code" role means users can only create Claude Code API keys * "Developer" role means users can create any kind of API key 4. Each invited user needs to complete these steps: * Accept the Console invite * [Check system requirements](/en/setup#system-requirements) * [Install Claude Code](/en/setup#installation) * Login with Console account credentials ### Cloud provider authentication **To set up Claude Code access for your team via Bedrock, Vertex, or Azure:** 1. Follow the [Bedrock docs](/en/amazon-bedrock), [Vertex docs](/en/google-vertex-ai), or [Microsoft Foundry docs](/en/microsoft-foundry) 2. Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/en/settings). 3. Users can [install Claude Code](/en/setup#installation) ## Access control and permissions We support fine-grained permissions so that you're able to specify exactly what the agent is allowed to do (e.g. run tests, run linter) and what it is not allowed to do (e.g. update cloud infrastructure). These permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers. ### Permission system Claude Code uses a tiered permission system to balance power and safety: | Tool Type | Example | Approval Required | "Yes, don't ask again" Behavior | | :---------------- | :------------------- | :---------------- | :-------------------------------------------- | | Read-only | File reads, LS, Grep | No | N/A | | Bash Commands | Shell execution | Yes | Permanently per project directory and command | | File Modification | Edit/write files | Yes | Until session end | ### Configuring permissions You can view & manage Claude Code's tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from. * **Allow** rules will allow Claude Code to use the specified tool without further manual approval. * **Ask** rules will ask the user for confirmation whenever Claude Code tries to use the specified tool. Ask rules take precedence over allow rules. * **Deny** rules will prevent Claude Code from using the specified tool. Deny rules take precedence over allow and ask rules. * **Additional directories** extend Claude's file access to directories beyond the initial working directory. * **Default mode** controls Claude's permission behavior when encountering new requests. Permission rules use the format: `Tool` or `Tool(optional-specifier)` A rule that is just the tool name matches any use of that tool. For example, adding `Bash` to the list of allow rules would allow Claude Code to use the Bash tool without requiring user approval. #### Permission modes Claude Code supports several permission modes that can be set as the `defaultMode` in [settings files](/en/settings#settings-files): | Mode | Description | | :------------------ | :--------------------------------------------------------------------------- | | `default` | Standard behavior - prompts for permission on first use of each tool | | `acceptEdits` | Automatically accepts file edit permissions for the session | | `plan` | Plan Mode - Claude can analyze but not modify files or execute commands | | `bypassPermissions` | Skips all permission prompts (requires safe environment - see warning below) | #### Working directories By default, Claude has access to files in the directory where it was launched. You can extend this access: * **During startup**: Use `--add-dir ` CLI argument * **During session**: Use `/add-dir` slash command * **Persistent configuration**: Add to `additionalDirectories` in [settings files](/en/settings#settings-files) Files in additional directories follow the same permission rules as the original working directory - they become readable without prompts, and file editing permissions follow the current permission mode. #### Tool-specific permission rules Some tools support more fine-grained permission controls: **Bash** * `Bash(npm run build)` Matches the exact Bash command `npm run build` * `Bash(npm run test:*)` Matches Bash commands starting with `npm run test` * `Bash(curl http://site.com/:*)` Matches curl commands that start with exactly `curl http://site.com/` Claude Code is aware of shell operators (like `&&`) so a prefix match rule like `Bash(safe-cmd:*)` won't give it permission to run the command `safe-cmd && other-cmd` Important limitations of Bash permission patterns: 1. This tool uses **prefix matches**, not regex or glob patterns 2. The wildcard `:*` only works at the end of a pattern to match any continuation 3. Patterns like `Bash(curl http://github.com/:*)` can be bypassed in many ways: * Options before URL: `curl -X GET http://github.com/...` won't match * Different protocol: `curl https://github.com/...` won't match * Redirects: `curl -L http://bit.ly/xyz` (redirects to github) * Variables: `URL=http://github.com && curl $URL` won't match * Extra spaces: `curl http://github.com` won't match For more reliable URL filtering, consider: * Using the WebFetch tool with `WebFetch(domain:github.com)` permission * Instructing Claude Code about your allowed curl patterns via CLAUDE.md * Using hooks for custom permission validation **Read & Edit** `Edit` rules apply to all built-in tools that edit files. Claude will make a best-effort attempt to apply `Read` rules to all built-in tools that read files like Grep, Glob, and LS. Read & Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types: | Pattern | Meaning | Example | Matches | | ------------------ | -------------------------------------- | -------------------------------- | ---------------------------------- | | `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` | | `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` | | `/path` | Path **relative to settings file** | `Edit(/src/**/*.ts)` | `/src/**/*.ts` | | `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `/*.env` | A pattern like `/Users/alice/file` is NOT an absolute path - it's relative to your settings file! Use `//Users/alice/file` for absolute paths. * `Edit(/docs/**)` - Edits in `/docs/` (NOT `/docs/`!) * `Read(~/.zshrc)` - Reads your home directory's `.zshrc` * `Edit(//tmp/scratch.txt)` - Edits the absolute path `/tmp/scratch.txt` * `Read(src/**)` - Reads from `/src/` **WebFetch** * `WebFetch(domain:example.com)` Matches fetch requests to example.com **MCP** * `mcp__puppeteer` Matches any tool provided by the `puppeteer` server (name configured in Claude Code) * `mcp__puppeteer__puppeteer_navigate` Matches the `puppeteer_navigate` tool provided by the `puppeteer` server Unlike other permission types, MCP permissions do NOT support wildcards (`*`). To approve all tools from an MCP server: * ✅ Use: `mcp__github` (approves ALL GitHub tools) * ❌ Don't use: `mcp__github__*` (wildcards are not supported) To approve specific tools only, list each one: * ✅ Use: `mcp__github__get_issue` * ✅ Use: `mcp__github__list_issues` ### Additional permission control with hooks [Claude Code hooks](/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission system runs, and the hook output can determine whether to approve or deny the tool call in place of the permission system. ### Enterprise managed settings For enterprise deployments of Claude Code, administrators can configure and distribute settings to their organization through the [Claude.ai admin console](https://claude.ai/admin-settings/claude-code). These settings are fetched automatically when users authenticate and cannot be overridden locally. This feature is available to Claude for Enterprise customers. If you don't see this option in your admin console, contact your Anthropic account team to have the feature enabled. For organizations that prefer file-based policy distribution, Claude Code also supports `managed-settings.json` files that can be deployed to [system directories](/en/settings#settings-files). These policy files follow the same format as regular settings files and cannot be overridden by user or project settings. ### Settings precedence When multiple settings sources exist, they are applied in the following order (highest to lowest precedence): 1. Managed settings (via Claude.ai admin console) 2. File-based managed settings (`managed-settings.json`) 3. Command line arguments 4. Local project settings (`.claude/settings.local.json`) 5. Shared project settings (`.claude/settings.json`) 6. User settings (`~/.claude/settings.json`) This hierarchy ensures that organizational policies are always enforced while still allowing flexibility at the project and user levels where appropriate. ## Credential management Claude Code securely manages your authentication credentials: * **Storage location**: On macOS, API keys, OAuth tokens, and other credentials are stored in the encrypted macOS Keychain. * **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth. * **Custom credential scripts**: The [`apiKeyHelper`](/en/settings#available-settings) setting can be configured to run a shell script that returns an API key. * **Refresh intervals**: By default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals. --- > To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt --- # Source: https://code.claude.com/docs/en/interactive-mode.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Interactive mode > Complete reference for keyboard shortcuts, input modes, and interactive features in Claude Code sessions. ## Keyboard shortcuts Keyboard shortcuts may vary by platform and terminal. Press `?` to see available shortcuts for your environment. **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+M`, `Alt+P`) require configuring Option as Meta in your terminal: * **iTerm2**: Settings → Profiles → Keys → Set Left/Right Option key to "Esc+" * **Terminal.app**: Settings → Profiles → Keyboard → Check "Use Option as Meta Key" * **VS Code**: Settings → Profiles → Keys → Set Left/Right Option key to "Esc+" See [Terminal configuration](/en/terminal-config) for details. ### General controls | Shortcut | Description | Context | | :------------------------------------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------- | | `Ctrl+C` | Cancel current input or generation | Standard interrupt | | `Ctrl+D` | Exit Claude Code session | EOF signal | | `Ctrl+G` | Open in default text editor | Edit your prompt or custom response in your default text editor | | `Ctrl+L` | Clear terminal screen | Keeps conversation history | | `Ctrl+O` | Toggle verbose output | Shows detailed tool usage and execution | | `Ctrl+R` | Reverse search command history | Search through previous commands interactively | | `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file | | `Ctrl+B` | Background running tasks | Backgrounds bash commands and agents. Tmux users press twice | | `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in permission dialogs and menus | | `Up/Down arrows` | Navigate command history | Recall previous inputs | | `Esc` + `Esc` | Rewind the code/conversation | Restore the code and/or conversation to a previous point | | `Shift+Tab` or `Alt+M` (some configurations) | Toggle permission modes | Switch between Auto-Accept Mode, Plan Mode, and normal mode | | `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt | | `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Run `/terminal-setup` first to enable this shortcut | ### Text editing | Shortcut | Description | Context | | :----------------------- | :--------------------------- | :------------------------------------------------------------------------------------------------------------ | | `Ctrl+K` | Delete to end of line | Stores deleted text for pasting | | `Ctrl+U` | Delete entire line | Stores deleted text for pasting | | `Ctrl+Y` | Paste deleted text | Paste text deleted with `Ctrl+K` or `Ctrl+U` | | `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS | | `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS | | `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS | ### Theme and display | Shortcut | Description | Context | | :------- | :----------------------------------------- | :----------------------------------------------------------------------------------------------------------- | | `Ctrl+T` | Toggle syntax highlighting for code blocks | Only works inside the `/theme` picker menu. Controls whether code in Claude's responses uses syntax coloring | Syntax highlighting is only available in the native build of Claude Code. ### Multiline input | Method | Shortcut | Context | | :--------------- | :------------- | :------------------------------------------------------ | | Quick escape | `\` + `Enter` | Works in all terminals | | macOS default | `Option+Enter` | Default on macOS | | Shift+Enter | `Shift+Enter` | Works out of the box in iTerm2, WezTerm, Ghostty, Kitty | | Control sequence | `Ctrl+J` | Line feed character for multiline | | Paste mode | Paste directly | For code blocks, logs | Shift+Enter works without configuration in iTerm2, WezTerm, Ghostty, and Kitty. For other terminals (VS Code, Alacritty, Zed, Warp), run `/terminal-setup` to install the binding. ### Quick commands | Shortcut | Description | Notes | | :----------- | :---------------- | :------------------------------------------------------------------- | | `/` at start | Command or skill | See [built-in commands](#built-in-commands) and [skills](/en/skills) | | `!` at start | Bash mode | Run commands directly and add execution output to the session | | `@` | File path mention | Trigger file path autocomplete | ## Built-in commands Built-in commands are shortcuts for common actions. The table below covers commonly used commands but not all available options. Type `/` in Claude Code to see the full list, or type `/` followed by any letters to filter. To create your own commands you can invoke with `/`, see [skills](/en/skills). | Command | Purpose | | :------------------------ | :-------------------------------------------------------------------------------------------------------------------------- | | `/clear` | Clear conversation history | | `/compact [instructions]` | Compact conversation with optional focus instructions | | `/config` | Open the Settings interface (Config tab) | | `/context` | Visualize current context usage as a colored grid | | `/cost` | Show token usage statistics. See [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details. | | `/doctor` | Checks the health of your Claude Code installation | | `/exit` | Exit the REPL | | `/export [filename]` | Export the current conversation to a file or clipboard | | `/help` | Get usage help | | `/init` | Initialize project with `CLAUDE.md` guide | | `/mcp` | Manage MCP server connections and OAuth authentication | | `/memory` | Edit `CLAUDE.md` memory files | | `/model` | Select or change the AI model | | `/permissions` | View or update [permissions](/en/permissions#manage-permissions) | | `/plan` | Enter plan mode directly from the prompt | | `/rename ` | Rename the current session for easier identification | | `/resume [session]` | Resume a conversation by ID or name, or open the session picker | | `/rewind` | Rewind the conversation and/or code | | `/stats` | Visualize daily usage, session history, streaks, and model preferences | | `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity | | `/statusline` | Set up Claude Code's status line UI | | `/copy` | Copy the last assistant response to clipboard | | `/tasks` | List and manage background tasks | | `/teleport` | Resume a remote session from claude.ai (subscribers only) | | `/theme` | Change the color theme | | `/todos` | List current TODO items | | `/usage` | For subscription plans only: show plan usage limits and rate limit status | ### MCP prompts MCP servers can expose prompts that appear as commands. These use the format `/mcp____` and are dynamically discovered from connected servers. See [MCP prompts](/en/mcp#use-mcp-prompts-as-commands) for details. ## Vim editor mode Enable vim-style editing with `/vim` command or configure permanently via `/config`. ### Mode switching | Command | Action | From mode | | :------ | :-------------------------- | :-------- | | `Esc` | Enter NORMAL mode | INSERT | | `i` | Insert before cursor | NORMAL | | `I` | Insert at beginning of line | NORMAL | | `a` | Insert after cursor | NORMAL | | `A` | Insert at end of line | NORMAL | | `o` | Open line below | NORMAL | | `O` | Open line above | NORMAL | ### Navigation (NORMAL mode) | Command | Action | | :-------------- | :-------------------------------------------------- | | `h`/`j`/`k`/`l` | Move left/down/up/right | | `w` | Next word | | `e` | End of word | | `b` | Previous word | | `0` | Beginning of line | | `$` | End of line | | `^` | First non-blank character | | `gg` | Beginning of input | | `G` | End of input | | `f{char}` | Jump to next occurrence of character | | `F{char}` | Jump to previous occurrence of character | | `t{char}` | Jump to just before next occurrence of character | | `T{char}` | Jump to just after previous occurrence of character | | `;` | Repeat last f/F/t/T motion | | `,` | Repeat last f/F/t/T motion in reverse | In vim normal mode, if the cursor is at the beginning or end of input and cannot move further, the arrow keys navigate command history instead. ### Editing (NORMAL mode) | Command | Action | | :------------- | :---------------------- | | `x` | Delete character | | `dd` | Delete line | | `D` | Delete to end of line | | `dw`/`de`/`db` | Delete word/to end/back | | `cc` | Change line | | `C` | Change to end of line | | `cw`/`ce`/`cb` | Change word/to end/back | | `yy`/`Y` | Yank (copy) line | | `yw`/`ye`/`yb` | Yank word/to end/back | | `p` | Paste after cursor | | `P` | Paste before cursor | | `>>` | Indent line | | `<<` | Dedent line | | `J` | Join lines | | `.` | Repeat last change | ### Text objects (NORMAL mode) Text objects work with operators like `d`, `c`, and `y`: | Command | Action | | :-------- | :--------------------------------------- | | `iw`/`aw` | Inner/around word | | `iW`/`aW` | Inner/around WORD (whitespace-delimited) | | `i"`/`a"` | Inner/around double quotes | | `i'`/`a'` | Inner/around single quotes | | `i(`/`a(` | Inner/around parentheses | | `i[`/`a[` | Inner/around brackets | | `i{`/`a{` | Inner/around braces | ## Command history Claude Code maintains command history for the current session: * History is stored per working directory * Cleared with `/clear` command * Use Up/Down arrows to navigate (see keyboard shortcuts above) * **Note**: History expansion (`!`) is disabled by default ### Reverse search with Ctrl+R Press `Ctrl+R` to interactively search through your command history: 1. **Start search**: Press `Ctrl+R` to activate reverse history search 2. **Type query**: Enter text to search for in previous commands - the search term will be highlighted in matching results 3. **Navigate matches**: Press `Ctrl+R` again to cycle through older matches 4. **Accept match**: * Press `Tab` or `Esc` to accept the current match and continue editing * Press `Enter` to accept and execute the command immediately 5. **Cancel search**: * Press `Ctrl+C` to cancel and restore your original input * Press `Backspace` on empty search to cancel The search displays matching commands with the search term highlighted, making it easy to find and reuse previous inputs. ## Background bash commands Claude Code supports running bash commands in the background, allowing you to continue working while long-running processes execute. ### How backgrounding works When Claude Code runs a command in the background, it runs the command asynchronously and immediately returns a background task ID. Claude Code can respond to new prompts while the command continues executing in the background. To run commands in the background, you can either: * Prompt Claude Code to run a command in the background * Press Ctrl+B to move a regular Bash tool invocation to the background. (Tmux users must press Ctrl+B twice due to tmux's prefix key.) **Key features:** * Output is buffered and Claude can retrieve it using the TaskOutput tool * Background tasks have unique IDs for tracking and output retrieval * Background tasks are automatically cleaned up when Claude Code exits To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/settings#environment-variables) for details. **Common backgrounded commands:** * Build tools (webpack, vite, make) * Package managers (npm, yarn, pnpm) * Test runners (jest, pytest) * Development servers * Long-running processes (docker, terraform) ### Bash mode with `!` prefix Run bash commands directly without going through Claude by prefixing your input with `!`: ```bash theme={null} ! npm test ! git status ! ls -la ``` Bash mode: * Adds the command and its output to the conversation context * Shows real-time progress and output * Supports the same `Ctrl+B` backgrounding for long-running commands * Does not require Claude to interpret or approve the command * Supports history-based autocomplete: type a partial command and press **Tab** to complete from previous `!` commands in the current project This is useful for quick shell operations while maintaining conversation context. ## Prompt suggestions When you first open a session, a grayed-out example command appears in the prompt input to help you get started. Claude Code picks this from your project's git history, so it reflects files you've been working on recently. After Claude responds, suggestions continue to appear based on your conversation history, such as a follow-up step from a multi-part request or a natural continuation of your workflow. * Press **Tab** to accept the suggestion, or press **Enter** to accept and submit * Start typing to dismiss it The suggestion runs as a background request that reuses the parent conversation's prompt cache, so the additional cost is minimal. Claude Code skips suggestion generation when the cache is cold to avoid unnecessary cost. Suggestions are automatically skipped after the first turn of a conversation, in non-interactive mode, and in plan mode. To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`: ```bash theme={null} export CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false ``` ## Task list When working on complex, multi-step work, Claude creates a task list to track progress. Tasks appear in the status area of your terminal with indicators showing what's pending, in progress, or complete. * Press `Ctrl+T` to toggle the task list view. The display shows up to 10 tasks at a time * To see all tasks or clear them, ask Claude directly: "show me all tasks" or "clear all tasks" * Tasks persist across context compactions, helping Claude stay organized on larger projects * To share a task list across sessions, set `CLAUDE_CODE_TASK_LIST_ID` to use a named directory in `~/.claude/tasks/`: `CLAUDE_CODE_TASK_LIST_ID=my-project claude` * To revert to the previous TODO list, set `CLAUDE_CODE_ENABLE_TASKS=false`. ## PR review status When working on a branch with an open pull request, Claude Code displays a clickable PR link in the footer (for example, "PR #446"). The link has a colored underline indicating the review state: * Green: approved * Yellow: pending review * Red: changes requested * Gray: draft * Purple: merged `Cmd+click` (Mac) or `Ctrl+click` (Windows/Linux) the link to open the pull request in your browser. The status updates automatically every 60 seconds. PR status requires the `gh` CLI to be installed and authenticated (`gh auth login`). ## See also * [Skills](/en/skills) - Custom prompts and workflows * [Checkpointing](/en/checkpointing) - Rewind Claude's edits and restore previous states * [CLI reference](/en/cli-reference) - Command-line flags and options * [Settings](/en/settings) - Configuration options * [Memory management](/en/memory) - Managing CLAUDE.md files --- # Source: https://code.claude.com/docs/en/jetbrains.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # JetBrains IDEs > Use Claude Code with JetBrains IDEs including IntelliJ, PyCharm, WebStorm, and more Claude Code integrates with JetBrains IDEs through a dedicated plugin, providing features like interactive diff viewing, selection context sharing, and more. ## Supported IDEs The Claude Code plugin works with most JetBrains IDEs, including: * IntelliJ IDEA * PyCharm * Android Studio * WebStorm * PhpStorm * GoLand ## Features * **Quick launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open Claude Code directly from your editor, or click the Claude Code button in the UI * **Diff viewing**: Code changes can be displayed directly in the IDE diff viewer instead of the terminal * **Selection context**: The current selection/tab in the IDE is automatically shared with Claude Code * **File reference shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references (for example, @File#L1-99) * **Diagnostic sharing**: Diagnostic errors (lint, syntax, etc.) from the IDE are automatically shared with Claude as you work ## Installation ### Marketplace Installation Find and install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains marketplace and restart your IDE. If you haven't installed Claude Code yet, see [our quickstart guide](/en/quickstart) for installation instructions. After installing the plugin, you may need to restart your IDE completely for it to take effect. ## Usage ### From Your IDE Run `claude` from your IDE's integrated terminal, and all integration features will be active. ### From External Terminals Use the `/ide` command in any external terminal to connect Claude Code to your JetBrains IDE and activate all features: ```bash theme={null} claude > /ide ``` If you want Claude to have access to the same files as your IDE, start Claude Code from the same directory as your IDE project root. ## Configuration ### Claude Code Settings Configure IDE integration through Claude Code's settings: 1. Run `claude` 2. Enter the `/config` command 3. Set the diff tool to `auto` for automatic IDE detection ### Plugin Settings Configure the Claude Code plugin by going to **Settings → Tools → Claude Code \[Beta]**: #### General Settings * **Claude command**: Specify a custom command to run Claude (for example, `claude`, `/usr/local/bin/claude`, or `npx @anthropic/claude`) * **Suppress notification for Claude command not found**: Skip notifications about not finding the Claude command * **Enable using Option+Enter for multi-line prompts** (macOS only): When enabled, Option+Enter inserts new lines in Claude Code prompts. Disable if experiencing issues with the Option key being captured unexpectedly (requires terminal restart) * **Enable automatic updates**: Automatically check for and install plugin updates (applied on restart) For WSL users: Set `wsl -d Ubuntu -- bash -lic "claude"` as your Claude command (replace `Ubuntu` with your WSL distribution name) #### ESC Key Configuration If the ESC key doesn't interrupt Claude Code operations in JetBrains terminals: 1. Go to **Settings → Tools → Terminal** 2. Either: * Uncheck "Move focus to the editor with Escape", or * Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut 3. Apply the changes This allows the ESC key to properly interrupt Claude Code operations. ## Special Configurations ### Remote Development When using JetBrains Remote Development, you must install the plugin in the remote host via **Settings → Plugin (Host)**. The plugin must be installed on the remote host, not on your local client machine. ### WSL Configuration WSL users may need additional configuration for IDE detection to work properly. See our [WSL troubleshooting guide](/en/troubleshooting#jetbrains-ide-not-detected-on-wsl2) for detailed setup instructions. WSL configuration may require: * Proper terminal configuration * Networking mode adjustments * Firewall settings updates ## Troubleshooting ### Plugin Not Working * Ensure you're running Claude Code from the project root directory * Check that the JetBrains plugin is enabled in the IDE settings * Completely restart the IDE (you may need to do this multiple times) * For Remote Development, ensure the plugin is installed in the remote host ### IDE Not Detected * Verify the plugin is installed and enabled * Restart the IDE completely * Check that you're running Claude Code from the integrated terminal * For WSL users, see the [WSL troubleshooting guide](/en/troubleshooting#jetbrains-ide-not-detected-on-wsl2) ### Command Not Found If clicking the Claude icon shows "command not found": 1. Verify Claude Code is installed: `npm list -g @anthropic-ai/claude-code` 2. Configure the Claude command path in plugin settings 3. For WSL users, use the WSL command format mentioned in the configuration section ## Security Considerations When Claude Code runs in a JetBrains IDE with auto-edit permissions enabled, it may be able to modify IDE configuration files that can be automatically executed by your IDE. This may increase the risk of running Claude Code in auto-edit mode and allow bypassing Claude Code's permission prompts for bash execution. When running in JetBrains IDEs, consider: * Using manual approval mode for edits * Taking extra care to ensure Claude is only used with trusted prompts * Being aware of which files Claude Code has access to modify For additional help, see our [troubleshooting guide](/en/troubleshooting). --- # Source: https://code.claude.com/docs/en/keybindings.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Customize keyboard shortcuts > Customize keyboard shortcuts in Claude Code with a keybindings configuration file. Claude Code supports customizable keyboard shortcuts. Run `/keybindings` to create or open your configuration file at `~/.claude/keybindings.json`. ## Configuration file The keybindings configuration file is an object with a `bindings` array. Each block specifies a context and a map of keystrokes to actions. Changes to the keybindings file are automatically detected and applied without restarting Claude Code. | Field | Description | | :--------- | :------------------------------------------------- | | `$schema` | Optional JSON Schema URL for editor autocompletion | | `$docs` | Optional documentation URL | | `bindings` | Array of binding blocks by context | This example binds `Ctrl+E` to open an external editor in the chat context, and unbinds `Ctrl+U`: ```json theme={null} { "$schema": "https://platform.claude.com/docs/schemas/claude-code/keybindings.json", "$docs": "https://code.claude.com/docs/en/keybindings", "bindings": [ { "context": "Chat", "bindings": { "ctrl+e": "chat:externalEditor", "ctrl+u": null } } ] } ``` ## Contexts Each binding block specifies a **context** where the bindings apply: | Context | Description | | :---------------- | :----------------------------------------------- | | `Global` | Applies everywhere in the app | | `Chat` | Main chat input area | | `Autocomplete` | Autocomplete menu is open | | `Settings` | Settings menu (escape-only dismiss) | | `Confirmation` | Permission and confirmation dialogs | | `Tabs` | Tab navigation components | | `Help` | Help menu is visible | | `Transcript` | Transcript viewer | | `HistorySearch` | History search mode (Ctrl+R) | | `Task` | Background task is running | | `ThemePicker` | Theme picker dialog | | `Attachments` | Image/attachment bar navigation | | `Footer` | Footer indicator navigation (tasks, teams, diff) | | `MessageSelector` | Rewind dialog message selection | | `DiffDialog` | Diff viewer navigation | | `ModelPicker` | Model picker effort level | | `Select` | Generic select/list components | | `Plugin` | Plugin dialog (browse, discover, manage) | ## Available actions Actions follow a `namespace:action` format, such as `chat:submit` to send a message or `app:toggleTodos` to show the task list. Each context has specific actions available. ### App actions Actions available in the `Global` context: | Action | Default | Description | | :--------------------- | :------ | :-------------------------- | | `app:interrupt` | Ctrl+C | Cancel current operation | | `app:exit` | Ctrl+D | Exit Claude Code | | `app:toggleTodos` | Ctrl+T | Toggle task list visibility | | `app:toggleTranscript` | Ctrl+O | Toggle verbose transcript | ### History actions Actions for navigating command history: | Action | Default | Description | | :----------------- | :------ | :-------------------- | | `history:search` | Ctrl+R | Open history search | | `history:previous` | Up | Previous history item | | `history:next` | Down | Next history item | ### Chat actions Actions available in the `Chat` context: | Action | Default | Description | | :-------------------- | :------------------------ | :----------------------- | | `chat:cancel` | Escape | Cancel current input | | `chat:cycleMode` | Shift+Tab\* | Cycle permission modes | | `chat:modelPicker` | Cmd+P / Meta+P | Open model picker | | `chat:thinkingToggle` | Cmd+T / Meta+T | Toggle extended thinking | | `chat:submit` | Enter | Submit message | | `chat:undo` | Ctrl+\_ | Undo last action | | `chat:externalEditor` | Ctrl+G | Open in external editor | | `chat:stash` | Ctrl+S | Stash current prompt | | `chat:imagePaste` | Ctrl+V (Alt+V on Windows) | Paste image | \*On Windows without VT mode (Node \<24.2.0/\<22.17.0, Bun \<1.2.23), defaults to Meta+M. ### Autocomplete actions Actions available in the `Autocomplete` context: | Action | Default | Description | | :---------------------- | :------ | :------------------ | | `autocomplete:accept` | Tab | Accept suggestion | | `autocomplete:dismiss` | Escape | Dismiss menu | | `autocomplete:previous` | Up | Previous suggestion | | `autocomplete:next` | Down | Next suggestion | ### Confirmation actions Actions available in the `Confirmation` context: | Action | Default | Description | | :-------------------------- | :-------- | :---------------------------- | | `confirm:yes` | Y, Enter | Confirm action | | `confirm:no` | N, Escape | Decline action | | `confirm:previous` | Up | Previous option | | `confirm:next` | Down | Next option | | `confirm:nextField` | Tab | Next field | | `confirm:previousField` | (unbound) | Previous field | | `confirm:cycleMode` | Shift+Tab | Cycle permission modes | | `confirm:toggleExplanation` | Ctrl+E | Toggle permission explanation | ### Permission actions Actions available in the `Confirmation` context for permission dialogs: | Action | Default | Description | | :----------------------- | :------ | :--------------------------- | | `permission:toggleDebug` | Ctrl+D | Toggle permission debug info | ### Transcript actions Actions available in the `Transcript` context: | Action | Default | Description | | :------------------------- | :------------- | :---------------------- | | `transcript:toggleShowAll` | Ctrl+E | Toggle show all content | | `transcript:exit` | Ctrl+C, Escape | Exit transcript view | ### History search actions Actions available in the `HistorySearch` context: | Action | Default | Description | | :---------------------- | :---------- | :----------------------- | | `historySearch:next` | Ctrl+R | Next match | | `historySearch:accept` | Escape, Tab | Accept selection | | `historySearch:cancel` | Ctrl+C | Cancel search | | `historySearch:execute` | Enter | Execute selected command | ### Task actions Actions available in the `Task` context: | Action | Default | Description | | :---------------- | :------ | :---------------------- | | `task:background` | Ctrl+B | Background current task | ### Theme actions Actions available in the `ThemePicker` context: | Action | Default | Description | | :------------------------------- | :------ | :------------------------- | | `theme:toggleSyntaxHighlighting` | Ctrl+T | Toggle syntax highlighting | ### Help actions Actions available in the `Help` context: | Action | Default | Description | | :------------- | :------ | :-------------- | | `help:dismiss` | Escape | Close help menu | ### Tabs actions Actions available in the `Tabs` context: | Action | Default | Description | | :-------------- | :-------------- | :----------- | | `tabs:next` | Tab, Right | Next tab | | `tabs:previous` | Shift+Tab, Left | Previous tab | ### Attachments actions Actions available in the `Attachments` context: | Action | Default | Description | | :--------------------- | :---------------- | :------------------------- | | `attachments:next` | Right | Next attachment | | `attachments:previous` | Left | Previous attachment | | `attachments:remove` | Backspace, Delete | Remove selected attachment | | `attachments:exit` | Down, Escape | Exit attachment bar | ### Footer actions Actions available in the `Footer` context: | Action | Default | Description | | :---------------------- | :------ | :------------------------ | | `footer:next` | Right | Next footer item | | `footer:previous` | Left | Previous footer item | | `footer:openSelected` | Enter | Open selected footer item | | `footer:clearSelection` | Escape | Clear footer selection | ### Message selector actions Actions available in the `MessageSelector` context: | Action | Default | Description | | :----------------------- | :---------------------------------------- | :---------------- | | `messageSelector:up` | Up, K | Move up in list | | `messageSelector:down` | Down, J | Move down in list | | `messageSelector:top` | Ctrl+Up, Shift+Up, Meta+Up, Shift+K | Jump to top | | `messageSelector:bottom` | Ctrl+Down, Shift+Down, Meta+Down, Shift+J | Jump to bottom | | `messageSelector:select` | Enter | Select message | ### Diff actions Actions available in the `DiffDialog` context: | Action | Default | Description | | :-------------------- | :----------------- | :--------------------- | | `diff:dismiss` | Escape | Close diff viewer | | `diff:previousSource` | Left | Previous diff source | | `diff:nextSource` | Right | Next diff source | | `diff:previousFile` | Up | Previous file in diff | | `diff:nextFile` | Down | Next file in diff | | `diff:viewDetails` | Enter | View diff details | | `diff:back` | (context-specific) | Go back in diff viewer | ### Model picker actions Actions available in the `ModelPicker` context: | Action | Default | Description | | :--------------------------- | :------ | :-------------------- | | `modelPicker:decreaseEffort` | Left | Decrease effort level | | `modelPicker:increaseEffort` | Right | Increase effort level | ### Select actions Actions available in the `Select` context: | Action | Default | Description | | :---------------- | :-------------- | :--------------- | | `select:next` | Down, J, Ctrl+N | Next option | | `select:previous` | Up, K, Ctrl+P | Previous option | | `select:accept` | Enter | Accept selection | | `select:cancel` | Escape | Cancel selection | ### Plugin actions Actions available in the `Plugin` context: | Action | Default | Description | | :--------------- | :------ | :----------------------- | | `plugin:toggle` | Space | Toggle plugin selection | | `plugin:install` | I | Install selected plugins | ### Settings actions Actions available in the `Settings` context: | Action | Default | Description | | :---------------- | :------ | :---------------------------------- | | `settings:search` | / | Enter search mode | | `settings:retry` | R | Retry loading usage data (on error) | ## Keystroke syntax ### Modifiers Use modifier keys with the `+` separator: * `ctrl` or `control` - Control key * `alt`, `opt`, or `option` - Alt/Option key * `shift` - Shift key * `meta`, `cmd`, or `command` - Meta/Command key For example: ``` ctrl+k Single key with modifier shift+tab Shift + Tab meta+p Command/Meta + P ctrl+shift+c Multiple modifiers ``` ### Uppercase letters A standalone uppercase letter implies Shift. For example, `K` is equivalent to `shift+k`. This is useful for vim-style bindings where uppercase and lowercase keys have different meanings. Uppercase letters with modifiers (e.g., `ctrl+K`) are treated as stylistic and do **not** imply Shift — `ctrl+K` is the same as `ctrl+k`. ### Chords Chords are sequences of keystrokes separated by spaces: ``` ctrl+k ctrl+s Press Ctrl+K, release, then Ctrl+S ``` ### Special keys * `escape` or `esc` - Escape key * `enter` or `return` - Enter key * `tab` - Tab key * `space` - Space bar * `up`, `down`, `left`, `right` - Arrow keys * `backspace`, `delete` - Delete keys ## Unbind default shortcuts Set an action to `null` to unbind a default shortcut: ```json theme={null} { "bindings": [ { "context": "Chat", "bindings": { "ctrl+s": null } } ] } ``` ## Reserved shortcuts These shortcuts cannot be rebound: | Shortcut | Reason | | :------- | :------------------------- | | Ctrl+C | Hardcoded interrupt/cancel | | Ctrl+D | Hardcoded exit | ## Terminal conflicts Some shortcuts may conflict with terminal multiplexers: | Shortcut | Conflict | | :------- | :-------------------------------- | | Ctrl+B | tmux prefix (press twice to send) | | Ctrl+A | GNU screen prefix | | Ctrl+Z | Unix process suspend (SIGTSTP) | ## Vim mode interaction When vim mode is enabled (`/vim`), keybindings and vim mode operate independently: * **Vim mode** handles input at the text input level (cursor movement, modes, motions) * **Keybindings** handle actions at the component level (toggle todos, submit, etc.) * The Escape key in vim mode switches INSERT to NORMAL mode; it does not trigger `chat:cancel` * Most Ctrl+key shortcuts pass through vim mode to the keybinding system * In vim NORMAL mode, `?` shows the help menu (vim behavior) ## Validation Claude Code validates your keybindings and shows warnings for: * Parse errors (invalid JSON or structure) * Invalid context names * Reserved shortcut conflicts * Terminal multiplexer conflicts * Duplicate bindings in the same context Run `/doctor` to see any keybinding warnings. --- # Source: https://code.claude.com/docs/en/legal-and-compliance.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Legal and compliance > Legal agreements, compliance certifications, and security information for Claude Code. ## Legal agreements ### License Your use of Claude Code is subject to: * [Commercial Terms](https://www.anthropic.com/legal/commercial-terms) - for Team, Enterprise, and Claude API users * [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) - for Free, Pro, and Max users ### Commercial agreements Whether you're using the Claude API directly (1P) or accessing it through AWS Bedrock or Google Vertex (3P), your existing commercial agreement will apply to Claude Code usage, unless we've mutually agreed otherwise. ## Compliance ### Healthcare compliance (BAA) If a customer has a Business Associate Agreement (BAA) with us, and wants to use Claude Code, the BAA will automatically extend to cover Claude Code if the customer has executed a BAA and has Zero Data Retention (ZDR) activated. The BAA will be applicable to that customer's API traffic flowing through Claude Code. ## Security and trust ### Trust and safety You can find more information in the [Anthropic Trust Center](https://trust.anthropic.com) and [Transparency Hub](https://www.anthropic.com/transparency). ### Security vulnerability reporting Anthropic manages our security program through HackerOne. [Use this form to report vulnerabilities](https://hackerone.com/anthropic-vdp/reports/new?type=team\&report_type=vulnerability). *** © Anthropic PBC. All rights reserved. Use is subject to applicable Anthropic Terms of Service. --- # Source: https://code.claude.com/docs/en/llm-gateway.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # LLM gateway configuration > Learn how to configure Claude Code to work with LLM gateway solutions. Covers gateway requirements, authentication configuration, model selection, and provider-specific endpoint setup. LLM gateways provide a centralized proxy layer between Claude Code and model providers, often providing: * **Centralized authentication** - Single point for API key management * **Usage tracking** - Monitor usage across teams and projects * **Cost controls** - Implement budgets and rate limits * **Audit logging** - Track all model interactions for compliance * **Model routing** - Switch between providers without code changes ## Gateway requirements For an LLM gateway to work with Claude Code, it must meet the following requirements: **API format** The gateway must expose to clients at least one of the following API formats: 1. **Anthropic Messages**: `/v1/messages`, `/v1/messages/count_tokens` * Must forward request headers: `anthropic-beta`, `anthropic-version` 2. **Bedrock InvokeModel**: `/invoke`, `/invoke-with-response-stream` * Must preserve request body fields: `anthropic_beta`, `anthropic_version` 3. **Vertex rawPredict**: `:rawPredict`, `:streamRawPredict`, `/count-tokens:rawPredict` * Must forward request headers: `anthropic-beta`, `anthropic-version` Failure to forward headers or preserve body fields may result in reduced functionality or inability to use Claude Code features. Claude Code determines which features to enable based on the API format. When using the Anthropic Messages format with Bedrock or Vertex, you may need to set environment variable `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`. ## Configuration ### Model selection By default, Claude Code will use standard model names for the selected API format. If you have configured custom model names in your gateway, use the environment variables documented in [Model configuration](/en/model-config) to match your custom names. ## LiteLLM configuration LiteLLM is a third-party proxy service. Anthropic doesn't endorse, maintain, or audit LiteLLM's security or functionality. This guide is provided for informational purposes and may become outdated. Use at your own discretion. ### Prerequisites * Claude Code updated to the latest version * LiteLLM Proxy Server deployed and accessible * Access to Claude models through your chosen provider ### Basic LiteLLM setup **Configure Claude Code**: #### Authentication methods ##### Static API key Simplest method using a fixed API key: ```bash theme={null} # Set in environment export ANTHROPIC_AUTH_TOKEN=sk-litellm-static-key # Or in Claude Code settings { "env": { "ANTHROPIC_AUTH_TOKEN": "sk-litellm-static-key" } } ``` This value will be sent as the `Authorization` header. ##### Dynamic API key with helper For rotating keys or per-user authentication: 1. Create an API key helper script: ```bash theme={null} #!/bin/bash # ~/bin/get-litellm-key.sh # Example: Fetch key from vault vault kv get -field=api_key secret/litellm/claude-code # Example: Generate JWT token jwt encode \ --secret="${JWT_SECRET}" \ --exp="+1h" \ '{"user":"'${USER}'","team":"engineering"}' ``` 2. Configure Claude Code settings to use the helper: ```json theme={null} { "apiKeyHelper": "~/bin/get-litellm-key.sh" } ``` 3. Set token refresh interval: ```bash theme={null} # Refresh every hour (3600000 ms) export CLAUDE_CODE_API_KEY_HELPER_TTL_MS=3600000 ``` This value will be sent as `Authorization` and `X-Api-Key` headers. The `apiKeyHelper` has lower precedence than `ANTHROPIC_AUTH_TOKEN` or `ANTHROPIC_API_KEY`. #### Unified endpoint (recommended) Using LiteLLM's [Anthropic format endpoint](https://docs.litellm.ai/docs/anthropic_unified): ```bash theme={null} export ANTHROPIC_BASE_URL=https://litellm-server:4000 ``` **Benefits of the unified endpoint over pass-through endpoints:** * Load balancing * Fallbacks * Consistent support for cost tracking and end-user tracking #### Provider-specific pass-through endpoints (alternative) ##### Claude API through LiteLLM Using [pass-through endpoint](https://docs.litellm.ai/docs/pass_through/anthropic_completion): ```bash theme={null} export ANTHROPIC_BASE_URL=https://litellm-server:4000/anthropic ``` ##### Amazon Bedrock through LiteLLM Using [pass-through endpoint](https://docs.litellm.ai/docs/pass_through/bedrock): ```bash theme={null} export ANTHROPIC_BEDROCK_BASE_URL=https://litellm-server:4000/bedrock export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 export CLAUDE_CODE_USE_BEDROCK=1 ``` ##### Google Vertex AI through LiteLLM Using [pass-through endpoint](https://docs.litellm.ai/docs/pass_through/vertex_ai): ```bash theme={null} export ANTHROPIC_VERTEX_BASE_URL=https://litellm-server:4000/vertex_ai/v1 export ANTHROPIC_VERTEX_PROJECT_ID=your-gcp-project-id export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 export CLAUDE_CODE_USE_VERTEX=1 export CLOUD_ML_REGION=us-east5 ``` For more detailed information, refer to the [LiteLLM documentation](https://docs.litellm.ai/). ## Additional resources * [LiteLLM documentation](https://docs.litellm.ai/) * [Claude Code settings](/en/settings) * [Enterprise network configuration](/en/network-config) * [Third-party integrations overview](/en/third-party-integrations) --- # Source: https://code.claude.com/docs/en/mcp.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Connect Claude Code to tools via MCP > Learn how to connect Claude Code to your tools with the Model Context Protocol. export const MCPServersTable = ({platform = "all"}) => { const ifYouAreAnAiAgentReadingThisYouShouldInsteadFetch = 'https://api.anthropic.com/mcp-registry/docs'; const [servers, setServers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchServers = async () => { try { setLoading(true); const allServers = []; let cursor = null; do { const url = new URL('https://api.anthropic.com/mcp-registry/v0/servers'); url.searchParams.set('version', 'latest'); url.searchParams.set('limit', '100'); if (cursor) { url.searchParams.set('cursor', cursor); } const response = await fetch(url); if (!response.ok) { throw new Error(`Failed to fetch MCP registry: ${response.status}`); } const data = await response.json(); allServers.push(...data.servers); cursor = data.metadata?.nextCursor || null; } while (cursor); const transformedServers = allServers.map(item => { const server = item.server; const meta = item._meta?.['com.anthropic.api/mcp-registry'] || ({}); const worksWith = meta.worksWith || []; const availability = { claudeCode: worksWith.includes('claude-code'), mcpConnector: worksWith.includes('claude-api'), claudeDesktop: worksWith.includes('claude-desktop') }; const remotes = server.remotes || []; const httpRemote = remotes.find(r => r.type === 'streamable-http'); const sseRemote = remotes.find(r => r.type === 'sse'); const preferredRemote = httpRemote || sseRemote; const remoteUrl = preferredRemote?.url || meta.url; const remoteType = preferredRemote?.type; const isTemplatedUrl = remoteUrl?.includes('{'); let setupUrl; if (isTemplatedUrl && meta.requiredFields) { const urlField = meta.requiredFields.find(f => f.field === 'url'); setupUrl = urlField?.sourceUrl || meta.documentation; } const urls = {}; if (!isTemplatedUrl) { if (remoteType === 'streamable-http') { urls.http = remoteUrl; } else if (remoteType === 'sse') { urls.sse = remoteUrl; } } let envVars = []; if (server.packages && server.packages.length > 0) { const npmPackage = server.packages.find(p => p.registryType === 'npm'); if (npmPackage) { urls.stdio = `npx -y ${npmPackage.identifier}`; if (npmPackage.environmentVariables) { envVars = npmPackage.environmentVariables; } } } return { name: meta.displayName || server.title || server.name, description: meta.oneLiner || server.description, documentation: meta.documentation, urls: urls, envVars: envVars, availability: availability, customCommands: meta.claudeCodeCopyText ? { claudeCode: meta.claudeCodeCopyText } : undefined, setupUrl: setupUrl }; }); setServers(transformedServers); setError(null); } catch (err) { setError(err.message); console.error('Error fetching MCP registry:', err); } finally { setLoading(false); } }; fetchServers(); }, []); const generateClaudeCodeCommand = server => { if (server.customCommands && server.customCommands.claudeCode) { return server.customCommands.claudeCode; } const serverSlug = server.name.toLowerCase().replace(/[^a-z0-9]/g, '-'); if (server.urls.http) { return `claude mcp add ${serverSlug} --transport http ${server.urls.http}`; } if (server.urls.sse) { return `claude mcp add ${serverSlug} --transport sse ${server.urls.sse}`; } if (server.urls.stdio) { const envFlags = server.envVars && server.envVars.length > 0 ? server.envVars.map(v => `--env ${v.name}=YOUR_${v.name}`).join(' ') : ''; const baseCommand = `claude mcp add ${serverSlug} --transport stdio`; return envFlags ? `${baseCommand} ${envFlags} -- ${server.urls.stdio}` : `${baseCommand} -- ${server.urls.stdio}`; } return null; }; if (loading) { return
Loading MCP servers...
; } if (error) { return
Error loading MCP servers: {error}
; } const filteredServers = servers.filter(server => { if (platform === "claudeCode") { return server.availability.claudeCode; } else if (platform === "mcpConnector") { return server.availability.mcpConnector; } else if (platform === "claudeDesktop") { return server.availability.claudeDesktop; } else if (platform === "all") { return true; } else { throw new Error(`Unknown platform: ${platform}`); } }); return <>
{filteredServers.map(server => { const claudeCodeCommand = generateClaudeCodeCommand(server); const mcpUrl = server.urls.http || server.urls.sse; const commandToShow = platform === "claudeCode" ? claudeCodeCommand : mcpUrl; return
{server.documentation ? {server.name} : {server.name}}

{server.description}

{server.setupUrl &&

Requires user-specific URL.{' '} Get your URL here .

} {commandToShow && !server.setupUrl && <>

{platform === "claudeCode" ? "Command" : "URL"}

{commandToShow}
}
; })}
; }; Claude Code can connect to hundreds of external tools and data sources through the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction), an open source standard for AI-tool integrations. MCP servers give Claude Code access to your tools, databases, and APIs. ## What you can do with MCP With MCP servers connected, you can ask Claude Code to: * **Implement features from issue trackers**: "Add the feature described in JIRA issue ENG-4521 and create a PR on GitHub." * **Analyze monitoring data**: "Check Sentry and Statsig to check the usage of the feature described in ENG-4521." * **Query databases**: "Find emails of 10 random users who used feature ENG-4521, based on our PostgreSQL database." * **Integrate designs**: "Update our standard email template based on the new Figma designs that were posted in Slack" * **Automate workflows**: "Create Gmail drafts inviting these 10 users to a feedback session about the new feature." ## Popular MCP servers Here are some commonly used MCP servers you can connect to Claude Code: Use third party MCP servers at your own risk - Anthropic has not verified the correctness or security of all these servers. Make sure you trust MCP servers you are installing. Be especially careful when using MCP servers that could fetch untrusted content, as these can expose you to prompt injection risk. **Need a specific integration?** [Find hundreds more MCP servers on GitHub](https://github.com/modelcontextprotocol/servers), or build your own using the [MCP SDK](https://modelcontextprotocol.io/quickstart/server). ## Installing MCP servers MCP servers can be configured in three different ways depending on your needs: ### Option 1: Add a remote HTTP server HTTP servers are the recommended option for connecting to remote MCP servers. This is the most widely supported transport for cloud-based services. ```bash theme={null} # Basic syntax claude mcp add --transport http # Real example: Connect to Notion claude mcp add --transport http notion https://mcp.notion.com/mcp # Example with Bearer token claude mcp add --transport http secure-api https://api.example.com/mcp \ --header "Authorization: Bearer your-token" ``` ### Option 2: Add a remote SSE server The SSE (Server-Sent Events) transport is deprecated. Use HTTP servers instead, where available. ```bash theme={null} # Basic syntax claude mcp add --transport sse # Real example: Connect to Asana claude mcp add --transport sse asana https://mcp.asana.com/sse # Example with authentication header claude mcp add --transport sse private-api https://api.company.com/sse \ --header "X-API-Key: your-key-here" ``` ### Option 3: Add a local stdio server Stdio servers run as local processes on your machine. They're ideal for tools that need direct system access or custom scripts. ```bash theme={null} # Basic syntax claude mcp add [options] -- [args...] # Real example: Add Airtable server claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \ -- npx -y airtable-mcp-server ``` **Important: Option ordering** All options (`--transport`, `--env`, `--scope`, `--header`) must come **before** the server name. The `--` (double dash) then separates the server name from the command and arguments that get passed to the MCP server. For example: * `claude mcp add --transport stdio myserver -- npx server` → runs `npx server` * `claude mcp add --transport stdio --env KEY=value myserver -- python server.py --port 8080` → runs `python server.py --port 8080` with `KEY=value` in environment This prevents conflicts between Claude's flags and the server's flags. ### Managing your servers Once configured, you can manage your MCP servers with these commands: ```bash theme={null} # List all configured servers claude mcp list # Get details for a specific server claude mcp get github # Remove a server claude mcp remove github # (within Claude Code) Check server status /mcp ``` ### Dynamic tool updates Claude Code supports MCP `list_changed` notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a `list_changed` notification, Claude Code automatically refreshes the available capabilities from that server. Tips: * Use the `--scope` flag to specify where the configuration is stored: * `local` (default): Available only to you in the current project (was called `project` in older versions) * `project`: Shared with everyone in the project via `.mcp.json` file * `user`: Available to you across all projects (was called `global` in older versions) * Set environment variables with `--env` flags (for example, `--env KEY=value`) * Configure MCP server startup timeout using the MCP\_TIMEOUT environment variable (for example, `MCP_TIMEOUT=10000 claude` sets a 10-second timeout) * Claude Code will display a warning when MCP tool output exceeds 10,000 tokens. To increase this limit, set the `MAX_MCP_OUTPUT_TOKENS` environment variable (for example, `MAX_MCP_OUTPUT_TOKENS=50000`) * Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication **Windows Users**: On native Windows (not WSL), local MCP servers that use `npx` require the `cmd /c` wrapper to ensure proper execution. ```bash theme={null} # This creates command="cmd" which Windows can execute claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package ``` Without the `cmd /c` wrapper, you'll encounter "Connection closed" errors because Windows cannot directly execute `npx`. (See the note above for an explanation of the `--` parameter.) ### Plugin-provided MCP servers [Plugins](/en/plugins) can bundle MCP servers, automatically providing tools and integrations when the plugin is enabled. Plugin MCP servers work identically to user-configured servers. **How plugin MCP servers work**: * Plugins define MCP servers in `.mcp.json` at the plugin root or inline in `plugin.json` * When a plugin is enabled, its MCP servers start automatically * Plugin MCP tools appear alongside manually configured MCP tools * Plugin servers are managed through plugin installation (not `/mcp` commands) **Example plugin MCP configuration**: In `.mcp.json` at plugin root: ```json theme={null} { "database-tools": { "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server", "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"], "env": { "DB_URL": "${DB_URL}" } } } ``` Or inline in `plugin.json`: ```json theme={null} { "name": "my-plugin", "mcpServers": { "plugin-api": { "command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server", "args": ["--port", "8080"] } } } ``` **Plugin MCP features**: * **Automatic lifecycle**: Servers start when plugin enables, but you must restart Claude Code to apply MCP server changes (enabling or disabling) * **Environment variables**: Use `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths * **User environment access**: Access to same environment variables as manually configured servers * **Multiple transport types**: Support stdio, SSE, and HTTP transports (transport support may vary by server) **Viewing plugin MCP servers**: ```bash theme={null} # Within Claude Code, see all MCP servers including plugin ones /mcp ``` Plugin servers appear in the list with indicators showing they come from plugins. **Benefits of plugin MCP servers**: * **Bundled distribution**: Tools and servers packaged together * **Automatic setup**: No manual MCP configuration needed * **Team consistency**: Everyone gets the same tools when plugin is installed See the [plugin components reference](/en/plugins-reference#mcp-servers) for details on bundling MCP servers with plugins. ## MCP installation scopes MCP servers can be configured at three different scope levels, each serving distinct purposes for managing server accessibility and sharing. Understanding these scopes helps you determine the best way to configure servers for your specific needs. ### Local scope Local-scoped servers represent the default configuration level and are stored in `~/.claude.json` under your project's path. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn't be shared. The term "local scope" for MCP servers differs from general local settings. MCP local-scoped servers are stored in `~/.claude.json` (your home directory), while general local settings use `.claude/settings.local.json` (in the project directory). See [Settings](/en/settings#settings-files) for details on settings file locations. ```bash theme={null} # Add a local-scoped server (default) claude mcp add --transport http stripe https://mcp.stripe.com # Explicitly specify local scope claude mcp add --transport http stripe --scope local https://mcp.stripe.com ``` ### Project scope Project-scoped servers enable team collaboration by storing configurations in a `.mcp.json` file at your project's root directory. This file is designed to be checked into version control, ensuring all team members have access to the same MCP tools and services. When you add a project-scoped server, Claude Code automatically creates or updates this file with the appropriate configuration structure. ```bash theme={null} # Add a project-scoped server claude mcp add --transport http paypal --scope project https://mcp.paypal.com/mcp ``` The resulting `.mcp.json` file follows a standardized format: ```json theme={null} { "mcpServers": { "shared-server": { "command": "/path/to/server", "args": [], "env": {} } } } ``` For security reasons, Claude Code prompts for approval before using project-scoped servers from `.mcp.json` files. If you need to reset these approval choices, use the `claude mcp reset-project-choices` command. ### User scope User-scoped servers are stored in `~/.claude.json` and provide cross-project accessibility, making them available across all projects on your machine while remaining private to your user account. This scope works well for personal utility servers, development tools, or services you frequently use across different projects. ```bash theme={null} # Add a user server claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic ``` ### Choosing the right scope Select your scope based on: * **Local scope**: Personal servers, experimental configurations, or sensitive credentials specific to one project * **Project scope**: Team-shared servers, project-specific tools, or services required for collaboration * **User scope**: Personal utilities needed across multiple projects, development tools, or frequently used services **Where are MCP servers stored?** * **User and local scope**: `~/.claude.json` (in the `mcpServers` field or under project paths) * **Project scope**: `.mcp.json` in your project root (checked into source control) * **Managed**: `managed-mcp.json` in system directories (see [Managed MCP configuration](#managed-mcp-configuration)) ### Scope hierarchy and precedence MCP server configurations follow a clear precedence hierarchy. When servers with the same name exist at multiple scopes, the system resolves conflicts by prioritizing local-scoped servers first, followed by project-scoped servers, and finally user-scoped servers. This design ensures that personal configurations can override shared ones when needed. ### Environment variable expansion in `.mcp.json` Claude Code supports environment variable expansion in `.mcp.json` files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys. **Supported syntax:** * `${VAR}` - Expands to the value of environment variable `VAR` * `${VAR:-default}` - Expands to `VAR` if set, otherwise uses `default` **Expansion locations:** Environment variables can be expanded in: * `command` - The server executable path * `args` - Command-line arguments * `env` - Environment variables passed to the server * `url` - For HTTP server types * `headers` - For HTTP server authentication **Example with variable expansion:** ```json theme={null} { "mcpServers": { "api-server": { "type": "http", "url": "${API_BASE_URL:-https://api.example.com}/mcp", "headers": { "Authorization": "Bearer ${API_KEY}" } } } } ``` If a required environment variable is not set and has no default value, Claude Code will fail to parse the config. ## Practical examples {/* ### Example: Automate browser testing with Playwright ```bash # 1. Add the Playwright MCP server claude mcp add --transport stdio playwright -- npx -y @playwright/mcp@latest # 2. Write and run browser tests > "Test if the login flow works with test@example.com" > "Take a screenshot of the checkout page on mobile" > "Verify that the search feature returns results" ``` */} ### Example: Monitor errors with Sentry ```bash theme={null} # 1. Add the Sentry MCP server claude mcp add --transport http sentry https://mcp.sentry.dev/mcp # 2. Use /mcp to authenticate with your Sentry account > /mcp # 3. Debug production issues > "What are the most common errors in the last 24 hours?" > "Show me the stack trace for error ID abc123" > "Which deployment introduced these new errors?" ``` ### Example: Connect to GitHub for code reviews ```bash theme={null} # 1. Add the GitHub MCP server claude mcp add --transport http github https://api.githubcopilot.com/mcp/ # 2. In Claude Code, authenticate if needed > /mcp # Select "Authenticate" for GitHub # 3. Now you can ask Claude to work with GitHub > "Review PR #456 and suggest improvements" > "Create a new issue for the bug we just found" > "Show me all open PRs assigned to me" ``` ### Example: Query your PostgreSQL database ```bash theme={null} # 1. Add the database server with your connection string claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \ --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics" # 2. Query your database naturally > "What's our total revenue this month?" > "Show me the schema for the orders table" > "Find customers who haven't made a purchase in 90 days" ``` ## Authenticate with remote MCP servers Many cloud-based MCP servers require authentication. Claude Code supports OAuth 2.0 for secure connections. For example: ```bash theme={null} claude mcp add --transport http sentry https://mcp.sentry.dev/mcp ``` In Claude code, use the command: ``` > /mcp ``` Then follow the steps in your browser to login. Tips: * Authentication tokens are stored securely and refreshed automatically * Use "Clear authentication" in the `/mcp` menu to revoke access * If your browser doesn't open automatically, copy the provided URL * OAuth authentication works with HTTP servers ## Add MCP servers from JSON configuration If you have a JSON configuration for an MCP server, you can add it directly: ```bash theme={null} # Basic syntax claude mcp add-json '' # Example: Adding an HTTP server with JSON configuration claude mcp add-json weather-api '{"type":"http","url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}' # Example: Adding a stdio server with JSON configuration claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}' ``` ```bash theme={null} claude mcp get weather-api ``` Tips: * Make sure the JSON is properly escaped in your shell * The JSON must conform to the MCP server configuration schema * You can use `--scope user` to add the server to your user configuration instead of the project-specific one ## Import MCP servers from Claude Desktop If you've already configured MCP servers in Claude Desktop, you can import them: ```bash theme={null} # Basic syntax claude mcp add-from-claude-desktop ``` After running the command, you'll see an interactive dialog that allows you to select which servers you want to import. ```bash theme={null} claude mcp list ``` Tips: * This feature only works on macOS and Windows Subsystem for Linux (WSL) * It reads the Claude Desktop configuration file from its standard location on those platforms * Use the `--scope user` flag to add servers to your user configuration * Imported servers will have the same names as in Claude Desktop * If servers with the same names already exist, they will get a numerical suffix (for example, `server_1`) ## Use Claude Code as an MCP server You can use Claude Code itself as an MCP server that other applications can connect to: ```bash theme={null} # Start Claude as a stdio MCP server claude mcp serve ``` You can use this in Claude Desktop by adding this configuration to claude\_desktop\_config.json: ```json theme={null} { "mcpServers": { "claude-code": { "type": "stdio", "command": "claude", "args": ["mcp", "serve"], "env": {} } } } ``` **Configuring the executable path**: The `command` field must reference the Claude Code executable. If the `claude` command is not in your system's PATH, you'll need to specify the full path to the executable. To find the full path: ```bash theme={null} which claude ``` Then use the full path in your configuration: ```json theme={null} { "mcpServers": { "claude-code": { "type": "stdio", "command": "/full/path/to/claude", "args": ["mcp", "serve"], "env": {} } } } ``` Without the correct executable path, you'll encounter errors like `spawn claude ENOENT`. Tips: * The server provides access to Claude's tools like View, Edit, LS, etc. * In Claude Desktop, try asking Claude to read files in a directory, make edits, and more. * Note that this MCP server is only exposing Claude Code's tools to your MCP client, so your own client is responsible for implementing user confirmation for individual tool calls. ## MCP output limits and warnings When MCP tools produce large outputs, Claude Code helps manage the token usage to prevent overwhelming your conversation context: * **Output warning threshold**: Claude Code displays a warning when any MCP tool output exceeds 10,000 tokens * **Configurable limit**: You can adjust the maximum allowed MCP output tokens using the `MAX_MCP_OUTPUT_TOKENS` environment variable * **Default limit**: The default maximum is 25,000 tokens To increase the limit for tools that produce large outputs: ```bash theme={null} # Set a higher limit for MCP tool outputs export MAX_MCP_OUTPUT_TOKENS=50000 claude ``` This is particularly useful when working with MCP servers that: * Query large datasets or databases * Generate detailed reports or documentation * Process extensive log files or debugging information If you frequently encounter output warnings with specific MCP servers, consider increasing the limit or configuring the server to paginate or filter its responses. ## Use MCP resources MCP servers can expose resources that you can reference using @ mentions, similar to how you reference files. ### Reference MCP resources Type `@` in your prompt to see available resources from all connected MCP servers. Resources appear alongside files in the autocomplete menu. Use the format `@server:protocol://resource/path` to reference a resource: ``` > Can you analyze @github:issue://123 and suggest a fix? ``` ``` > Please review the API documentation at @docs:file://api/authentication ``` You can reference multiple resources in a single prompt: ``` > Compare @postgres:schema://users with @docs:file://database/user-model ``` Tips: * Resources are automatically fetched and included as attachments when referenced * Resource paths are fuzzy-searchable in the @ mention autocomplete * Claude Code automatically provides tools to list and read MCP resources when servers support them * Resources can contain any type of content that the MCP server provides (text, JSON, structured data, etc.) ## Scale with MCP Tool Search When you have many MCP servers configured, tool definitions can consume a significant portion of your context window. MCP Tool Search solves this by dynamically loading tools on-demand instead of preloading all of them. ### How it works Claude Code automatically enables Tool Search when your MCP tool descriptions would consume more than 10% of the context window. You can [adjust this threshold](#configure-tool-search) or disable tool search entirely. When triggered: 1. MCP tools are deferred rather than loaded into context upfront 2. Claude uses a search tool to discover relevant MCP tools when needed 3. Only the tools Claude actually needs are loaded into context 4. MCP tools continue to work exactly as before from your perspective ### For MCP server authors If you're building an MCP server, the server instructions field becomes more useful with Tool Search enabled. Server instructions help Claude understand when to search for your tools, similar to how [skills](/en/skills) work. Add clear, descriptive server instructions that explain: * What category of tasks your tools handle * When Claude should search for your tools * Key capabilities your server provides ### Configure tool search Tool search runs in auto mode by default, meaning it activates only when your MCP tool definitions exceed the context threshold. If you have few tools, they load normally without tool search. This feature requires models that support `tool_reference` blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search. Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable: | Value | Behavior | | :--------- | :--------------------------------------------------------------------------------- | | `auto` | Activates when MCP tools exceed 10% of context (default) | | `auto:` | Activates at custom threshold, where `` is a percentage (e.g., `auto:5` for 5%) | | `true` | Always enabled | | `false` | Disabled, all MCP tools loaded upfront | ```bash theme={null} # Use a custom 5% threshold ENABLE_TOOL_SEARCH=auto:5 claude # Disable tool search entirely ENABLE_TOOL_SEARCH=false claude ``` Or set the value in your [settings.json `env` field](/en/settings#available-settings). You can also disable the MCPSearch tool specifically using the `disallowedTools` setting: ```json theme={null} { "permissions": { "deny": ["MCPSearch"] } } ``` ## Use MCP prompts as commands MCP servers can expose prompts that become available as commands in Claude Code. ### Execute MCP prompts Type `/` to see all available commands, including those from MCP servers. MCP prompts appear with the format `/mcp__servername__promptname`. ``` > /mcp__github__list_prs ``` Many prompts accept arguments. Pass them space-separated after the command: ``` > /mcp__github__pr_review 456 ``` ``` > /mcp__jira__create_issue "Bug in login flow" high ``` Tips: * MCP prompts are dynamically discovered from connected servers * Arguments are parsed based on the prompt's defined parameters * Prompt results are injected directly into the conversation * Server and prompt names are normalized (spaces become underscores) ## Managed MCP configuration For organizations that need centralized control over MCP servers, Claude Code supports two configuration options: 1. **Exclusive control with `managed-mcp.json`**: Deploy a fixed set of MCP servers that users cannot modify or extend 2. **Policy-based control with allowlists/denylists**: Allow users to add their own servers, but restrict which ones are permitted These options allow IT administrators to: * **Control which MCP servers employees can access**: Deploy a standardized set of approved MCP servers across the organization * **Prevent unauthorized MCP servers**: Restrict users from adding unapproved MCP servers * **Disable MCP entirely**: Remove MCP functionality completely if needed ### Option 1: Exclusive control with managed-mcp.json When you deploy a `managed-mcp.json` file, it takes **exclusive control** over all MCP servers. Users cannot add, modify, or use any MCP servers other than those defined in this file. This is the simplest approach for organizations that want complete control. System administrators deploy the configuration file to a system-wide directory: * macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json` * Linux and WSL: `/etc/claude-code/managed-mcp.json` * Windows: `C:\Program Files\ClaudeCode\managed-mcp.json` These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators. The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file: ```json theme={null} { "mcpServers": { "github": { "type": "http", "url": "https://api.githubcopilot.com/mcp/" }, "sentry": { "type": "http", "url": "https://mcp.sentry.dev/mcp" }, "company-internal": { "type": "stdio", "command": "/usr/local/bin/company-mcp-server", "args": ["--config", "/etc/company/mcp-config.json"], "env": { "COMPANY_API_URL": "https://internal.company.com" } } } } ``` ### Option 2: Policy-based control with allowlists and denylists Instead of taking exclusive control, administrators can allow users to configure their own MCP servers while enforcing restrictions on which servers are permitted. This approach uses `allowedMcpServers` and `deniedMcpServers` in the [managed settings file](/en/settings#settings-files). **Choosing between options**: Use Option 1 (`managed-mcp.json`) when you want to deploy a fixed set of servers with no user customization. Use Option 2 (allowlists/denylists) when you want to allow users to add their own servers within policy constraints. #### Restriction options Each entry in the allowlist or denylist can restrict servers in three ways: 1. **By server name** (`serverName`): Matches the configured name of the server 2. **By command** (`serverCommand`): Matches the exact command and arguments used to start stdio servers 3. **By URL pattern** (`serverUrl`): Matches remote server URLs with wildcard support **Important**: Each entry must have exactly one of `serverName`, `serverCommand`, or `serverUrl`. #### Example configuration ```json theme={null} { "allowedMcpServers": [ // Allow by server name { "serverName": "github" }, { "serverName": "sentry" }, // Allow by exact command (for stdio servers) { "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] }, { "serverCommand": ["python", "/usr/local/bin/approved-server.py"] }, // Allow by URL pattern (for remote servers) { "serverUrl": "https://mcp.company.com/*" }, { "serverUrl": "https://*.internal.corp/*" } ], "deniedMcpServers": [ // Block by server name { "serverName": "dangerous-server" }, // Block by exact command (for stdio servers) { "serverCommand": ["npx", "-y", "unapproved-package"] }, // Block by URL pattern (for remote servers) { "serverUrl": "https://*.untrusted.com/*" } ] } ``` #### How command-based restrictions work **Exact matching**: * Command arrays must match **exactly** - both the command and all arguments in the correct order * Example: `["npx", "-y", "server"]` will NOT match `["npx", "server"]` or `["npx", "-y", "server", "--flag"]` **Stdio server behavior**: * When the allowlist contains **any** `serverCommand` entries, stdio servers **must** match one of those commands * Stdio servers cannot pass by name alone when command restrictions are present * This ensures administrators can enforce which commands are allowed to run **Non-stdio server behavior**: * Remote servers (HTTP, SSE, WebSocket) use URL-based matching when `serverUrl` entries exist in the allowlist * If no URL entries exist, remote servers fall back to name-based matching * Command restrictions do not apply to remote servers #### How URL-based restrictions work URL patterns support wildcards using `*` to match any sequence of characters. This is useful for allowing entire domains or subdomains. **Wildcard examples**: * `https://mcp.company.com/*` - Allow all paths on a specific domain * `https://*.example.com/*` - Allow any subdomain of example.com * `http://localhost:*/*` - Allow any port on localhost **Remote server behavior**: * When the allowlist contains **any** `serverUrl` entries, remote servers **must** match one of those URL patterns * Remote servers cannot pass by name alone when URL restrictions are present * This ensures administrators can enforce which remote endpoints are allowed ```json theme={null} { "allowedMcpServers": [ { "serverUrl": "https://mcp.company.com/*" }, { "serverUrl": "https://*.internal.corp/*" } ] } ``` **Result**: * HTTP server at `https://mcp.company.com/api`: ✅ Allowed (matches URL pattern) * HTTP server at `https://api.internal.corp/mcp`: ✅ Allowed (matches wildcard subdomain) * HTTP server at `https://external.com/mcp`: ❌ Blocked (doesn't match any URL pattern) * Stdio server with any command: ❌ Blocked (no name or command entries to match) ```json theme={null} { "allowedMcpServers": [ { "serverCommand": ["npx", "-y", "approved-package"] } ] } ``` **Result**: * Stdio server with `["npx", "-y", "approved-package"]`: ✅ Allowed (matches command) * Stdio server with `["node", "server.js"]`: ❌ Blocked (doesn't match command) * HTTP server named "my-api": ❌ Blocked (no name entries to match) ```json theme={null} { "allowedMcpServers": [ { "serverName": "github" }, { "serverCommand": ["npx", "-y", "approved-package"] } ] } ``` **Result**: * Stdio server named "local-tool" with `["npx", "-y", "approved-package"]`: ✅ Allowed (matches command) * Stdio server named "local-tool" with `["node", "server.js"]`: ❌ Blocked (command entries exist but doesn't match) * Stdio server named "github" with `["node", "server.js"]`: ❌ Blocked (stdio servers must match commands when command entries exist) * HTTP server named "github": ✅ Allowed (matches name) * HTTP server named "other-api": ❌ Blocked (name doesn't match) ```json theme={null} { "allowedMcpServers": [ { "serverName": "github" }, { "serverName": "internal-tool" } ] } ``` **Result**: * Stdio server named "github" with any command: ✅ Allowed (no command restrictions) * Stdio server named "internal-tool" with any command: ✅ Allowed (no command restrictions) * HTTP server named "github": ✅ Allowed (matches name) * Any server named "other": ❌ Blocked (name doesn't match) #### Allowlist behavior (`allowedMcpServers`) * `undefined` (default): No restrictions - users can configure any MCP server * Empty array `[]`: Complete lockdown - users cannot configure any MCP servers * List of entries: Users can only configure servers that match by name, command, or URL pattern #### Denylist behavior (`deniedMcpServers`) * `undefined` (default): No servers are blocked * Empty array `[]`: No servers are blocked * List of entries: Specified servers are explicitly blocked across all scopes #### Important notes * **Option 1 and Option 2 can be combined**: If `managed-mcp.json` exists, it has exclusive control and users cannot add servers. Allowlists/denylists still apply to the managed servers themselves. * **Denylist takes absolute precedence**: If a server matches a denylist entry (by name, command, or URL), it will be blocked even if it's on the allowlist * Name-based, command-based, and URL-based restrictions work together: a server passes if it matches **either** a name entry, a command entry, or a URL pattern (unless blocked by denylist) **When using `managed-mcp.json`**: Users cannot add MCP servers through `claude mcp add` or configuration files. The `allowedMcpServers` and `deniedMcpServers` settings still apply to filter which managed servers are actually loaded. --- # Source: https://code.claude.com/docs/en/memory.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Manage Claude's memory > Learn how to manage Claude Code's memory across sessions with different memory locations and best practices. Claude Code can remember your preferences across sessions, like style guidelines and common commands in your workflow. ## Determine memory type Claude Code offers four memory locations in a hierarchical structure, each serving a different purpose: | Memory Type | Location | Purpose | Use Case Examples | Shared With | | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- | | **Managed policy** | • macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`
• Linux: `/etc/claude-code/CLAUDE.md`
• Windows: `C:\Program Files\ClaudeCode\CLAUDE.md` | Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization | | **Project memory** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control | | **Project rules** | `./.claude/rules/*.md` | Modular, topic-specific project instructions | Language-specific guidelines, testing conventions, API standards | Team members via source control | | **User memory** | `~/.claude/CLAUDE.md` | Personal preferences for all projects | Code styling preferences, personal tooling shortcuts | Just you (all projects) | | **Project memory (local)** | `./CLAUDE.local.md` | Personal project-specific preferences | Your sandbox URLs, preferred test data | Just you (current project) | All memory files are automatically loaded into Claude Code's context when launched. Files higher in the hierarchy take precedence and are loaded first, providing a foundation that more specific memories build upon. CLAUDE.local.md files are automatically added to .gitignore, making them ideal for private project-specific preferences that shouldn't be checked into version control. ## CLAUDE.md imports CLAUDE.md files can import additional files using `@path/to/import` syntax. The following example imports 3 files: ``` See @README for project overview and @package.json for available npm commands for this project. # Additional Instructions - git workflow @docs/git-instructions.md ``` Both relative and absolute paths are allowed. Relative paths resolve relative to the file containing the import, not the working directory. For private per-project preferences that shouldn't be checked into version control, prefer `CLAUDE.local.md`: it is automatically loaded and added to `.gitignore`. If you work across multiple git worktrees, `CLAUDE.local.md` only exists in one. Use a home-directory import instead so all worktrees share the same personal instructions: ``` # Individual Preferences - @~/.claude/my-project-instructions.md ``` The first time Claude Code encounters external imports in a project, it shows an approval dialog listing the specific files. Approve to load them; decline to skip them. This is a one-time decision per project: once declined, the dialog does not resurface and the imports remain disabled. To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks. ``` This code span will not be treated as an import: `@anthropic-ai/claude-code` ``` Imported files can recursively import additional files, with a max-depth of 5 hops. You can see what memory files are loaded by running `/memory` command. ## How Claude looks up memories Claude Code reads memories recursively: starting in the cwd, Claude Code recurses up to (but not including) the root directory */* and reads any CLAUDE.md or CLAUDE.local.md files it finds. This is especially convenient when working in large repositories where you run Claude Code in *foo/bar/*, and have memories in both *foo/CLAUDE.md* and *foo/bar/CLAUDE.md*. Claude will also discover CLAUDE.md nested in subtrees under your current working directory. Instead of loading them at launch, they are only included when Claude reads files in those subtrees. ### Load memory from additional directories The `--add-dir` flag gives Claude access to additional directories outside your main working directory. By default, CLAUDE.md files from these directories are not loaded. To also load memory files (CLAUDE.md, .claude/CLAUDE.md, and .claude/rules/\*.md) from additional directories, set the `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` environment variable: ```bash theme={null} CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config ``` ## Directly edit memories with `/memory` Use the `/memory` command during a session to open any memory file in your system editor for more extensive additions or organization. ## Set up project memory Suppose you want to set up a CLAUDE.md file to store important project information, conventions, and frequently used commands. Project memory can be stored in either `./CLAUDE.md` or `./.claude/CLAUDE.md`. Bootstrap a CLAUDE.md for your codebase with the following command: ``` > /init ``` Tips: * Include frequently used commands (build, test, lint) to avoid repeated searches * Document code style preferences and naming conventions * Add important architectural patterns specific to your project * CLAUDE.md memories can be used for both instructions shared with your team and for your individual preferences. ## Modular rules with `.claude/rules/` For larger projects, you can organize instructions into multiple files using the `.claude/rules/` directory. This allows teams to maintain focused, well-organized rule files instead of one large CLAUDE.md. ### Basic structure Place markdown files in your project's `.claude/rules/` directory: ``` your-project/ ├── .claude/ │ ├── CLAUDE.md # Main project instructions │ └── rules/ │ ├── code-style.md # Code style guidelines │ ├── testing.md # Testing conventions │ └── security.md # Security requirements ``` All `.md` files in `.claude/rules/` are automatically loaded as project memory, with the same priority as `.claude/CLAUDE.md`. ### Path-specific rules Rules can be scoped to specific files using YAML frontmatter with the `paths` field. These conditional rules only apply when Claude is working with files matching the specified patterns. ```markdown theme={null} --- paths: - "src/api/**/*.ts" --- # API Development Rules - All API endpoints must include input validation - Use the standard error response format - Include OpenAPI documentation comments ``` Rules without a `paths` field are loaded unconditionally and apply to all files. ### Glob patterns The `paths` field supports standard glob patterns: | Pattern | Matches | | ---------------------- | ---------------------------------------- | | `**/*.ts` | All TypeScript files in any directory | | `src/**/*` | All files under `src/` directory | | `*.md` | Markdown files in the project root | | `src/components/*.tsx` | React components in a specific directory | You can specify multiple patterns: ```markdown theme={null} --- paths: - "src/**/*.ts" - "lib/**/*.ts" - "tests/**/*.test.ts" --- ``` Brace expansion is supported for matching multiple extensions or directories: ```markdown theme={null} --- paths: - "src/**/*.{ts,tsx}" - "{src,lib}/**/*.ts" --- # TypeScript/React Rules ``` This expands `src/**/*.{ts,tsx}` to match both `.ts` and `.tsx` files. ### Subdirectories Rules can be organized into subdirectories for better structure: ``` .claude/rules/ ├── frontend/ │ ├── react.md │ └── styles.md ├── backend/ │ ├── api.md │ └── database.md └── general.md ``` All `.md` files are discovered recursively. ### Symlinks The `.claude/rules/` directory supports symlinks, allowing you to share common rules across multiple projects: ```bash theme={null} # Symlink a shared rules directory ln -s ~/shared-claude-rules .claude/rules/shared # Symlink individual rule files ln -s ~/company-standards/security.md .claude/rules/security.md ``` Symlinks are resolved and their contents are loaded normally. Circular symlinks are detected and handled gracefully. ### User-level rules You can create personal rules that apply to all your projects in `~/.claude/rules/`: ``` ~/.claude/rules/ ├── preferences.md # Your personal coding preferences └── workflows.md # Your preferred workflows ``` User-level rules are loaded before project rules, giving project rules higher priority. Best practices for `.claude/rules/`: * **Keep rules focused**: Each file should cover one topic (e.g., `testing.md`, `api-design.md`) * **Use descriptive filenames**: The filename should indicate what the rules cover * **Use conditional rules sparingly**: Only add `paths` frontmatter when rules truly apply to specific file types * **Organize with subdirectories**: Group related rules (e.g., `frontend/`, `backend/`) ## Organization-level memory management Organizations can deploy centrally managed CLAUDE.md files that apply to all users. To set up organization-level memory management: 1. Create the managed memory file at the **Managed policy** location shown in the [memory types table above](#determine-memory-type). 2. Deploy via your configuration management system (MDM, Group Policy, Ansible, etc.) to ensure consistent distribution across all developer machines. ## Memory best practices * **Be specific**: "Use 2-space indentation" is better than "Format code properly". * **Use structure to organize**: Format each individual memory as a bullet point and group related memories under descriptive markdown headings. * **Review periodically**: Update memories as your project evolves to ensure Claude is always using the most up to date information and context. --- # Source: https://code.claude.com/docs/en/microsoft-foundry.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code on Microsoft Foundry > Learn about configuring Claude Code through Microsoft Foundry, including setup, configuration, and troubleshooting. ## Prerequisites Before configuring Claude Code with Microsoft Foundry, ensure you have: * An Azure subscription with access to Microsoft Foundry * RBAC permissions to create Microsoft Foundry resources and deployments * Azure CLI installed and configured (optional - only needed if you don't have another mechanism for getting credentials) ## Setup ### 1. Provision Microsoft Foundry resource First, create a Claude resource in Azure: 1. Navigate to the [Microsoft Foundry portal](https://ai.azure.com/) 2. Create a new resource, noting your resource name 3. Create deployments for the Claude models: * Claude Opus * Claude Sonnet * Claude Haiku ### 2. Configure Azure credentials Claude Code supports two authentication methods for Microsoft Foundry. Choose the method that best fits your security requirements. **Option A: API key authentication** 1. Navigate to your resource in the Microsoft Foundry portal 2. Go to the **Endpoints and keys** section 3. Copy **API Key** 4. Set the environment variable: ```bash theme={null} export ANTHROPIC_FOUNDRY_API_KEY=your-azure-api-key ``` **Option B: Microsoft Entra ID authentication** When `ANTHROPIC_FOUNDRY_API_KEY` is not set, Claude Code automatically uses the Azure SDK [default credential chain](https://learn.microsoft.com/en-us/azure/developer/javascript/sdk/authentication/credential-chains#defaultazurecredential-overview). This supports a variety of methods for authenticating local and remote workloads. On local environments, you commonly may use the Azure CLI: ```bash theme={null} az login ``` When using Microsoft Foundry, the `/login` and `/logout` commands are disabled since authentication is handled through Azure credentials. ### 3. Configure Claude Code Set the following environment variables to enable Microsoft Foundry. Note that your deployments' names are set as the model identifiers in Claude Code (may be optional if using suggested deployment names). ```bash theme={null} # Enable Microsoft Foundry integration export CLAUDE_CODE_USE_FOUNDRY=1 # Azure resource name (replace {resource} with your resource name) export ANTHROPIC_FOUNDRY_RESOURCE={resource} # Or provide the full base URL: # export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com/anthropic # Set models to your resource's deployment names export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-5' export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5' export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-1' ``` For more details on model configuration options, see [Model configuration](/en/model-config). ## Azure RBAC configuration The `Azure AI User` and `Cognitive Services User` default roles include all required permissions for invoking Claude models. For more restrictive permissions, create a custom role with the following: ```json theme={null} { "permissions": [ { "dataActions": [ "Microsoft.CognitiveServices/accounts/providers/*" ] } ] } ``` For details, see [Microsoft Foundry RBAC documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/concepts/rbac-azure-ai-foundry). ## Troubleshooting If you receive an error "Failed to get token from azureADTokenProvider: ChainedTokenCredential authentication failed": * Configure Entra ID on the environment, or set `ANTHROPIC_FOUNDRY_API_KEY`. ## Additional resources * [Microsoft Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry) * [Microsoft Foundry models](https://ai.azure.com/explore/models) * [Microsoft Foundry pricing](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/) --- # Source: https://code.claude.com/docs/en/sdk/migration-guide.md # Migrate to Claude Agent SDK Guide for migrating the Claude Code TypeScript and Python SDKs to the Claude Agent SDK --- ## Overview The Claude Code SDK has been renamed to the **Claude Agent SDK** and its documentation has been reorganized. This change reflects the SDK's broader capabilities for building AI agents beyond just coding tasks. ## What's Changed | Aspect | Old | New | | :----------------------- | :-------------------------- | :------------------------------- | | **Package Name (TS/JS)** | `@anthropic-ai/claude-code` | `@anthropic-ai/claude-agent-sdk` | | **Python Package** | `claude-code-sdk` | `claude-agent-sdk` | | **Documentation Location** | Claude Code docs | API Guide → Agent SDK section | **Documentation Changes:** The Agent SDK documentation has moved from the Claude Code docs to the API Guide under a dedicated [Agent SDK](/docs/en/agent-sdk/overview) section. The Claude Code docs now focus on the CLI tool and automation features. ## Migration Steps ### For TypeScript/JavaScript Projects **1. Uninstall the old package:** ```bash npm uninstall @anthropic-ai/claude-code ``` **2. Install the new package:** ```bash npm install @anthropic-ai/claude-agent-sdk ``` **3. Update your imports:** Change all imports from `@anthropic-ai/claude-code` to `@anthropic-ai/claude-agent-sdk`: ```typescript // Before import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-code"; // After import { query, tool, createSdkMcpServer, } from "@anthropic-ai/claude-agent-sdk"; ``` **4. Update package.json dependencies:** If you have the package listed in your `package.json`, update it: ```json // Before { "dependencies": { "@anthropic-ai/claude-code": "^1.0.0" } } // After { "dependencies": { "@anthropic-ai/claude-agent-sdk": "^0.1.0" } } ``` That's it! No other code changes are required. ### For Python Projects **1. Uninstall the old package:** ```bash pip uninstall claude-code-sdk ``` **2. Install the new package:** ```bash pip install claude-agent-sdk ``` **3. Update your imports:** Change all imports from `claude_code_sdk` to `claude_agent_sdk`: ```python # Before from claude_code_sdk import query, ClaudeCodeOptions # After from claude_agent_sdk import query, ClaudeAgentOptions ``` **4. Update type names:** Change `ClaudeCodeOptions` to `ClaudeAgentOptions`: ```python # Before from claude_agent_sdk import query, ClaudeCodeOptions options = ClaudeCodeOptions( model="claude-sonnet-4-5" ) # After from claude_agent_sdk import query, ClaudeAgentOptions options = ClaudeAgentOptions( model="claude-sonnet-4-5" ) ``` **5. Review [breaking changes](#breaking-changes)** Make any code changes needed to complete the migration. ## Breaking changes To improve isolation and explicit configuration, Claude Agent SDK v0.1.0 introduces breaking changes for users migrating from Claude Code SDK. Review this section carefully before migrating. ### Python: ClaudeCodeOptions renamed to ClaudeAgentOptions **What changed:** The Python SDK type `ClaudeCodeOptions` has been renamed to `ClaudeAgentOptions`. **Migration:** ```python # BEFORE (v0.0.x) from claude_agent_sdk import query, ClaudeCodeOptions options = ClaudeCodeOptions( model="claude-sonnet-4-5", permission_mode="acceptEdits" ) # AFTER (v0.1.0) from claude_agent_sdk import query, ClaudeAgentOptions options = ClaudeAgentOptions( model="claude-sonnet-4-5", permission_mode="acceptEdits" ) ``` **Why this changed:** The type name now matches the "Claude Agent SDK" branding and provides consistency across the SDK's naming conventions. ### System prompt no longer default **What changed:** The SDK no longer uses Claude Code's system prompt by default. **Migration:** ```typescript TypeScript // BEFORE (v0.0.x) - Used Claude Code's system prompt by default const result = query({ prompt: "Hello" }); // AFTER (v0.1.0) - Uses empty system prompt by default // To get the old behavior, explicitly request Claude Code's preset: const result = query({ prompt: "Hello", options: { systemPrompt: { type: "preset", preset: "claude_code" } } }); // Or use a custom system prompt: const result = query({ prompt: "Hello", options: { systemPrompt: "You are a helpful coding assistant" } }); ``` ```python Python # BEFORE (v0.0.x) - Used Claude Code's system prompt by default async for message in query(prompt="Hello"): print(message) # AFTER (v0.1.0) - Uses empty system prompt by default # To get the old behavior, explicitly request Claude Code's preset: from claude_agent_sdk import query, ClaudeAgentOptions async for message in query( prompt="Hello", options=ClaudeAgentOptions( system_prompt={"type": "preset", "preset": "claude_code"} # Use the preset ) ): print(message) # Or use a custom system prompt: async for message in query( prompt="Hello", options=ClaudeAgentOptions( system_prompt="You are a helpful coding assistant" ) ): print(message) ``` **Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code's CLI-focused instructions. ### Settings Sources No Longer Loaded by Default **What changed:** The SDK no longer reads from filesystem settings (CLAUDE.md, settings.json, slash commands, etc.) by default. **Migration:** ```typescript TypeScript // BEFORE (v0.0.x) - Loaded all settings automatically const result = query({ prompt: "Hello" }); // Would read from: // - ~/.claude/settings.json (user) // - .claude/settings.json (project) // - .claude/settings.local.json (local) // - CLAUDE.md files // - Custom slash commands // AFTER (v0.1.0) - No settings loaded by default // To get the old behavior: const result = query({ prompt: "Hello", options: { settingSources: ["user", "project", "local"] } }); // Or load only specific sources: const result = query({ prompt: "Hello", options: { settingSources: ["project"] // Only project settings } }); ``` ```python Python # BEFORE (v0.0.x) - Loaded all settings automatically async for message in query(prompt="Hello"): print(message) # Would read from: # - ~/.claude/settings.json (user) # - .claude/settings.json (project) # - .claude/settings.local.json (local) # - CLAUDE.md files # - Custom slash commands # AFTER (v0.1.0) - No settings loaded by default # To get the old behavior: from claude_agent_sdk import query, ClaudeAgentOptions async for message in query( prompt="Hello", options=ClaudeAgentOptions( setting_sources=["user", "project", "local"] ) ): print(message) # Or load only specific sources: async for message in query( prompt="Hello", options=ClaudeAgentOptions( setting_sources=["project"] # Only project settings ) ): print(message) ``` **Why this changed:** Ensures SDK applications have predictable behavior independent of local filesystem configurations. This is especially important for: - **CI/CD environments** - Consistent behavior without local customizations - **Deployed applications** - No dependency on filesystem settings - **Testing** - Isolated test environments - **Multi-tenant systems** - Prevent settings leakage between users **Backward compatibility:** If your application relied on filesystem settings (custom slash commands, CLAUDE.md instructions, etc.), add `settingSources: ['user', 'project', 'local']` to your options. ## Why the Rename? The Claude Code SDK was originally designed for coding tasks, but it has evolved into a powerful framework for building all types of AI agents. The new name "Claude Agent SDK" better reflects its capabilities: - Building business agents (legal assistants, finance advisors, customer support) - Creating specialized coding agents (SRE bots, security reviewers, code review agents) - Developing custom agents for any domain with tool use, MCP integration, and more ## Getting Help If you encounter any issues during migration: **For TypeScript/JavaScript:** 1. Check that all imports are updated to use `@anthropic-ai/claude-agent-sdk` 2. Verify your package.json has the new package name 3. Run `npm install` to ensure dependencies are updated **For Python:** 1. Check that all imports are updated to use `claude_agent_sdk` 2. Verify your requirements.txt or pyproject.toml has the new package name 3. Run `pip install claude-agent-sdk` to ensure the package is installed ## Next Steps - Explore the [Agent SDK Overview](/docs/en/agent-sdk/overview) to learn about available features - Check out the [TypeScript SDK Reference](/docs/en/agent-sdk/typescript) for detailed API documentation - Review the [Python SDK Reference](/docs/en/agent-sdk/python) for Python-specific documentation - Learn about [Custom Tools](/docs/en/agent-sdk/custom-tools) and [MCP Integration](/docs/en/agent-sdk/mcp) --- # Source: https://code.claude.com/docs/en/model-config.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Model configuration > Learn about the Claude Code model configuration, including model aliases like `opusplan` ## Available models For the `model` setting in Claude Code, you can configure either: * A **model alias** * A **model name** * Anthropic API: A full **[model name](https://docs.claude.com/en/docs/about-claude/models/overview#model-names)** * Bedrock: an inference profile ARN * Foundry: a deployment name * Vertex: a version name ### Model aliases Model aliases provide a convenient way to select model settings without remembering exact version numbers: | Model alias | Behavior | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **`default`** | Recommended model setting, depending on your account type | | **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.5) for daily coding tasks | | **`opus`** | Uses Opus model (currently Opus 4.5) for specialized complex reasoning tasks | | **`haiku`** | Uses the fast and efficient Haiku model for simple tasks | | **`sonnet[1m]`** | Uses Sonnet with a [1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window) window for long sessions | | **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution | ### Setting your model You can configure your model in several ways, listed in order of priority: 1. **During session** - Use `/model ` to switch models mid-session 2. **At startup** - Launch with `claude --model ` 3. **Environment variable** - Set `ANTHROPIC_MODEL=` 4. **Settings** - Configure permanently in your settings file using the `model` field. Example usage: ```bash theme={null} # Start with Opus claude --model opus # Switch to Sonnet during session /model sonnet ``` Example settings file: ``` { "permissions": { ... }, "model": "opus" } ``` ## Special model behavior ### `default` model setting The behavior of `default` depends on your account type. For certain Max users, Claude Code will automatically fall back to Sonnet if you hit a usage threshold with Opus. ### `opusplan` model setting The `opusplan` model alias provides an automated hybrid approach: * **In plan mode** - Uses `opus` for complex reasoning and architecture decisions * **In execution mode** - Automatically switches to `sonnet` for code generation and implementation This gives you the best of both worlds: Opus's superior reasoning for planning, and Sonnet's efficiency for execution. ### Extended context with \[1m] For Console/API users, the `[1m]` suffix can be added to full model names to enable a [1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window). ```bash theme={null} # Example of using a full model name with the [1m] suffix /model anthropic.claude-sonnet-4-5-20250929-v1:0[1m] ``` Note: Extended context models have [different pricing](https://docs.claude.com/en/docs/about-claude/pricing#long-context-pricing). ## Checking your current model You can see which model you're currently using in several ways: 1. In [status line](/en/statusline) (if configured) 2. In `/status`, which also displays your account information. ## Environment variables You can use the following environment variables, which must be full **model names** (or equivalent for your API provider), to control the model names that the aliases map to. | Environment variable | Description | | -------------------------------- | --------------------------------------------------------------------------------------------- | | `ANTHROPIC_DEFAULT_OPUS_MODEL` | The model to use for `opus`, or for `opusplan` when Plan Mode is active. | | `ANTHROPIC_DEFAULT_SONNET_MODEL` | The model to use for `sonnet`, or for `opusplan` when Plan Mode is not active. | | `ANTHROPIC_DEFAULT_HAIKU_MODEL` | The model to use for `haiku`, or [background functionality](/en/costs#background-token-usage) | | `CLAUDE_CODE_SUBAGENT_MODEL` | The model to use for [subagents](/en/sub-agents) | Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of `ANTHROPIC_DEFAULT_HAIKU_MODEL`. ### Prompt caching configuration Claude Code automatically uses [prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers: | Environment variable | Description | | ------------------------------- | ---------------------------------------------------------------------------------------------- | | `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) | | `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models only | | `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models only | | `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models only | These environment variables give you fine-grained control over prompt caching behavior. The global `DISABLE_PROMPT_CACHING` setting takes precedence over the model-specific settings, allowing you to quickly disable all caching when needed. The per-model settings are useful for selective control, such as when debugging specific models or working with cloud providers that may have different caching implementations. --- # Source: https://code.claude.com/docs/en/monitoring-usage.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Monitoring > Learn how to enable and configure OpenTelemetry for Claude Code. Claude Code supports OpenTelemetry (OTel) metrics and events for monitoring and observability. All metrics are time series data exported via OpenTelemetry's standard metrics protocol, and events are exported via OpenTelemetry's logs/events protocol. It is the user's responsibility to ensure their metrics and logs backends are properly configured and that the aggregation granularity meets their monitoring requirements. ## Quick start Configure OpenTelemetry using environment variables: ```bash theme={null} # 1. Enable telemetry export CLAUDE_CODE_ENABLE_TELEMETRY=1 # 2. Choose exporters (both are optional - configure only what you need) export OTEL_METRICS_EXPORTER=otlp # Options: otlp, prometheus, console export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console # 3. Configure OTLP endpoint (for OTLP exporter) export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 # 4. Set authentication (if required) export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token" # 5. For debugging: reduce export intervals export OTEL_METRIC_EXPORT_INTERVAL=10000 # 10 seconds (default: 60000ms) export OTEL_LOGS_EXPORT_INTERVAL=5000 # 5 seconds (default: 5000ms) # 6. Run Claude Code claude ``` The default export intervals are 60 seconds for metrics and 5 seconds for logs. During setup, you may want to use shorter intervals for debugging purposes. Remember to reset these for production use. For full configuration options, see the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options). ## Administrator configuration Administrators can configure OpenTelemetry settings for all users through the [managed settings file](/en/settings#settings-files). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](/en/settings#settings-precedence) for more information about how settings are applied. Example managed settings configuration: ```json theme={null} { "env": { "CLAUDE_CODE_ENABLE_TELEMETRY": "1", "OTEL_METRICS_EXPORTER": "otlp", "OTEL_LOGS_EXPORTER": "otlp", "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc", "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.company.com:4317", "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer company-token" } } ``` Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users. ## Configuration details ### Common configuration variables | Environment Variable | Description | Example Values | | ----------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------ | | `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` | | `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` | | `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` | | `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` | | `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` | | `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics (overrides general) | `grpc`, `http/json`, `http/protobuf` | | `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint (overrides general) | `http://localhost:4318/v1/metrics` | | `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs (overrides general) | `grpc`, `http/json`, `http/protobuf` | | `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint (overrides general) | `http://localhost:4318/v1/logs` | | `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` | | `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file | | `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file | | `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` | | `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` | | `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable | | `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` | ### Metrics cardinality control The following environment variables control which attributes are included in metrics to manage cardinality: | Environment Variable | Description | Default Value | Example to Disable | | ----------------------------------- | ----------------------------------------------- | ------------- | ------------------ | | `OTEL_METRICS_INCLUDE_SESSION_ID` | Include session.id attribute in metrics | `true` | `false` | | `OTEL_METRICS_INCLUDE_VERSION` | Include app.version attribute in metrics | `false` | `true` | | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Include user.account\_uuid attribute in metrics | `true` | `false` | These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. ### Dynamic headers For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically: #### Settings configuration Add to your `.claude/settings.json`: ```json theme={null} { "otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh" } ``` #### Script requirements The script must output valid JSON with string key-value pairs representing HTTP headers: ```bash theme={null} #!/bin/bash # Example: Multiple headers echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}" ``` #### Refresh behavior The headers helper script runs at startup and periodically thereafter to support token refresh. By default, the script runs every 29 minutes. Customize the interval with the `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` environment variable. ### Multi-team organization support Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable: ```bash theme={null} # Add custom attributes for team identification export OTEL_RESOURCE_ATTRIBUTES="department=engineering,team.id=platform,cost_center=eng-123" ``` These custom attributes will be included in all metrics and events, allowing you to: * Filter metrics by team or department * Track costs per cost center * Create team-specific dashboards * Set up alerts for specific teams **Important formatting requirements for OTEL\_RESOURCE\_ATTRIBUTES:** The `OTEL_RESOURCE_ATTRIBUTES` environment variable follows the [W3C Baggage specification](https://www.w3.org/TR/baggage/), which has strict formatting requirements: * **No spaces allowed**: Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid * **Format**: Must be comma-separated key=value pairs: `key1=value1,key2=value2` * **Allowed characters**: Only US-ASCII characters excluding control characters, whitespace, double quotes, commas, semicolons, and backslashes * **Special characters**: Characters outside the allowed range must be percent-encoded **Examples:** ```bash theme={null} # ❌ Invalid - contains spaces export OTEL_RESOURCE_ATTRIBUTES="org.name=John's Organization" # ✅ Valid - use underscores or camelCase instead export OTEL_RESOURCE_ATTRIBUTES="org.name=Johns_Organization" export OTEL_RESOURCE_ATTRIBUTES="org.name=JohnsOrganization" # ✅ Valid - percent-encode special characters if needed export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization" ``` Note: wrapping values in quotes doesn't escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` (with quotes included), not `My Company`. ### Example configurations ```bash theme={null} # Console debugging (1-second intervals) export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console export OTEL_METRIC_EXPORT_INTERVAL=1000 # OTLP/gRPC export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 # Prometheus export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=prometheus # Multiple exporters export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console,otlp export OTEL_EXPORTER_OTLP_PROTOCOL=http/json # Different endpoints/backends for metrics and logs export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=otlp export OTEL_LOGS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.company.com:4318 export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.company.com:4317 # Metrics only (no events/logs) export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 # Events/logs only (no metrics) export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_LOGS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 ``` ## Available metrics and events ### Standard attributes All metrics and events share these standard attributes: | Attribute | Description | Controlled By | | ------------------- | -------------------------------------------------------------------- | --------------------------------------------------- | | `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) | | `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) | | `organization.id` | Organization UUID (when authenticated) | Always included when available | | `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) | | `terminal.type` | Terminal type (for example, `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected | ### Metrics Claude Code exports the following metrics: | Metric Name | Description | Unit | | ------------------------------------- | ----------------------------------------------- | ------ | | `claude_code.session.count` | Count of CLI sessions started | count | | `claude_code.lines_of_code.count` | Count of lines of code modified | count | | `claude_code.pull_request.count` | Number of pull requests created | count | | `claude_code.commit.count` | Number of git commits created | count | | `claude_code.cost.usage` | Cost of the Claude Code session | USD | | `claude_code.token.usage` | Number of tokens used | tokens | | `claude_code.code_edit_tool.decision` | Count of code editing tool permission decisions | count | | `claude_code.active_time.total` | Total active time in seconds | s | ### Metric details #### Session counter Incremented at the start of each session. **Attributes**: * All [standard attributes](#standard-attributes) #### Lines of code counter Incremented when code is added or removed. **Attributes**: * All [standard attributes](#standard-attributes) * `type`: (`"added"`, `"removed"`) #### Pull request counter Incremented when creating pull requests via Claude Code. **Attributes**: * All [standard attributes](#standard-attributes) #### Commit counter Incremented when creating git commits via Claude Code. **Attributes**: * All [standard attributes](#standard-attributes) #### Cost counter Incremented after each API request. **Attributes**: * All [standard attributes](#standard-attributes) * `model`: Model identifier (for example, "claude-sonnet-4-5-20250929") #### Token counter Incremented after each API request. **Attributes**: * All [standard attributes](#standard-attributes) * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`) * `model`: Model identifier (for example, "claude-sonnet-4-5-20250929") #### Code edit tool decision counter Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage. **Attributes**: * All [standard attributes](#standard-attributes) * `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`) * `decision`: User decision (`"accept"`, `"reject"`) * `language`: Programming language of the edited file (for example, `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions. #### Active time counter Tracks actual time spent actively using Claude Code (not idle time). This metric is incremented during user interactions such as typing prompts or receiving responses. **Attributes**: * All [standard attributes](#standard-attributes) ### Events Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured): #### User prompt event Logged when a user submits a prompt. **Event Name**: `claude_code.user_prompt` **Attributes**: * All [standard attributes](#standard-attributes) * `event.name`: `"user_prompt"` * `event.timestamp`: ISO 8601 timestamp * `prompt_length`: Length of the prompt * `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`) #### Tool result event Logged when a tool completes execution. **Event Name**: `claude_code.tool_result` **Attributes**: * All [standard attributes](#standard-attributes) * `event.name`: `"tool_result"` * `event.timestamp`: ISO 8601 timestamp * `tool_name`: Name of the tool * `success`: `"true"` or `"false"` * `duration_ms`: Execution time in milliseconds * `error`: Error message (if failed) * `decision`: Either `"accept"` or `"reject"` * `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` * `tool_parameters`: JSON string containing tool-specific parameters (when available) * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox` #### API request event Logged for each API request to Claude. **Event Name**: `claude_code.api_request` **Attributes**: * All [standard attributes](#standard-attributes) * `event.name`: `"api_request"` * `event.timestamp`: ISO 8601 timestamp * `model`: Model used (for example, "claude-sonnet-4-5-20250929") * `cost_usd`: Estimated cost in USD * `duration_ms`: Request duration in milliseconds * `input_tokens`: Number of input tokens * `output_tokens`: Number of output tokens * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation #### API error event Logged when an API request to Claude fails. **Event Name**: `claude_code.api_error` **Attributes**: * All [standard attributes](#standard-attributes) * `event.name`: `"api_error"` * `event.timestamp`: ISO 8601 timestamp * `model`: Model used (for example, "claude-sonnet-4-5-20250929") * `error`: Error message * `status_code`: HTTP status code (if applicable) * `duration_ms`: Request duration in milliseconds * `attempt`: Attempt number (for retried requests) #### Tool decision event Logged when a tool permission decision is made (accept/reject). **Event Name**: `claude_code.tool_decision` **Attributes**: * All [standard attributes](#standard-attributes) * `event.name`: `"tool_decision"` * `event.timestamp`: ISO 8601 timestamp * `tool_name`: Name of the tool (for example, "Read", "Edit", "Write", "NotebookEdit") * `decision`: Either `"accept"` or `"reject"` * `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` ## Interpreting metrics and events data The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create: ### Usage monitoring | Metric | Analysis Opportunity | | ------------------------------------------------------------- | --------------------------------------------------------- | | `claude_code.token.usage` | Break down by `type` (input/output), user, team, or model | | `claude_code.session.count` | Track adoption and engagement over time | | `claude_code.lines_of_code.count` | Measure productivity by tracking code additions/removals | | `claude_code.commit.count` & `claude_code.pull_request.count` | Understand impact on development workflows | ### Cost monitoring The `claude_code.cost.usage` metric helps with: * Tracking usage trends across teams or individuals * Identifying high-usage sessions for optimization Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex). ### Alerting and segmentation Common alerts to consider: * Cost spikes * Unusual token consumption * High session volume from specific users All metrics can be segmented by `user.account_uuid`, `organization.id`, `session.id`, `model`, and `app.version`. ### Event analysis The event data provides detailed insights into Claude Code interactions: **Tool Usage Patterns**: analyze tool result events to identify: * Most frequently used tools * Tool success rates * Average tool execution times * Error patterns by tool type **Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks. ## Backend considerations Your choice of metrics and logs backends determines the types of analyses you can perform: ### For metrics * **Time series databases (for example, Prometheus)**: Rate calculations, aggregated metrics * **Columnar stores (for example, ClickHouse)**: Complex queries, unique user analysis * **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Advanced querying, visualization, alerting ### For events/logs * **Log aggregation systems (for example, Elasticsearch, Loki)**: Full-text search, log analysis * **Columnar stores (for example, ClickHouse)**: Structured event analysis * **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Correlation between metrics and events For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries. ## Service information All metrics and events are exported with the following resource attributes: * `service.name`: `claude-code` * `service.version`: Current Claude Code version * `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`) * `os.version`: Operating system version string * `host.arch`: Host architecture (for example, `amd64`, `arm64`) * `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux) * Meter Name: `com.anthropic.claude_code` ## ROI measurement resources For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](https://github.com/anthropics/claude-code-monitoring-guide). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear. ## Security/privacy considerations * Telemetry is opt-in and requires explicit configuration * Sensitive information like API keys or file contents are never included in metrics or events * User prompt content is redacted by default - only prompt length is recorded. To enable user prompt logging, set `OTEL_LOG_USER_PROMPTS=1` ## Monitoring Claude Code on Amazon Bedrock For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md). --- # Source: https://code.claude.com/docs/en/network-config.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Enterprise network configuration > Configure Claude Code for enterprise environments with proxy servers, custom Certificate Authorities (CA), and mutual Transport Layer Security (mTLS) authentication. Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security. All environment variables shown on this page can also be configured in [`settings.json`](/en/settings). ## Proxy configuration ### Environment variables Claude Code respects standard proxy environment variables: ```bash theme={null} # HTTPS proxy (recommended) export HTTPS_PROXY=https://proxy.example.com:8080 # HTTP proxy (if HTTPS not available) export HTTP_PROXY=http://proxy.example.com:8080 # Bypass proxy for specific requests - space-separated format export NO_PROXY="localhost 192.168.1.1 example.com .example.com" # Bypass proxy for specific requests - comma-separated format export NO_PROXY="localhost,192.168.1.1,example.com,.example.com" # Bypass proxy for all requests export NO_PROXY="*" ``` Claude Code does not support SOCKS proxies. ### Basic authentication If your proxy requires basic authentication, include credentials in the proxy URL: ```bash theme={null} export HTTPS_PROXY=http://username:password@proxy.example.com:8080 ``` Avoid hardcoding passwords in scripts. Use environment variables or secure credential storage instead. For proxies requiring advanced authentication (NTLM, Kerberos, etc.), consider using an LLM Gateway service that supports your authentication method. ## Custom CA certificates If your enterprise environment uses custom CAs for HTTPS connections (whether through a proxy or direct API access), configure Claude Code to trust them: ```bash theme={null} export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem ``` ## mTLS authentication For enterprise environments requiring client certificate authentication: ```bash theme={null} # Client certificate for authentication export CLAUDE_CODE_CLIENT_CERT=/path/to/client-cert.pem # Client private key export CLAUDE_CODE_CLIENT_KEY=/path/to/client-key.pem # Optional: Passphrase for encrypted private key export CLAUDE_CODE_CLIENT_KEY_PASSPHRASE="your-passphrase" ``` ## Network access requirements Claude Code requires access to the following URLs: * `api.anthropic.com` - Claude API endpoints * `claude.ai` - WebFetch safeguards * `statsig.anthropic.com` - Telemetry and metrics * `sentry.io` - Error reporting Ensure these URLs are allowlisted in your proxy configuration and firewall rules. This is especially important when using Claude Code in containerized or restricted network environments. ## Additional resources * [Claude Code settings](/en/settings) * [Environment variables reference](/en/settings#environment-variables) * [Troubleshooting guide](/en/troubleshooting) --- # Source: https://code.claude.com/docs/en/output-styles.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Output styles > Adapt Claude Code for uses beyond software engineering Output styles allow you to use Claude Code as any type of agent while keeping its core capabilities, such as running local scripts, reading/writing files, and tracking TODOs. ## Built-in output styles Claude Code's **Default** output style is the existing system prompt, designed to help you complete software engineering tasks efficiently. There are two additional built-in output styles focused on teaching you the codebase and how Claude operates: * **Explanatory**: Provides educational "Insights" in between helping you complete software engineering tasks. Helps you understand implementation choices and codebase patterns. * **Learning**: Collaborative, learn-by-doing mode where Claude will not only share "Insights" while coding, but also ask you to contribute small, strategic pieces of code yourself. Claude Code will add `TODO(human)` markers in your code for you to implement. ## How output styles work Output styles directly modify Claude Code's system prompt. * All output styles exclude instructions for efficient output (such as responding concisely). * Custom output styles exclude instructions for coding (such as verifying code with tests), unless `keep-coding-instructions` is true. * All output styles have their own custom instructions added to the end of the system prompt. * All output styles trigger reminders for Claude to adhere to the output style instructions during the conversation. ## Change your output style You can either: * Run `/output-style` to access a menu and select your output style (this can also be accessed from the `/config` menu) * Run `/output-style [style]`, such as `/output-style explanatory`, to directly switch to a style These changes apply to the [local project level](/en/settings) and are saved in `.claude/settings.local.json`. You can also directly edit the `outputStyle` field in a settings file at a different level. ## Create a custom output style Custom output styles are Markdown files with frontmatter and the text that will be added to the system prompt: ```markdown theme={null} --- name: My Custom Style description: A brief description of what this style does, to be displayed to the user --- # Custom Style Instructions You are an interactive CLI tool that helps users with software engineering tasks. [Your custom instructions here...] ## Specific Behaviors [Define how the assistant should behave in this style...] ``` You can save these files at the user level (`~/.claude/output-styles`) or project level (`.claude/output-styles`). ### Frontmatter Output style files support frontmatter, useful for specifying metadata about the command: | Frontmatter | Purpose | Default | | :------------------------- | :-------------------------------------------------------------------------- | :---------------------- | | `name` | Name of the output style, if not the file name | Inherits from file name | | `description` | Description of the output style. Used only in the UI of `/output-style` | None | | `keep-coding-instructions` | Whether to keep the parts of Claude Code's system prompt related to coding. | false | ## Comparisons to related features ### Output Styles vs. CLAUDE.md vs. --append-system-prompt Output styles completely "turn off" the parts of Claude Code's default system prompt specific to software engineering. Neither CLAUDE.md nor `--append-system-prompt` edit Claude Code's default system prompt. CLAUDE.md adds the contents as a user message *following* Claude Code's default system prompt. `--append-system-prompt` appends the content to the system prompt. ### Output Styles vs. [Agents](/en/sub-agents) Output styles directly affect the main agent loop and only affect the system prompt. Agents are invoked to handle specific tasks and can include additional settings like the model to use, the tools they have available, and some context about when to use the agent. ### Output Styles vs. [Skills](/en/skills) Output styles modify how Claude responds (formatting, tone, structure) and are always active once selected. Skills are task-specific prompts that you invoke with `/skill-name` or that Claude loads automatically when relevant. Use output styles for consistent formatting preferences; use skills for reusable workflows and tasks. --- # Source: https://code.claude.com/docs/en/overview.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code overview > Learn about Claude Code, Anthropic's agentic coding tool that lives in your terminal and helps you turn ideas into code faster than ever before. ## Get started in 30 seconds Prerequisites: * A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise) or [Claude Console](https://console.anthropic.com/) account **Install Claude Code:** To install Claude Code, use one of the following methods: **macOS, Linux, WSL:** ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash ``` **Windows PowerShell:** ```powershell theme={null} irm https://claude.ai/install.ps1 | iex ``` **Windows CMD:** ```batch theme={null} curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd ``` Native installations automatically update in the background to keep you on the latest version. ```sh theme={null} brew install --cask claude-code ``` Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes. ```powershell theme={null} winget install Anthropic.ClaudeCode ``` WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes. **Start using Claude Code:** ```bash theme={null} cd your-project claude ``` You'll be prompted to log in on first use. That's it! [Continue with Quickstart (5 minutes) →](/en/quickstart) See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues. ## What Claude Code does for you * **Build features from descriptions**: Tell Claude what you want to build in plain English. It will make a plan, write the code, and ensure it works. * **Debug and fix issues**: Describe a bug or paste an error message. Claude Code will analyze your codebase, identify the problem, and implement a fix. * **Navigate any codebase**: Ask anything about your team's codebase, and get a thoughtful answer back. Claude Code maintains awareness of your entire project structure, can find up-to-date information from the web, and with [MCP](/en/mcp) can pull from external data sources like Google Drive, Figma, and Slack. * **Automate tedious tasks**: Fix fiddly lint issues, resolve merge conflicts, and write release notes. Do all this in a single command from your developer machines, or automatically in CI. ## Why developers love Claude Code * **Works in your terminal**: Not another chat window. Not another IDE. Claude Code meets you where you already work, with the tools you already love. * **Takes action**: Claude Code can directly edit files, run commands, and create commits. Need more? [MCP](/en/mcp) lets Claude read your design docs in Google Drive, update your tickets in Jira, or use *your* custom developer tooling. * **Unix philosophy**: Claude Code is composable and scriptable. `tail -f app.log | claude -p "Slack me if you see any anomalies appear in this log stream"` *works*. Your CI can run `claude -p "If there are new text strings, translate them into French and raise a PR for @lang-fr-team to review"`. * **Enterprise-ready**: Use the Claude API, or host on AWS or GCP. Enterprise-grade [security](/en/security), [privacy](/en/data-usage), and [compliance](https://trust.anthropic.com/) is built-in. ## Use Claude Code everywhere Claude Code works across your development environment: in your terminal, in your IDE, in the cloud, and in Slack. * **[Terminal (CLI)](/en/quickstart)**: the core Claude Code experience. Run `claude` in any terminal to start coding. * **[Claude Code on the web](/en/claude-code-on-the-web)**: use Claude Code from your browser at [claude.ai/code](https://claude.ai/code) or the Claude iOS app, with no local setup required. Run tasks in parallel, work on repos you don't have locally, and review changes in a built-in diff view. * **[Desktop app](/en/desktop)**: a standalone application with diff review, parallel sessions via git worktrees, and the ability to launch cloud sessions. * **[VS Code](/en/vs-code)**: a native extension with inline diffs, @-mentions, and plan review. * **[JetBrains IDEs](/en/jetbrains)**: a plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with IDE diff viewing and context sharing. * **[GitHub Actions](/en/github-actions)**: automate code review, issue triage, and other workflows in CI/CD with `@claude` mentions. * **[GitLab CI/CD](/en/gitlab-ci-cd)**: event-driven automation for GitLab merge requests and issues. * **[Slack](/en/slack)**: mention Claude in Slack to route coding tasks to Claude Code on the web and get PRs back. * **[Chrome](/en/chrome)**: connect Claude Code to your browser for live debugging, design verification, and web app testing. ## Next steps See Claude Code in action with practical examples Step-by-step guides for common workflows Solutions for common issues with Claude Code Run Claude Code as a standalone application ## Additional resources Learn more about Claude Code on claude.com Create custom AI agents with the Claude Agent SDK Configure Claude Code with Amazon Bedrock or Google Vertex AI Customize Claude Code for your workflow Learn about CLI commands and controls Clone our development container reference implementation Discover Claude Code's safeguards and best practices for safe usage Understand how Claude Code handles your data --- # Source: https://code.claude.com/docs/en/permissions.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Configure permissions > Control what Claude Code can access and do with fine-grained permission rules, modes, and managed policies. Claude Code supports fine-grained permissions so that you can specify exactly what the agent is allowed to do and what it cannot. Permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers. ## Permission system Claude Code uses a tiered permission system to balance power and safety: | Tool type | Example | Approval required | "Yes, don't ask again" behavior | | :---------------- | :--------------- | :---------------- | :-------------------------------------------- | | Read-only | File reads, Grep | No | N/A | | Bash commands | Shell execution | Yes | Permanently per project directory and command | | File modification | Edit/write files | Yes | Until session end | ## Manage permissions You can view and manage Claude Code's tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from. * **Allow** rules let Claude Code use the specified tool without manual approval. * **Ask** rules prompt for confirmation whenever Claude Code tries to use the specified tool. * **Deny** rules prevent Claude Code from using the specified tool. Rules are evaluated in order: **deny -> ask -> allow**. The first matching rule wins, so deny rules always take precedence. ## Permission modes Claude Code supports several permission modes that control how tools are approved. Set the `defaultMode` in your [settings files](/en/settings#settings-files): | Mode | Description | | :------------------ | :------------------------------------------------------------------------------------ | | `default` | Standard behavior: prompts for permission on first use of each tool | | `acceptEdits` | Automatically accepts file edit permissions for the session | | `plan` | Plan Mode: Claude can analyze but not modify files or execute commands | | `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules | | `bypassPermissions` | Skips all permission prompts (requires safe environment, see warning below) | `bypassPermissions` mode disables all permission checks. Only use this in isolated environments like containers or VMs where Claude Code cannot cause damage. Administrators can prevent this mode by setting `disableBypassPermissionsMode` to `"disable"` in [managed settings](#managed-settings). ## Permission rule syntax Permission rules follow the format `Tool` or `Tool(specifier)`. ### Match all uses of a tool To match all uses of a tool, use just the tool name without parentheses: | Rule | Effect | | :--------- | :----------------------------- | | `Bash` | Matches all Bash commands | | `WebFetch` | Matches all web fetch requests | | `Read` | Matches all file reads | `Bash(*)` is equivalent to `Bash` and matches all Bash commands. ### Use specifiers for fine-grained control Add a specifier in parentheses to match specific tool uses: | Rule | Effect | | :----------------------------- | :------------------------------------------------------- | | `Bash(npm run build)` | Matches the exact command `npm run build` | | `Read(./.env)` | Matches reading the `.env` file in the current directory | | `WebFetch(domain:example.com)` | Matches fetch requests to example.com | ### Wildcard patterns Bash rules support glob patterns with `*`. Wildcards can appear at any position in the command. This configuration allows npm and git commit commands while blocking git push: ```json theme={null} { "permissions": { "allow": [ "Bash(npm run *)", "Bash(git commit *)", "Bash(git * main)", "Bash(* --version)", "Bash(* --help *)" ], "deny": [ "Bash(git push *)" ] } } ``` The space before `*` matters: `Bash(ls *)` matches `ls -la` but not `lsof`, while `Bash(ls*)` matches both. The legacy `:*` suffix syntax is equivalent to ` *` but is deprecated. ## Tool-specific permission rules ### Bash Bash permission rules support wildcard matching with `*`. Wildcards can appear at any position in the command, including at the beginning, middle, or end: * `Bash(npm run build)` matches the exact Bash command `npm run build` * `Bash(npm run test *)` matches Bash commands starting with `npm run test` * `Bash(npm *)` matches any command starting with `npm ` * `Bash(* install)` matches any command ending with ` install` * `Bash(git * main)` matches commands like `git checkout main`, `git merge main` When `*` appears at the end with a space before it (like `Bash(ls *)`), it enforces a word boundary, requiring the prefix to be followed by a space or end-of-string. For example, `Bash(ls *)` matches `ls -la` but not `lsof`. In contrast, `Bash(ls*)` without a space matches both `ls -la` and `lsof` because there's no word boundary constraint. Claude Code is aware of shell operators (like `&&`) so a prefix match rule like `Bash(safe-cmd *)` won't give it permission to run the command `safe-cmd && other-cmd`. Bash permission patterns that try to constrain command arguments are fragile. For example, `Bash(curl http://github.com/ *)` intends to restrict curl to GitHub URLs, but won't match variations like: * Options before URL: `curl -X GET http://github.com/...` * Different protocol: `curl https://github.com/...` * Redirects: `curl -L http://bit.ly/xyz` (redirects to github) * Variables: `URL=http://github.com && curl $URL` * Extra spaces: `curl http://github.com` For more reliable URL filtering, consider: * **Restrict Bash network tools**: use deny rules to block `curl`, `wget`, and similar commands, then use the WebFetch tool with `WebFetch(domain:github.com)` permission for allowed domains * **Use PreToolUse hooks**: implement a hook that validates URLs in Bash commands and blocks disallowed domains * Instructing Claude Code about your allowed curl patterns via CLAUDE.md Note that using WebFetch alone does not prevent network access. If Bash is allowed, Claude can still use `curl`, `wget`, or other tools to reach any URL. ### Read and Edit `Edit` rules apply to all built-in tools that edit files. Claude makes a best-effort attempt to apply `Read` rules to all built-in tools that read files like Grep and Glob. Read and Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types: | Pattern | Meaning | Example | Matches | | ------------------ | -------------------------------------- | -------------------------------- | ---------------------------------- | | `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` | | `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` | | `/path` | Path **relative to settings file** | `Edit(/src/**/*.ts)` | `/src/**/*.ts` | | `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `/*.env` | A pattern like `/Users/alice/file` is NOT an absolute path. It's relative to your settings file. Use `//Users/alice/file` for absolute paths. Examples: * `Edit(/docs/**)`: edits in `/docs/` (NOT `/docs/`) * `Read(~/.zshrc)`: reads your home directory's `.zshrc` * `Edit(//tmp/scratch.txt)`: edits the absolute path `/tmp/scratch.txt` * `Read(src/**)`: reads from `/src/` In gitignore patterns, `*` matches files in a single directory while `**` matches recursively across directories. To allow all file access, use just the tool name without parentheses: `Read`, `Edit`, or `Write`. ### WebFetch * `WebFetch(domain:example.com)` matches fetch requests to example.com ### MCP * `mcp__puppeteer` matches any tool provided by the `puppeteer` server (name configured in Claude Code) * `mcp__puppeteer__*` wildcard syntax that also matches all tools from the `puppeteer` server * `mcp__puppeteer__puppeteer_navigate` matches the `puppeteer_navigate` tool provided by the `puppeteer` server ### Task (subagents) Use `Task(AgentName)` rules to control which [subagents](/en/sub-agents) Claude can use: * `Task(Explore)` matches the Explore subagent * `Task(Plan)` matches the Plan subagent * `Task(Verify)` matches the Verify subagent Add these rules to the `deny` array in your settings or use the `--disallowedTools` CLI flag to disable specific agents. To disable the Explore agent: ```json theme={null} { "permissions": { "deny": ["Task(Explore)"] } } ``` ## Extend permissions with hooks [Claude Code hooks](/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission system, and the hook output can determine whether to approve or deny the tool call in place of the permission system. ## Working directories By default, Claude has access to files in the directory where it was launched. You can extend this access: * **During startup**: use `--add-dir ` CLI argument * **During session**: use `/add-dir` command * **Persistent configuration**: add to `additionalDirectories` in [settings files](/en/settings#settings-files) Files in additional directories follow the same permission rules as the original working directory: they become readable without prompts, and file editing permissions follow the current permission mode. ## How permissions interact with sandboxing Permissions and [sandboxing](/en/sandboxing) are complementary security layers: * **Permissions** control which tools Claude Code can use and which files or domains it can access. They apply to all tools (Bash, Read, Edit, WebFetch, MCP, and others). * **Sandboxing** provides OS-level enforcement that restricts the Bash tool's filesystem and network access. It applies only to Bash commands and their child processes. Use both for defense-in-depth: * Permission deny rules block Claude from even attempting to access restricted resources * Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude's decision-making * Filesystem restrictions in the sandbox use Read and Edit deny rules, not separate sandbox configuration * Network restrictions combine WebFetch permission rules with the sandbox's `allowedDomains` list ## Managed settings For organizations that need centralized control over Claude Code configuration, administrators can deploy `managed-settings.json` files to system directories. These policy files follow the same format as regular settings files and cannot be overridden by user or project settings. **Managed settings file locations**: * **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json` * **Linux and WSL**: `/etc/claude-code/managed-settings.json` * **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json` These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators. ### Managed-only settings Some settings are only effective in managed settings: | Setting | Description | | :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- | | `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode and the `--dangerously-skip-permissions` flag | | `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply | | `allowManagedHooksOnly` | When `true`, prevents loading of user, project, and plugin hooks. Only managed hooks and SDK hooks are allowed | | `strictKnownMarketplaces` | Controls which plugin marketplaces users can add. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | ## Settings precedence Permission rules follow the same [settings precedence](/en/settings#settings-precedence) as all other Claude Code settings: managed settings have the highest precedence, followed by command line arguments, local project, shared project, and user settings. If a permission is allowed in user settings but denied in project settings, the project setting takes precedence and the permission is blocked. ## Example configurations This [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) includes starter settings configurations for common deployment scenarios. Use these as starting points and adjust them to fit your needs. ## See also * [Settings](/en/settings): complete configuration reference including the permission settings table * [Sandboxing](/en/sandboxing): OS-level filesystem and network isolation for Bash commands * [Authentication](/en/authentication): set up user access to Claude Code * [Security](/en/security): security safeguards and best practices * [Hooks](/en/hooks-guide): automate workflows and extend permission evaluation --- # Source: https://code.claude.com/docs/en/plugin-marketplaces.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Create and distribute a plugin marketplace > Build and host plugin marketplaces to distribute Claude Code extensions across teams and communities. A plugin marketplace is a catalog that lets you distribute plugins to others. Marketplaces provide centralized discovery, version tracking, automatic updates, and support for multiple source types (git repositories, local paths, and more). This guide shows you how to create your own marketplace to share plugins with your team or community. Looking to install plugins from an existing marketplace? See [Discover and install prebuilt plugins](/en/discover-plugins). ## Overview Creating and distributing a marketplace involves: 1. **Creating plugins**: build one or more plugins with commands, agents, hooks, MCP servers, or LSP servers. This guide assumes you already have plugins to distribute; see [Create plugins](/en/plugins) for details on how to create them. 2. **Creating a marketplace file**: define a `marketplace.json` that lists your plugins and where to find them (see [Create the marketplace file](#create-the-marketplace-file)). 3. **Host the marketplace**: push to GitHub, GitLab, or another git host (see [Host and distribute marketplaces](#host-and-distribute-marketplaces)). 4. **Share with users**: users add your marketplace with `/plugin marketplace add` and install individual plugins (see [Discover and install plugins](/en/discover-plugins)). Once your marketplace is live, you can update it by pushing changes to your repository. Users refresh their local copy with `/plugin marketplace update`. ## Walkthrough: create a local marketplace This example creates a marketplace with one plugin: a `/review` skill for code reviews. You'll create the directory structure, add a skill, create the plugin manifest and marketplace catalog, then install and test it. ```bash theme={null} mkdir -p my-marketplace/.claude-plugin mkdir -p my-marketplace/plugins/review-plugin/.claude-plugin mkdir -p my-marketplace/plugins/review-plugin/skills/review ``` Create a `SKILL.md` file that defines what the `/review` skill does. ```markdown my-marketplace/plugins/review-plugin/skills/review/SKILL.md theme={null} --- description: Review code for bugs, security, and performance disable-model-invocation: true --- Review the code I've selected or the recent changes for: - Potential bugs or edge cases - Security concerns - Performance issues - Readability improvements Be concise and actionable. ``` Create a `plugin.json` file that describes the plugin. The manifest goes in the `.claude-plugin/` directory. ```json my-marketplace/plugins/review-plugin/.claude-plugin/plugin.json theme={null} { "name": "review-plugin", "description": "Adds a /review skill for quick code reviews", "version": "1.0.0" } ``` Create the marketplace catalog that lists your plugin. ```json my-marketplace/.claude-plugin/marketplace.json theme={null} { "name": "my-plugins", "owner": { "name": "Your Name" }, "plugins": [ { "name": "review-plugin", "source": "./plugins/review-plugin", "description": "Adds a /review skill for quick code reviews" } ] } ``` Add the marketplace and install the plugin. ```shell theme={null} /plugin marketplace add ./my-marketplace /plugin install review-plugin@my-plugins ``` Select some code in your editor and run your new command. ```shell theme={null} /review ``` To learn more about what plugins can do, including hooks, agents, MCP servers, and LSP servers, see [Plugins](/en/plugins). **How plugins are installed**: When users install a plugin, Claude Code copies the plugin directory to a cache location. This means plugins can't reference files outside their directory using paths like `../shared-utils`, because those files won't be copied. If you need to share files across plugins, use symlinks (which are followed during copying) or restructure your marketplace so the shared directory is inside the plugin source path. See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for details. ## Create the marketplace file Create `.claude-plugin/marketplace.json` in your repository root. This file defines your marketplace's name, owner information, and a list of plugins with their sources. Each plugin entry needs at minimum a `name` and `source` (where to fetch it from). See the [full schema](#marketplace-schema) below for all available fields. ```json theme={null} { "name": "company-tools", "owner": { "name": "DevTools Team", "email": "devtools@example.com" }, "plugins": [ { "name": "code-formatter", "source": "./plugins/formatter", "description": "Automatic code formatting on save", "version": "2.1.0", "author": { "name": "DevTools Team" } }, { "name": "deployment-tools", "source": { "source": "github", "repo": "company/deploy-plugin" }, "description": "Deployment automation tools" } ] } ``` ## Marketplace schema ### Required fields | Field | Type | Description | Example | | :-------- | :----- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------- | | `name` | string | Marketplace identifier (kebab-case, no spaces). This is public-facing: users see it when installing plugins (for example, `/plugin install my-tool@your-marketplace`). | `"acme-tools"` | | `owner` | object | Marketplace maintainer information ([see fields below](#owner-fields)) | | | `plugins` | array | List of available plugins | See below | **Reserved names**: The following marketplace names are reserved for official Anthropic use and cannot be used by third-party marketplaces: `claude-code-marketplace`, `claude-code-plugins`, `claude-plugins-official`, `anthropic-marketplace`, `anthropic-plugins`, `agent-skills`, `life-sciences`. Names that impersonate official marketplaces (like `official-claude-plugins` or `anthropic-tools-v2`) are also blocked. ### Owner fields | Field | Type | Required | Description | | :------ | :----- | :------- | :------------------------------- | | `name` | string | Yes | Name of the maintainer or team | | `email` | string | No | Contact email for the maintainer | ### Optional metadata | Field | Type | Description | | :--------------------- | :----- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `metadata.description` | string | Brief marketplace description | | `metadata.version` | string | Marketplace version | | `metadata.pluginRoot` | string | Base directory prepended to relative plugin source paths (for example, `"./plugins"` lets you write `"source": "formatter"` instead of `"source": "./plugins/formatter"`) | ## Plugin entries Each plugin entry in the `plugins` array describes a plugin and where to find it. You can include any field from the [plugin manifest schema](/en/plugins-reference#plugin-manifest-schema) (like `description`, `version`, `author`, `commands`, `hooks`, etc.), plus these marketplace-specific fields: `source`, `category`, `tags`, and `strict`. ### Required fields | Field | Type | Description | | :------- | :------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | string | Plugin identifier (kebab-case, no spaces). This is public-facing: users see it when installing (for example, `/plugin install my-plugin@marketplace`). | | `source` | string\|object | Where to fetch the plugin from (see [Plugin sources](#plugin-sources) below) | ### Optional plugin fields **Standard metadata fields:** | Field | Type | Description | | :------------ | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `description` | string | Brief plugin description | | `version` | string | Plugin version | | `author` | object | Plugin author information (`name` required, `email` optional) | | `homepage` | string | Plugin homepage or documentation URL | | `repository` | string | Source code repository URL | | `license` | string | SPDX license identifier (for example, MIT, Apache-2.0) | | `keywords` | array | Tags for plugin discovery and categorization | | `category` | string | Plugin category for organization | | `tags` | array | Tags for searchability | | `strict` | boolean | Controls whether plugins need their own `plugin.json` file. When `true` (default), the plugin source must contain a `plugin.json`, and any fields you add here in the marketplace entry get merged with it. When `false`, the plugin doesn't need its own `plugin.json`; the marketplace entry itself defines everything about the plugin. Use `false` when you want to define simple plugins entirely in your marketplace file. | **Component configuration fields:** | Field | Type | Description | | :----------- | :------------- | :----------------------------------------------- | | `commands` | string\|array | Custom paths to command files or directories | | `agents` | string\|array | Custom paths to agent files | | `hooks` | string\|object | Custom hooks configuration or path to hooks file | | `mcpServers` | string\|object | MCP server configurations or path to MCP config | | `lspServers` | string\|object | LSP server configurations or path to LSP config | ## Plugin sources ### Relative paths For plugins in the same repository: ```json theme={null} { "name": "my-plugin", "source": "./plugins/my-plugin" } ``` Relative paths only work when users add your marketplace via Git (GitHub, GitLab, or git URL). If users add your marketplace via a direct URL to the `marketplace.json` file, relative paths will not resolve correctly. For URL-based distribution, use GitHub, npm, or git URL sources instead. See [Troubleshooting](#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details. ### GitHub repositories ```json theme={null} { "name": "github-plugin", "source": { "source": "github", "repo": "owner/plugin-repo" } } ``` You can pin to a specific branch, tag, or commit: ```json theme={null} { "name": "github-plugin", "source": { "source": "github", "repo": "owner/plugin-repo", "ref": "v2.0.0", "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0" } } ``` | Field | Type | Description | | :----- | :----- | :-------------------------------------------------------------------- | | `repo` | string | Required. GitHub repository in `owner/repo` format | | `ref` | string | Optional. Git branch or tag (defaults to repository default branch) | | `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version | ### Git repositories ```json theme={null} { "name": "git-plugin", "source": { "source": "url", "url": "https://gitlab.com/team/plugin.git" } } ``` You can pin to a specific branch, tag, or commit: ```json theme={null} { "name": "git-plugin", "source": { "source": "url", "url": "https://gitlab.com/team/plugin.git", "ref": "main", "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0" } } ``` | Field | Type | Description | | :---- | :----- | :-------------------------------------------------------------------- | | `url` | string | Required. Full git repository URL (must end with `.git`) | | `ref` | string | Optional. Git branch or tag (defaults to repository default branch) | | `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version | ### Advanced plugin entries This example shows a plugin entry using many of the optional fields, including custom paths for commands, agents, hooks, and MCP servers: ```json theme={null} { "name": "enterprise-tools", "source": { "source": "github", "repo": "company/enterprise-plugin" }, "description": "Enterprise workflow automation tools", "version": "2.1.0", "author": { "name": "Enterprise Team", "email": "enterprise@example.com" }, "homepage": "https://docs.example.com/plugins/enterprise-tools", "repository": "https://github.com/company/enterprise-plugin", "license": "MIT", "keywords": ["enterprise", "workflow", "automation"], "category": "productivity", "commands": [ "./commands/core/", "./commands/enterprise/", "./commands/experimental/preview.md" ], "agents": ["./agents/security-reviewer.md", "./agents/compliance-checker.md"], "hooks": { "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh" } ] } ] }, "mcpServers": { "enterprise-db": { "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server", "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"] } }, "strict": false } ``` Key things to notice: * **`commands` and `agents`**: You can specify multiple directories or individual files. Paths are relative to the plugin root. * **`${CLAUDE_PLUGIN_ROOT}`**: Use this variable in hooks and MCP server configs to reference files within the plugin's installation directory. This is necessary because plugins are copied to a cache location when installed. * **`strict: false`**: Since this is set to false, the plugin doesn't need its own `plugin.json`. The marketplace entry defines everything. ## Host and distribute marketplaces ### Host on GitHub (recommended) GitHub provides the easiest distribution method: 1. **Create a repository**: Set up a new repository for your marketplace 2. **Add marketplace file**: Create `.claude-plugin/marketplace.json` with your plugin definitions 3. **Share with teams**: Users add your marketplace with `/plugin marketplace add owner/repo` **Benefits**: Built-in version control, issue tracking, and team collaboration features. ### Host on other git services Any git hosting service works, such as GitLab, Bitbucket, and self-hosted servers. Users add with the full repository URL: ```shell theme={null} /plugin marketplace add https://gitlab.com/company/plugins.git ``` ### Private repositories Claude Code supports installing plugins from private repositories. For manual installation and updates, Claude Code uses your existing git credential helpers. If `git clone` works for a private repository in your terminal, it works in Claude Code too. Common credential helpers include `gh auth login` for GitHub, macOS Keychain, and `git-credential-store`. Background auto-updates run at startup without credential helpers, since interactive prompts would block Claude Code from starting. To enable auto-updates for private marketplaces, set the appropriate authentication token in your environment: | Provider | Environment variables | Notes | | :-------- | :--------------------------- | :---------------------------------------- | | GitHub | `GITHUB_TOKEN` or `GH_TOKEN` | Personal access token or GitHub App token | | GitLab | `GITLAB_TOKEN` or `GL_TOKEN` | Personal access token or project token | | Bitbucket | `BITBUCKET_TOKEN` | App password or repository access token | Set the token in your shell configuration (for example, `.bashrc`, `.zshrc`) or pass it when running Claude Code: ```bash theme={null} export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx ``` For CI/CD environments, configure the token as a secret environment variable. GitHub Actions automatically provides `GITHUB_TOKEN` for repositories in the same organization. ### Test locally before distribution Test your marketplace locally before sharing: ```shell theme={null} /plugin marketplace add ./my-local-marketplace /plugin install test-plugin@my-local-marketplace ``` For the full range of add commands (GitHub, Git URLs, local paths, remote URLs), see [Add marketplaces](/en/discover-plugins#add-marketplaces). ### Require marketplaces for your team You can configure your repository so team members are automatically prompted to install your marketplace when they trust the project folder. Add your marketplace to `.claude/settings.json`: ```json theme={null} { "extraKnownMarketplaces": { "company-tools": { "source": { "source": "github", "repo": "your-org/claude-plugins" } } } } ``` You can also specify which plugins should be enabled by default: ```json theme={null} { "enabledPlugins": { "code-formatter@company-tools": true, "deployment-tools@company-tools": true } } ``` For full configuration options, see [Plugin settings](/en/settings#plugin-settings). ### Managed marketplace restrictions For organizations requiring strict control over plugin sources, administrators can restrict which plugin marketplaces users are allowed to add using the [`strictKnownMarketplaces`](/en/settings#strictknownmarketplaces) setting in managed settings. When `strictKnownMarketplaces` is configured in managed settings, the restriction behavior depends on the value: | Value | Behavior | | ------------------- | ---------------------------------------------------------------- | | Undefined (default) | No restrictions. Users can add any marketplace | | Empty array `[]` | Complete lockdown. Users cannot add any new marketplaces | | List of sources | Users can only add marketplaces that match the allowlist exactly | #### Common configurations Disable all marketplace additions: ```json theme={null} { "strictKnownMarketplaces": [] } ``` Allow specific marketplaces only: ```json theme={null} { "strictKnownMarketplaces": [ { "source": "github", "repo": "acme-corp/approved-plugins" }, { "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" }, { "source": "url", "url": "https://plugins.example.com/marketplace.json" } ] } ``` Allow all marketplaces from an internal git server using regex pattern matching: ```json theme={null} { "strictKnownMarketplaces": [ { "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" } ] } ``` #### How restrictions work Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts. The allowlist uses exact matching for most source types. For a marketplace to be allowed, all specified fields must match exactly: * For GitHub sources: `repo` is required, and `ref` or `path` must also match if specified in the allowlist * For URL sources: the full URL must match exactly * For `hostPattern` sources: the marketplace host is matched against the regex pattern Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions. For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces). ## Validation and testing Test your marketplace before sharing. Validate your marketplace JSON syntax: ```bash theme={null} claude plugin validate . ``` Or from within Claude Code: ```shell theme={null} /plugin validate . ``` Add the marketplace for testing: ```shell theme={null} /plugin marketplace add ./path/to/marketplace ``` Install a test plugin to verify everything works: ```shell theme={null} /plugin install test-plugin@marketplace-name ``` For complete plugin testing workflows, see [Test your plugins locally](/en/plugins#test-your-plugins-locally). For technical troubleshooting, see [Plugins reference](/en/plugins-reference). ## Troubleshooting ### Marketplace not loading **Symptoms**: Can't add marketplace or see plugins from it **Solutions**: * Verify the marketplace URL is accessible * Check that `.claude-plugin/marketplace.json` exists at the specified path * Ensure JSON syntax is valid using `claude plugin validate` or `/plugin validate` * For private repositories, confirm you have access permissions ### Marketplace validation errors Run `claude plugin validate .` or `/plugin validate .` from your marketplace directory to check for issues. Common errors: | Error | Cause | Solution | | :------------------------------------------------ | :------------------------------ | :------------------------------------------------------------ | | `File not found: .claude-plugin/marketplace.json` | Missing manifest | Create `.claude-plugin/marketplace.json` with required fields | | `Invalid JSON syntax: Unexpected token...` | JSON syntax error | Check for missing commas, extra commas, or unquoted strings | | `Duplicate plugin name "x" found in marketplace` | Two plugins share the same name | Give each plugin a unique `name` value | | `plugins[0].source: Path traversal not allowed` | Source path contains `..` | Use paths relative to marketplace root without `..` | **Warnings** (non-blocking): * `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array * `No marketplace description provided`: add `metadata.description` to help users understand your marketplace * `Plugin "x" uses npm source which is not yet fully implemented`: use `github` or local path sources instead ### Plugin installation failures **Symptoms**: Marketplace appears but plugin installation fails **Solutions**: * Verify plugin source URLs are accessible * Check that plugin directories contain required files * For GitHub sources, ensure repositories are public or you have access * Test plugin sources manually by cloning/downloading ### Private repository authentication fails **Symptoms**: Authentication errors when installing plugins from private repositories **Solutions**: For manual installation and updates: * Verify you're authenticated with your git provider (for example, run `gh auth status` for GitHub) * Check that your credential helper is configured correctly: `git config --global credential.helper` * Try cloning the repository manually to verify your credentials work For background auto-updates: * Set the appropriate token in your environment: `echo $GITHUB_TOKEN` * Check that the token has the required permissions (read access to the repository) * For GitHub, ensure the token has the `repo` scope for private repositories * For GitLab, ensure the token has at least `read_repository` scope * Verify the token hasn't expired ### Plugins with relative paths fail in URL-based marketplaces **Symptoms**: Added a marketplace via URL (such as `https://example.com/marketplace.json`), but plugins with relative path sources like `"./plugins/my-plugin"` fail to install with "path not found" errors. **Cause**: URL-based marketplaces only download the `marketplace.json` file itself. They do not download plugin files from the server. Relative paths in the marketplace entry reference files on the remote server that were not downloaded. **Solutions**: * **Use external sources**: Change plugin entries to use GitHub, npm, or git URL sources instead of relative paths: ```json theme={null} { "name": "my-plugin", "source": { "source": "github", "repo": "owner/repo" } } ``` * **Use a Git-based marketplace**: Host your marketplace in a Git repository and add it with the git URL. Git-based marketplaces clone the entire repository, making relative paths work correctly. ### Files not found after installation **Symptoms**: Plugin installs but references to files fail, especially files outside the plugin directory **Cause**: Plugins are copied to a cache directory rather than used in-place. Paths that reference files outside the plugin's directory (such as `../shared-utils`) won't work because those files aren't copied. **Solutions**: See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for workarounds including symlinks and directory restructuring. For additional debugging tools and common issues, see [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools). ## See also * [Discover and install prebuilt plugins](/en/discover-plugins) - Installing plugins from existing marketplaces * [Plugins](/en/plugins) - Creating your own plugins * [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas * [Plugin settings](/en/settings#plugin-settings) - Plugin configuration options * [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces) - Managed marketplace restrictions --- # Source: https://code.claude.com/docs/en/plugins-reference.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Plugins reference > Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications. Looking to install plugins? See [Discover and install plugins](/en/discover-plugins). For creating plugins, see [Plugins](/en/plugins). For distributing plugins, see [Plugin marketplaces](/en/plugin-marketplaces). This reference provides complete technical specifications for the Claude Code plugin system, including component schemas, CLI commands, and development tools. ## Plugin components reference This section documents the types of components that plugins can provide. ### Skills Plugins add skills to Claude Code, creating `/name` shortcuts that you or Claude can invoke. **Location**: `skills/` or `commands/` directory in plugin root **File format**: Skills are directories with `SKILL.md`; commands are simple markdown files **Skill structure**: ``` skills/ ├── pdf-processor/ │ ├── SKILL.md │ ├── reference.md (optional) │ └── scripts/ (optional) └── code-reviewer/ └── SKILL.md ``` **Integration behavior**: * Skills and commands are automatically discovered when the plugin is installed * Claude can invoke them automatically based on task context * Skills can include supporting files alongside SKILL.md For complete details, see [Skills](/en/skills). ### Agents Plugins can provide specialized subagents for specific tasks that Claude can invoke automatically when appropriate. **Location**: `agents/` directory in plugin root **File format**: Markdown files describing agent capabilities **Agent structure**: ```markdown theme={null} --- description: What this agent specializes in capabilities: ["task1", "task2", "task3"] --- # Agent Name Detailed description of the agent's role, expertise, and when Claude should invoke it. ## Capabilities - Specific task the agent excels at - Another specialized capability - When to use this agent vs others ## Context and examples Provide examples of when this agent should be used and what kinds of problems it solves. ``` **Integration points**: * Agents appear in the `/agents` interface * Claude can invoke agents automatically based on task context * Agents can be invoked manually by users * Plugin agents work alongside built-in Claude agents ### Hooks Plugins can provide event handlers that respond to Claude Code events automatically. **Location**: `hooks/hooks.json` in plugin root, or inline in plugin.json **Format**: JSON configuration with event matchers and actions **Hook configuration**: ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format-code.sh" } ] } ] } } ``` **Available events**: * `PreToolUse`: Before Claude uses any tool * `PostToolUse`: After Claude successfully uses any tool * `PostToolUseFailure`: After Claude tool execution fails * `PermissionRequest`: When a permission dialog is shown * `UserPromptSubmit`: When user submits a prompt * `Notification`: When Claude Code sends notifications * `Stop`: When Claude attempts to stop * `SubagentStart`: When a subagent is started * `SubagentStop`: When a subagent attempts to stop * `SessionStart`: At the beginning of sessions * `SessionEnd`: At the end of sessions * `PreCompact`: Before conversation history is compacted **Hook types**: * `command`: Execute shell commands or scripts * `prompt`: Evaluate a prompt with an LLM (uses `$ARGUMENTS` placeholder for context) * `agent`: Run an agentic verifier with tools for complex verification tasks ### MCP servers Plugins can bundle Model Context Protocol (MCP) servers to connect Claude Code with external tools and services. **Location**: `.mcp.json` in plugin root, or inline in plugin.json **Format**: Standard MCP server configuration **MCP server configuration**: ```json theme={null} { "mcpServers": { "plugin-database": { "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server", "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"], "env": { "DB_PATH": "${CLAUDE_PLUGIN_ROOT}/data" } }, "plugin-api-client": { "command": "npx", "args": ["@company/mcp-server", "--plugin-mode"], "cwd": "${CLAUDE_PLUGIN_ROOT}" } } } ``` **Integration behavior**: * Plugin MCP servers start automatically when the plugin is enabled * Servers appear as standard MCP tools in Claude's toolkit * Server capabilities integrate seamlessly with Claude's existing tools * Plugin servers can be configured independently of user MCP servers ### LSP servers Looking to use LSP plugins? Install them from the official marketplace—search for "lsp" in the `/plugin` Discover tab. This section documents how to create LSP plugins for languages not covered by the official marketplace. Plugins can provide [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) servers to give Claude real-time code intelligence while working on your codebase. LSP integration provides: * **Instant diagnostics**: Claude sees errors and warnings immediately after each edit * **Code navigation**: go to definition, find references, and hover information * **Language awareness**: type information and documentation for code symbols **Location**: `.lsp.json` in plugin root, or inline in `plugin.json` **Format**: JSON configuration mapping language server names to their configurations **`.lsp.json` file format**: ```json theme={null} { "go": { "command": "gopls", "args": ["serve"], "extensionToLanguage": { ".go": "go" } } } ``` **Inline in `plugin.json`**: ```json theme={null} { "name": "my-plugin", "lspServers": { "go": { "command": "gopls", "args": ["serve"], "extensionToLanguage": { ".go": "go" } } } } ``` **Required fields:** | Field | Description | | :-------------------- | :------------------------------------------- | | `command` | The LSP binary to execute (must be in PATH) | | `extensionToLanguage` | Maps file extensions to language identifiers | **Optional fields:** | Field | Description | | :---------------------- | :-------------------------------------------------------- | | `args` | Command-line arguments for the LSP server | | `transport` | Communication transport: `stdio` (default) or `socket` | | `env` | Environment variables to set when starting the server | | `initializationOptions` | Options passed to the server during initialization | | `settings` | Settings passed via `workspace/didChangeConfiguration` | | `workspaceFolder` | Workspace folder path for the server | | `startupTimeout` | Max time to wait for server startup (milliseconds) | | `shutdownTimeout` | Max time to wait for graceful shutdown (milliseconds) | | `restartOnCrash` | Whether to automatically restart the server if it crashes | | `maxRestarts` | Maximum number of restart attempts before giving up | **You must install the language server binary separately.** LSP plugins configure how Claude Code connects to a language server, but they don't include the server itself. If you see `Executable not found in $PATH` in the `/plugin` Errors tab, install the required binary for your language. **Available LSP plugins:** | Plugin | Language server | Install command | | :--------------- | :------------------------- | :----------------------------------------------------------------------------------------- | | `pyright-lsp` | Pyright (Python) | `pip install pyright` or `npm install -g pyright` | | `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` | | `rust-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) | Install the language server first, then install the plugin from the marketplace. *** ## Plugin installation scopes When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it: | Scope | Settings file | Use case | | :-------- | :---------------------------- | :------------------------------------------------------- | | `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) | | `project` | `.claude/settings.json` | Team plugins shared via version control | | `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored | | `managed` | `managed-settings.json` | Managed plugins (read-only, update only) | Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/en/settings#configuration-scopes). *** ## Plugin manifest schema The `plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options. ### Complete schema ```json theme={null} { "name": "plugin-name", "version": "1.2.0", "description": "Brief plugin description", "author": { "name": "Author Name", "email": "author@example.com", "url": "https://github.com/author" }, "homepage": "https://docs.example.com/plugin", "repository": "https://github.com/author/plugin", "license": "MIT", "keywords": ["keyword1", "keyword2"], "commands": ["./custom/commands/special.md"], "agents": "./custom/agents/", "skills": "./custom/skills/", "hooks": "./config/hooks.json", "mcpServers": "./mcp-config.json", "outputStyles": "./styles/", "lspServers": "./.lsp.json" } ``` ### Required fields | Field | Type | Description | Example | | :----- | :----- | :---------------------------------------- | :------------------- | | `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` | ### Metadata fields | Field | Type | Description | Example | | :------------ | :----- | :---------------------------------- | :------------------------------------------------- | | `version` | string | Semantic version | `"2.1.0"` | | `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` | | `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` | | `homepage` | string | Documentation URL | `"https://docs.example.com"` | | `repository` | string | Source code URL | `"https://github.com/user/plugin"` | | `license` | string | License identifier | `"MIT"`, `"Apache-2.0"` | | `keywords` | array | Discovery tags | `["deployment", "ci-cd"]` | ### Component path fields | Field | Type | Description | Example | | :------------- | :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- | | `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` | | `agents` | string\|array | Additional agent files | `"./custom/agents/"` | | `skills` | string\|array | Additional skill directories | `"./custom/skills/"` | | `hooks` | string\|object | Hook config path or inline config | `"./hooks.json"` | | `mcpServers` | string\|object | MCP config path or inline config | `"./mcp-config.json"` | | `outputStyles` | string\|array | Additional output style files/directories | `"./styles/"` | | `lspServers` | string\|object | [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) config for code intelligence (go to definition, find references, etc.) | `"./.lsp.json"` | ### Path behavior rules **Important**: Custom paths supplement default directories - they don't replace them. * If `commands/` exists, it's loaded in addition to custom command paths * All paths must be relative to plugin root and start with `./` * Commands from custom paths use the same naming and namespacing rules * Multiple paths can be specified as arrays for flexibility **Path examples**: ```json theme={null} { "commands": [ "./specialized/deploy.md", "./utilities/batch-process.md" ], "agents": [ "./custom-agents/reviewer.md", "./custom-agents/tester.md" ] } ``` ### Environment variables **`${CLAUDE_PLUGIN_ROOT}`**: Contains the absolute path to your plugin directory. Use this in hooks, MCP servers, and scripts to ensure correct paths regardless of installation location. ```json theme={null} { "hooks": { "PostToolUse": [ { "hooks": [ { "type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/scripts/process.sh" } ] } ] } } ``` *** ## Plugin caching and file resolution For security and verification purposes, Claude Code copies plugins to a cache directory rather than using them in-place. Understanding this behavior is important when developing plugins that reference external files. ### How plugin caching works When you install a plugin, Claude Code copies the plugin files to a cache directory: * **For marketplace plugins with relative paths**: The path specified in the `source` field is copied recursively. For example, if your marketplace entry specifies `"source": "./plugins/my-plugin"`, the entire `./plugins` directory is copied. * **For plugins with `.claude-plugin/plugin.json`**: The implicit root directory (the directory containing `.claude-plugin/plugin.json`) is copied recursively. ### Path traversal limitations Plugins cannot reference files outside their copied directory structure. Paths that traverse outside the plugin root (such as `../shared-utils`) will not work after installation because those external files are not copied to the cache. ### Working with external dependencies If your plugin needs to access files outside its directory, you have two options: **Option 1: Use symlinks** Create symbolic links to external files within your plugin directory. Symlinks are honored during the copy process: ```bash theme={null} # Inside your plugin directory ln -s /path/to/shared-utils ./shared-utils ``` The symlinked content will be copied into the plugin cache. **Option 2: Restructure your marketplace** Set the plugin path to a parent directory that contains all required files, then provide the rest of the plugin manifest directly in the marketplace entry: ```json theme={null} { "name": "my-plugin", "source": "./", "description": "Plugin that needs root-level access", "commands": ["./plugins/my-plugin/commands/"], "agents": ["./plugins/my-plugin/agents/"], "strict": false } ``` This approach copies the entire marketplace root, giving your plugin access to sibling directories. Symlinks that point to locations outside the plugin's logical root are followed during copying. This provides flexibility while maintaining the security benefits of the caching system. *** ## Plugin directory structure ### Standard plugin layout A complete plugin follows this structure: ``` enterprise-plugin/ ├── .claude-plugin/ # Metadata directory │ └── plugin.json # Required: plugin manifest ├── commands/ # Default command location │ ├── status.md │ └── logs.md ├── agents/ # Default agent location │ ├── security-reviewer.md │ ├── performance-tester.md │ └── compliance-checker.md ├── skills/ # Agent Skills │ ├── code-reviewer/ │ │ └── SKILL.md │ └── pdf-processor/ │ ├── SKILL.md │ └── scripts/ ├── hooks/ # Hook configurations │ ├── hooks.json # Main hook config │ └── security-hooks.json # Additional hooks ├── .mcp.json # MCP server definitions ├── .lsp.json # LSP server configurations ├── scripts/ # Hook and utility scripts │ ├── security-scan.sh │ ├── format-code.py │ └── deploy.js ├── LICENSE # License file └── CHANGELOG.md # Version history ``` The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, hooks/) must be at the plugin root, not inside `.claude-plugin/`. ### File locations reference | Component | Default Location | Purpose | | :-------------- | :--------------------------- | :---------------------------------------------------------- | | **Manifest** | `.claude-plugin/plugin.json` | Required metadata file | | **Commands** | `commands/` | Skill Markdown files (legacy; use `skills/` for new skills) | | **Agents** | `agents/` | Subagent Markdown files | | **Skills** | `skills/` | Skills with `/SKILL.md` structure | | **Hooks** | `hooks/hooks.json` | Hook configuration | | **MCP servers** | `.mcp.json` | MCP server definitions | | **LSP servers** | `.lsp.json` | Language server configurations | *** ## CLI commands reference Claude Code provides CLI commands for non-interactive plugin management, useful for scripting and automation. ### plugin install Install a plugin from available marketplaces. ```bash theme={null} claude plugin install [options] ``` **Arguments:** * ``: Plugin name or `plugin-name@marketplace-name` for a specific marketplace **Options:** | Option | Description | Default | | :-------------------- | :------------------------------------------------ | :------ | | `-s, --scope ` | Installation scope: `user`, `project`, or `local` | `user` | | `-h, --help` | Display help for command | | **Examples:** ```bash theme={null} # Install to user scope (default) claude plugin install formatter@my-marketplace # Install to project scope (shared with team) claude plugin install formatter@my-marketplace --scope project # Install to local scope (gitignored) claude plugin install formatter@my-marketplace --scope local ``` ### plugin uninstall Remove an installed plugin. ```bash theme={null} claude plugin uninstall [options] ``` **Arguments:** * ``: Plugin name or `plugin-name@marketplace-name` **Options:** | Option | Description | Default | | :-------------------- | :-------------------------------------------------- | :------ | | `-s, --scope ` | Uninstall from scope: `user`, `project`, or `local` | `user` | | `-h, --help` | Display help for command | | **Aliases:** `remove`, `rm` ### plugin enable Enable a disabled plugin. ```bash theme={null} claude plugin enable [options] ``` **Arguments:** * ``: Plugin name or `plugin-name@marketplace-name` **Options:** | Option | Description | Default | | :-------------------- | :--------------------------------------------- | :------ | | `-s, --scope ` | Scope to enable: `user`, `project`, or `local` | `user` | | `-h, --help` | Display help for command | | ### plugin disable Disable a plugin without uninstalling it. ```bash theme={null} claude plugin disable [options] ``` **Arguments:** * ``: Plugin name or `plugin-name@marketplace-name` **Options:** | Option | Description | Default | | :-------------------- | :---------------------------------------------- | :------ | | `-s, --scope ` | Scope to disable: `user`, `project`, or `local` | `user` | | `-h, --help` | Display help for command | | ### plugin update Update a plugin to the latest version. ```bash theme={null} claude plugin update [options] ``` **Arguments:** * ``: Plugin name or `plugin-name@marketplace-name` **Options:** | Option | Description | Default | | :-------------------- | :-------------------------------------------------------- | :------ | | `-s, --scope ` | Scope to update: `user`, `project`, `local`, or `managed` | `user` | | `-h, --help` | Display help for command | | *** ## Debugging and development tools ### Debugging commands Use `claude --debug` to see plugin loading details: ```bash theme={null} claude --debug ``` This shows: * Which plugins are being loaded * Any errors in plugin manifests * Command, agent, and hook registration * MCP server initialization ### Common issues | Issue | Cause | Solution | | :---------------------------------- | :------------------------------ | :-------------------------------------------------------------------------------- | | Plugin not loading | Invalid `plugin.json` | Validate JSON syntax with `claude plugin validate` or `/plugin validate` | | Commands not appearing | Wrong directory structure | Ensure `commands/` at root, not in `.claude-plugin/` | | Hooks not firing | Script not executable | Run `chmod +x script.sh` | | MCP server fails | Missing `${CLAUDE_PLUGIN_ROOT}` | Use variable for all plugin paths | | Path errors | Absolute paths used | All paths must be relative and start with `./` | | LSP `Executable not found in $PATH` | Language server not installed | Install the binary (e.g., `npm install -g typescript-language-server typescript`) | ### Example error messages **Manifest validation errors**: * `Invalid JSON syntax: Unexpected token } in JSON at position 142`: check for missing commas, extra commas, or unquoted strings * `Plugin has an invalid manifest file at .claude-plugin/plugin.json. Validation errors: name: Required`: a required field is missing * `Plugin has a corrupt manifest file at .claude-plugin/plugin.json. JSON parse error: ...`: JSON syntax error **Plugin loading errors**: * `Warning: No commands found in plugin my-plugin custom directory: ./cmds. Expected .md files or SKILL.md in subdirectories.`: command path exists but contains no valid command files * `Plugin directory not found at path: ./plugins/my-plugin. Check that the marketplace entry has the correct path.`: the `source` path in marketplace.json points to a non-existent directory * `Plugin my-plugin has conflicting manifests: both plugin.json and marketplace entry specify components.`: remove duplicate component definitions or set `strict: true` in marketplace entry ### Hook troubleshooting **Hook script not executing**: 1. Check the script is executable: `chmod +x ./scripts/your-script.sh` 2. Verify the shebang line: First line should be `#!/bin/bash` or `#!/usr/bin/env bash` 3. Check the path uses `${CLAUDE_PLUGIN_ROOT}`: `"command": "${CLAUDE_PLUGIN_ROOT}/scripts/your-script.sh"` 4. Test the script manually: `./scripts/your-script.sh` **Hook not triggering on expected events**: 1. Verify the event name is correct (case-sensitive): `PostToolUse`, not `postToolUse` 2. Check the matcher pattern matches your tools: `"matcher": "Write|Edit"` for file operations 3. Confirm the hook type is valid: `command`, `prompt`, or `agent` ### MCP server troubleshooting **Server not starting**: 1. Check the command exists and is executable 2. Verify all paths use `${CLAUDE_PLUGIN_ROOT}` variable 3. Check the MCP server logs: `claude --debug` shows initialization errors 4. Test the server manually outside of Claude Code **Server tools not appearing**: 1. Ensure the server is properly configured in `.mcp.json` or `plugin.json` 2. Verify the server implements the MCP protocol correctly 3. Check for connection timeouts in debug output ### Directory structure mistakes **Symptoms**: Plugin loads but components (commands, agents, hooks) are missing. **Correct structure**: Components must be at the plugin root, not inside `.claude-plugin/`. Only `plugin.json` belongs in `.claude-plugin/`. ``` my-plugin/ ├── .claude-plugin/ │ └── plugin.json ← Only manifest here ├── commands/ ← At root level ├── agents/ ← At root level └── hooks/ ← At root level ``` If your components are inside `.claude-plugin/`, move them to the plugin root. **Debug checklist**: 1. Run `claude --debug` and look for "loading plugin" messages 2. Check that each component directory is listed in the debug output 3. Verify file permissions allow reading the plugin files *** ## Distribution and versioning reference ### Version management Follow semantic versioning for plugin releases: ```json theme={null} { "name": "my-plugin", "version": "2.1.0" } ``` **Version format**: `MAJOR.MINOR.PATCH` * **MAJOR**: Breaking changes (incompatible API changes) * **MINOR**: New features (backward-compatible additions) * **PATCH**: Bug fixes (backward-compatible fixes) **Best practices**: * Start at `1.0.0` for your first stable release * Update the version in `plugin.json` before distributing changes * Document changes in a `CHANGELOG.md` file * Use pre-release versions like `2.0.0-beta.1` for testing *** ## See also * [Plugins](/en/plugins) - Tutorials and practical usage * [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing marketplaces * [Skills](/en/skills) - Skill development details * [Subagents](/en/sub-agents) - Agent configuration and capabilities * [Hooks](/en/hooks) - Event handling and automation * [MCP](/en/mcp) - External tool integration * [Settings](/en/settings) - Configuration options for plugins --- # Source: https://code.claude.com/docs/en/plugins.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Create plugins > Create custom plugins to extend Claude Code with skills, agents, hooks, and MCP servers. Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. This guide covers creating your own plugins with skills, agents, hooks, and MCP servers. Looking to install existing plugins? See [Discover and install plugins](/en/discover-plugins). For complete technical specifications, see [Plugins reference](/en/plugins-reference). ## When to use plugins vs standalone configuration Claude Code supports two ways to add custom skills, agents, and hooks: | Approach | Skill names | Best for | | :---------------------------------------------------------- | :------------------- | :---------------------------------------------------------------------------------------------- | | **Standalone** (`.claude/` directory) | `/hello` | Personal workflows, project-specific customizations, quick experiments | | **Plugins** (directories with `.claude-plugin/plugin.json`) | `/plugin-name:hello` | Sharing with teammates, distributing to community, versioned releases, reusable across projects | **Use standalone configuration when**: * You're customizing Claude Code for a single project * The configuration is personal and doesn't need to be shared * You're experimenting with skills or hooks before packaging them * You want short skill names like `/hello` or `/review` **Use plugins when**: * You want to share functionality with your team or community * You need the same skills/agents across multiple projects * You want version control and easy updates for your extensions * You're distributing through a marketplace * You're okay with namespaced skills like `/my-plugin:hello` (namespacing prevents conflicts between plugins) Start with standalone configuration in `.claude/` for quick iteration, then [convert to a plugin](#convert-existing-configurations-to-plugins) when you're ready to share. ## Quickstart This quickstart walks you through creating a plugin with a custom skill. You'll create a manifest (the configuration file that defines your plugin), add a skill, and test it locally using the `--plugin-dir` flag. ### Prerequisites * Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code) * Claude Code version 1.0.33 or later (run `claude --version` to check) If you don't see the `/plugin` command, update Claude Code to the latest version. See [Troubleshooting](/en/troubleshooting) for upgrade instructions. ### Create your first plugin Every plugin lives in its own directory containing a manifest and your skills, agents, or hooks. Create one now: ```bash theme={null} mkdir my-first-plugin ``` The manifest file at `.claude-plugin/plugin.json` defines your plugin's identity: its name, description, and version. Claude Code uses this metadata to display your plugin in the plugin manager. Create the `.claude-plugin` directory inside your plugin folder: ```bash theme={null} mkdir my-first-plugin/.claude-plugin ``` Then create `my-first-plugin/.claude-plugin/plugin.json` with this content: ```json my-first-plugin/.claude-plugin/plugin.json theme={null} { "name": "my-first-plugin", "description": "A greeting plugin to learn the basics", "version": "1.0.0", "author": { "name": "Your Name" } } ``` | Field | Purpose | | :------------ | :----------------------------------------------------------------------------------------------------- | | `name` | Unique identifier and skill namespace. Skills are prefixed with this (e.g., `/my-first-plugin:hello`). | | `description` | Shown in the plugin manager when browsing or installing plugins. | | `version` | Track releases using [semantic versioning](/en/plugins-reference#version-management). | | `author` | Optional. Helpful for attribution. | For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/en/plugins-reference#plugin-manifest-schema). Skills live in the `skills/` directory. Each skill is a folder containing a `SKILL.md` file. The folder name becomes the skill name, prefixed with the plugin's namespace (`hello/` in a plugin named `my-first-plugin` creates `/my-first-plugin:hello`). Create a skill directory in your plugin folder: ```bash theme={null} mkdir -p my-first-plugin/skills/hello ``` Then create `my-first-plugin/skills/hello/SKILL.md` with this content: ```markdown my-first-plugin/skills/hello/SKILL.md theme={null} --- description: Greet the user with a friendly message disable-model-invocation: true --- Greet the user warmly and ask how you can help them today. ``` Run Claude Code with the `--plugin-dir` flag to load your plugin: ```bash theme={null} claude --plugin-dir ./my-first-plugin ``` Once Claude Code starts, try your new command: ```shell theme={null} /my-first-plugin:hello ``` You'll see Claude respond with a greeting. Run `/help` to see your command listed under the plugin namespace. **Why namespacing?** Plugin skills are always namespaced (like `/greet:hello`) to prevent conflicts when multiple plugins have skills with the same name. To change the namespace prefix, update the `name` field in `plugin.json`. Make your skill dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the skill name. Update your `hello.md` file: ```markdown my-first-plugin/commands/hello.md theme={null} --- description: Greet the user with a personalized message --- # Hello Command Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging. ``` Restart Claude Code to pick up the changes, then try the command with your name: ```shell theme={null} /my-first-plugin:hello Alex ``` Claude will greet you by name. For more on passing arguments to skills, see [Skills](/en/skills#pass-arguments-to-skills). You've successfully created and tested a plugin with these key components: * **Plugin manifest** (`.claude-plugin/plugin.json`): describes your plugin's metadata * **Commands directory** (`commands/`): contains your custom skills * **Skill arguments** (`$ARGUMENTS`): captures user input for dynamic behavior The `--plugin-dir` flag is useful for development and testing. When you're ready to share your plugin with others, see [Create and distribute a plugin marketplace](/en/plugin-marketplaces). ## Plugin structure overview You've created a plugin with a skill, but plugins can include much more: custom agents, hooks, MCP servers, and LSP servers. **Common mistake**: Don't put `commands/`, `agents/`, `skills/`, or `hooks/` inside the `.claude-plugin/` directory. Only `plugin.json` goes inside `.claude-plugin/`. All other directories must be at the plugin root level. | Directory | Location | Purpose | | :---------------- | :---------- | :---------------------------------------------- | | `.claude-plugin/` | Plugin root | Contains only `plugin.json` manifest (required) | | `commands/` | Plugin root | Skills as Markdown files | | `agents/` | Plugin root | Custom agent definitions | | `skills/` | Plugin root | Agent Skills with `SKILL.md` files | | `hooks/` | Plugin root | Event handlers in `hooks.json` | | `.mcp.json` | Plugin root | MCP server configurations | | `.lsp.json` | Plugin root | LSP server configurations for code intelligence | **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/plugins-reference). ## Develop more complex plugins Once you're comfortable with basic plugins, you can create more sophisticated extensions. ### Add Skills to your plugin Plugins can include [Agent Skills](/en/skills) to extend Claude's capabilities. Skills are model-invoked: Claude automatically uses them based on the task context. Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files: ``` my-plugin/ ├── .claude-plugin/ │ └── plugin.json └── skills/ └── code-review/ └── SKILL.md ``` Each `SKILL.md` needs frontmatter with `name` and `description` fields, followed by instructions: ```yaml theme={null} --- name: code-review description: Reviews code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality. --- When reviewing code, check for: 1. Code organization and structure 2. Error handling 3. Security concerns 4. Test coverage ``` After installing the plugin, restart Claude Code to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/en/skills). ### Add LSP servers to your plugin For common languages like TypeScript, Python, and Rust, install the pre-built LSP plugins from the official marketplace. Create custom LSP plugins only when you need support for languages not already covered. LSP (Language Server Protocol) plugins give Claude real-time code intelligence. If you need to support a language that doesn't have an official LSP plugin, you can create your own by adding an `.lsp.json` file to your plugin: ```json .lsp.json theme={null} { "go": { "command": "gopls", "args": ["serve"], "extensionToLanguage": { ".go": "go" } } } ``` Users installing your plugin must have the language server binary installed on their machine. For complete LSP configuration options, see [LSP servers](/en/plugins-reference#lsp-servers). ### Organize complex plugins For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/en/plugins-reference#plugin-directory-structure). ### Test your plugins locally Use the `--plugin-dir` flag to test plugins during development. This loads your plugin directly without requiring installation. ```bash theme={null} claude --plugin-dir ./my-plugin ``` As you make changes to your plugin, restart Claude Code to pick up the updates. Test your plugin components: * Try your commands with `/command-name` * Check that agents appear in `/agents` * Verify hooks work as expected You can load multiple plugins at once by specifying the flag multiple times: ```bash theme={null} claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two ``` ### Debug plugin issues If your plugin isn't working as expected: 1. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/` 2. **Test components individually**: Check each command, agent, and hook separately 3. **Use validation and debugging tools**: See [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques ### Share your plugins When your plugin is ready to share: 1. **Add documentation**: Include a `README.md` with installation and usage instructions 2. **Version your plugin**: Use [semantic versioning](/en/plugins-reference#version-management) in your `plugin.json` 3. **Create or use a marketplace**: Distribute through [plugin marketplaces](/en/plugin-marketplaces) for installation 4. **Test with others**: Have team members test the plugin before wider distribution Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins). For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference). ## Convert existing configurations to plugins If you already have skills or hooks in your `.claude/` directory, you can convert them into a plugin for easier sharing and distribution. ### Migration steps Create a new plugin directory: ```bash theme={null} mkdir -p my-plugin/.claude-plugin ``` Create the manifest file at `my-plugin/.claude-plugin/plugin.json`: ```json my-plugin/.claude-plugin/plugin.json theme={null} { "name": "my-plugin", "description": "Migrated from standalone configuration", "version": "1.0.0" } ``` Copy your existing configurations to the plugin directory: ```bash theme={null} # Copy commands cp -r .claude/commands my-plugin/ # Copy agents (if any) cp -r .claude/agents my-plugin/ # Copy skills (if any) cp -r .claude/skills my-plugin/ ``` If you have hooks in your settings, create a hooks directory: ```bash theme={null} mkdir my-plugin/hooks ``` Create `my-plugin/hooks/hooks.json` with your hooks configuration. Copy the `hooks` object from your `.claude/settings.json` or `settings.local.json`, since the format is the same. The command receives hook input as JSON on stdin, so use `jq` to extract the file path: ```json my-plugin/hooks/hooks.json theme={null} { "hooks": { "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npm run lint:fix" }] } ] } } ``` Load your plugin to verify everything works: ```bash theme={null} claude --plugin-dir ./my-plugin ``` Test each component: run your commands, check agents appear in `/agents`, and verify hooks trigger correctly. ### What changes when migrating | Standalone (`.claude/`) | Plugin | | :---------------------------- | :------------------------------- | | Only available in one project | Can be shared via marketplaces | | Files in `.claude/commands/` | Files in `plugin-name/commands/` | | Hooks in `settings.json` | Hooks in `hooks/hooks.json` | | Must manually copy to share | Install with `/plugin install` | After migrating, you can remove the original files from `.claude/` to avoid duplicates. The plugin version will take precedence when loaded. ## Next steps Now that you understand Claude Code's plugin system, here are suggested paths for different goals: ### For plugin users * [Discover and install plugins](/en/discover-plugins): browse marketplaces and install plugins * [Configure team marketplaces](/en/discover-plugins#configure-team-marketplaces): set up repository-level plugins for your team ### For plugin developers * [Create and distribute a marketplace](/en/plugin-marketplaces): package and share your plugins * [Plugins reference](/en/plugins-reference): complete technical specifications * Dive deeper into specific plugin components: * [Skills](/en/skills): skill development details * [Subagents](/en/sub-agents): agent configuration and capabilities * [Hooks](/en/hooks): event handling and automation * [MCP](/en/mcp): external tool integration --- # Source: https://code.claude.com/docs/en/quickstart.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Quickstart > Welcome to Claude Code! This quickstart guide will have you using AI-powered coding assistance in just a few minutes. By the end, you'll understand how to use Claude Code for common development tasks. ## Before you begin Make sure you have: * A terminal or command prompt open * A code project to work with * A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise), [Claude Console](https://console.anthropic.com/) account, or access through a [supported cloud provider](/en/third-party-integrations) This guide covers the terminal CLI. Claude Code is also available on the [web](https://claude.ai/code), as a [desktop app](/en/desktop), in [VS Code](/en/vs-code) and [JetBrains IDEs](/en/jetbrains), in [Slack](/en/slack), and in CI/CD with [GitHub Actions](/en/github-actions) and [GitLab](/en/gitlab-ci-cd). See [all interfaces](/en/overview#use-claude-code-everywhere). ## Step 1: Install Claude Code To install Claude Code, use one of the following methods: **macOS, Linux, WSL:** ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash ``` **Windows PowerShell:** ```powershell theme={null} irm https://claude.ai/install.ps1 | iex ``` **Windows CMD:** ```batch theme={null} curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd ``` Native installations automatically update in the background to keep you on the latest version. ```sh theme={null} brew install --cask claude-code ``` Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes. ```powershell theme={null} winget install Anthropic.ClaudeCode ``` WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes. ## Step 2: Log in to your account Claude Code requires an account to use. When you start an interactive session with the `claude` command, you'll need to log in: ```bash theme={null} claude # You'll be prompted to log in on first use ``` ```bash theme={null} /login # Follow the prompts to log in with your account ``` You can log in using any of these account types: * [Claude Pro, Max, Teams, or Enterprise](https://claude.com/pricing) (recommended) * [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits). On first login, a "Claude Code" workspace is automatically created in the Console for centralized cost tracking. * [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) (enterprise cloud providers) Once logged in, your credentials are stored and you won't need to log in again. To switch accounts later, use the `/login` command. ## Step 3: Start your first session Open your terminal in any project directory and start Claude Code: ```bash theme={null} cd /path/to/your/project claude ``` You'll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands or `/resume` to continue a previous conversation. After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/authentication#credential-management). ## Step 4: Ask your first question Let's start with understanding your codebase. Try one of these commands: ``` what does this project do? ``` Claude will analyze your files and provide a summary. You can also ask more specific questions: ``` what technologies does this project use? ``` ``` where is the main entry point? ``` ``` explain the folder structure ``` You can also ask Claude about its own capabilities: ``` what can Claude Code do? ``` ``` how do I create custom skills in Claude Code? ``` ``` can Claude Code work with Docker? ``` Claude Code reads your files as needed - you don't have to manually add context. Claude also has access to its own documentation and can answer questions about its features and capabilities. ## Step 5: Make your first code change Now let's make Claude Code do some actual coding. Try a simple task: ``` add a hello world function to the main file ``` Claude Code will: 1. Find the appropriate file 2. Show you the proposed changes 3. Ask for your approval 4. Make the edit Claude Code always asks for permission before modifying files. You can approve individual changes or enable "Accept all" mode for a session. ## Step 6: Use Git with Claude Code Claude Code makes Git operations conversational: ``` what files have I changed? ``` ``` commit my changes with a descriptive message ``` You can also prompt for more complex Git operations: ``` create a new branch called feature/quickstart ``` ``` show me the last 5 commits ``` ``` help me resolve merge conflicts ``` ## Step 7: Fix a bug or add a feature Claude is proficient at debugging and feature implementation. Describe what you want in natural language: ``` add input validation to the user registration form ``` Or fix existing issues: ``` there's a bug where users can submit empty forms - fix it ``` Claude Code will: * Locate the relevant code * Understand the context * Implement a solution * Run tests if available ## Step 8: Test out other common workflows There are a number of ways to work with Claude: **Refactor code** ``` refactor the authentication module to use async/await instead of callbacks ``` **Write tests** ``` write unit tests for the calculator functions ``` **Update documentation** ``` update the README with installation instructions ``` **Code review** ``` review my changes and suggest improvements ``` **Remember**: Claude Code is your AI pair programmer. Talk to it like you would a helpful colleague - describe what you want to achieve, and it will help you get there. ## Essential commands Here are the most important commands for daily use: | Command | What it does | Example | | ------------------- | ------------------------------------------------------ | ----------------------------------- | | `claude` | Start interactive mode | `claude` | | `claude "task"` | Run a one-time task | `claude "fix the build error"` | | `claude -p "query"` | Run one-off query, then exit | `claude -p "explain this function"` | | `claude -c` | Continue most recent conversation in current directory | `claude -c` | | `claude -r` | Resume a previous conversation | `claude -r` | | `claude commit` | Create a Git commit | `claude commit` | | `/clear` | Clear conversation history | `/clear` | | `/help` | Show available commands | `/help` | | `exit` or Ctrl+C | Exit Claude Code | `exit` | See the [CLI reference](/en/cli-reference) for a complete list of commands. ## Pro tips for beginners For more, see [best practices](/en/best-practices) and [common workflows](/en/common-workflows). Instead of: "fix the bug" Try: "fix the login bug where users see a blank screen after entering wrong credentials" Break complex tasks into steps: ``` 1. create a new database table for user profiles 2. create an API endpoint to get and update user profiles 3. build a webpage that allows users to see and edit their information ``` Before making changes, let Claude understand your code: ``` analyze the database schema ``` ``` build a dashboard showing products that are most frequently returned by our UK customers ``` * Press `?` to see all available keyboard shortcuts * Use Tab for command completion * Press ↑ for command history * Type `/` to see all commands and skills ## What's next? Now that you've learned the basics, explore more advanced features: Understand the agentic loop, built-in tools, and how Claude Code interacts with your project Get better results with effective prompting and project setup Step-by-step guides for common tasks Customize with CLAUDE.md, skills, hooks, MCP, and more ## Getting help * **In Claude Code**: Type `/help` or ask "how do I..." * **Documentation**: You're here! Browse other guides * **Community**: Join our [Discord](https://www.anthropic.com/discord) for tips and support --- # Source: https://code.claude.com/docs/en/sandboxing.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Sandboxing > Learn how Claude Code's sandboxed bash tool provides filesystem and network isolation for safer, more autonomous agent execution. ## Overview Claude Code features native sandboxing to provide a more secure environment for agent execution while reducing the need for constant permission prompts. Instead of asking permission for each bash command, sandboxing creates defined boundaries upfront where Claude Code can work more freely with reduced risk. The sandboxed bash tool uses OS-level primitives to enforce both filesystem and network isolation. ## Why sandboxing matters Traditional permission-based security requires constant user approval for bash commands. While this provides control, it can lead to: * **Approval fatigue**: Repeatedly clicking "approve" can cause users to pay less attention to what they're approving * **Reduced productivity**: Constant interruptions slow down development workflows * **Limited autonomy**: Claude Code cannot work as efficiently when waiting for approvals Sandboxing addresses these challenges by: 1. **Defining clear boundaries**: Specify exactly which directories and network hosts Claude Code can access 2. **Reducing permission prompts**: Safe commands within the sandbox don't require approval 3. **Maintaining security**: Attempts to access resources outside the sandbox trigger immediate notifications 4. **Enabling autonomy**: Claude Code can run more independently within defined limits Effective sandboxing requires **both** filesystem and network isolation. Without network isolation, a compromised agent could exfiltrate sensitive files like SSH keys. Without filesystem isolation, a compromised agent could backdoor system resources to gain network access. When configuring sandboxing it is important to ensure that your configured settings do not create bypasses in these systems. ## How it works ### Filesystem isolation The sandboxed bash tool restricts file system access to specific directories: * **Default writes behavior**: Read and write access to the current working directory and its subdirectories * **Default read behavior**: Read access to the entire computer, except certain denied directories * **Blocked access**: Cannot modify files outside the current working directory without explicit permission * **Configurable**: Define custom allowed and denied paths through settings ### Network isolation Network access is controlled through a proxy server running outside the sandbox: * **Domain restrictions**: Only approved domains can be accessed * **User confirmation**: New domain requests trigger permission prompts * **Custom proxy support**: Advanced users can implement custom rules on outgoing traffic * **Comprehensive coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands ### OS-level enforcement The sandboxed bash tool leverages operating system security primitives: * **macOS**: Uses Seatbelt for sandbox enforcement * **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation * **WSL2**: Uses bubblewrap, same as Linux WSL1 is not supported because bubblewrap requires kernel features only available in WSL2. These OS-level restrictions ensure that all child processes spawned by Claude Code's commands inherit the same security boundaries. ## Getting started ### Prerequisites On **macOS**, sandboxing works out of the box using the built-in Seatbelt framework. On **Linux and WSL2**, install the required packages first: ```bash theme={null} sudo apt-get install bubblewrap socat ``` ```bash theme={null} sudo dnf install bubblewrap socat ``` ### Enable sandboxing You can enable sandboxing by running the `/sandbox` command: ``` > /sandbox ``` This opens a menu where you can choose between sandbox modes. If required dependencies are missing (such as `bubblewrap` or `socat` on Linux), the menu displays installation instructions for your platform. ### Sandbox modes Claude Code offers two sandbox modes: **Auto-allow mode**: Bash commands will attempt to run inside the sandbox and are automatically allowed without requiring permission. Commands that cannot be sandboxed (such as those needing network access to non-allowed hosts) fall back to the regular permission flow. Explicit ask/deny rules you've configured are always respected. **Regular permissions mode**: All bash commands go through the standard permission flow, even when sandboxed. This provides more control but requires more approvals. In both modes, the sandbox enforces the same filesystem and network restrictions. The difference is only in whether sandboxed commands are auto-approved or require explicit permission. Auto-allow mode works independently of your permission mode setting. Even if you're not in "accept edits" mode, sandboxed bash commands will run automatically when auto-allow is enabled. This means bash commands that modify files within the sandbox boundaries will execute without prompting, even when file edit tools would normally require approval. ### Configure sandboxing Customize sandbox behavior through your `settings.json` file. See [Settings](/en/settings#sandbox-settings) for complete configuration reference. Not all commands are compatible with sandboxing out of the box. Some notes that may help you make the most out of the sandbox: * Many CLI tools require accessing certain hosts. As you use these tools, they will request permission to access certain hosts. Granting permission will allow them to access these hosts now and in the future, enabling them to safely execute inside the sandbox. * `watchman` is incompatible with running in the sandbox. If you're running `jest`, consider using `jest --no-watchman` * `docker` is incompatible with running in the sandbox. Consider specifying `docker` in `excludedCommands` to force it to run outside of the sandbox. Claude Code includes an intentional escape hatch mechanism that allows commands to run outside the sandbox when necessary. When a command fails due to sandbox restrictions (such as network connectivity issues or incompatible tools), Claude is prompted to analyze the failure and may retry the command with the `dangerouslyDisableSandbox` parameter. Commands that use this parameter go through the normal Claude Code permissions flow requiring user permission to execute. This allows Claude Code to handle edge cases where certain tools or network operations cannot function within sandbox constraints. You can disable this escape hatch by setting `"allowUnsandboxedCommands": false` in your [sandbox settings](/en/settings#sandbox-settings). When disabled, the `dangerouslyDisableSandbox` parameter is completely ignored and all commands must run sandboxed or be explicitly listed in `excludedCommands`. ## Security benefits ### Protection against prompt injection Even if an attacker successfully manipulates Claude Code's behavior through prompt injection, the sandbox ensures your system remains secure: **Filesystem protection:** * Cannot modify critical config files such as `~/.bashrc` * Cannot modify system-level files in `/bin/` * Cannot read files that are denied in your [Claude permission settings](/en/permissions#manage-permissions) **Network protection:** * Cannot exfiltrate data to attacker-controlled servers * Cannot download malicious scripts from unauthorized domains * Cannot make unexpected API calls to unapproved services * Cannot contact any domains not explicitly allowed **Monitoring and control:** * All access attempts outside the sandbox are blocked at the OS level * You receive immediate notifications when boundaries are tested * You can choose to deny, allow once, or permanently update your configuration ### Reduced attack surface Sandboxing limits the potential damage from: * **Malicious dependencies**: NPM packages or other dependencies with harmful code * **Compromised scripts**: Build scripts or tools with security vulnerabilities * **Social engineering**: Attacks that trick users into running dangerous commands * **Prompt injection**: Attacks that trick Claude into running dangerous commands ### Transparent operation When Claude Code attempts to access network resources outside the sandbox: 1. The operation is blocked at the OS level 2. You receive an immediate notification 3. You can choose to: * Deny the request * Allow it once * Update your sandbox configuration to permanently allow it ## Security Limitations * Network Sandboxing Limitations: The network filtering system operates by restricting the domains that processes are allowed to connect to. It does not otherwise inspect the traffic passing through the proxy and users are responsible for ensuring they only allow trusted domains in their policy. Users should be aware of potential risks that come from allowing broad domains like `github.com` that may allow for data exfiltration. Also, in some cases it may be possible to bypass the network filtering through [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting). * Privilege Escalation via Unix Sockets: The `allowUnixSockets` configuration can inadvertently grant access to powerful system services that could lead to sandbox bypasses. For example, if it is used to allow access to `/var/run/docker.sock` this would effectively grant access to the host system through exploiting the docker socket. Users are encouraged to carefully consider any unix sockets that they allow through the sandbox. * Filesystem Permission Escalation: Overly broad filesystem write permissions can enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files (`.bashrc`, `.zshrc`) can lead to code execution in different security contexts when other users or system processes access these files. * Linux Sandbox Strength: The Linux implementation provides strong filesystem and network isolation but includes an `enableWeakerNestedSandbox` mode that enables it to work inside of Docker environments without privileged namespaces. This option considerably weakens security and should only be used in cases where additional isolation is otherwise enforced. ## How sandboxing relates to permissions Sandboxing and [permissions](/en/permissions) are complementary security layers that work together: * **Permissions** control which tools Claude Code can use and are evaluated before any tool runs. They apply to all tools: Bash, Read, Edit, WebFetch, MCP, and others. * **Sandboxing** provides OS-level enforcement that restricts what Bash commands can access at the filesystem and network level. It applies only to Bash commands and their child processes. Filesystem and network restrictions are configured through permission rules, not sandbox settings: * Use `Read` and `Edit` deny rules to block access to specific files or directories * Use `WebFetch` allow/deny rules to control domain access * Use sandbox `allowedDomains` to control which domains Bash commands can reach This [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) includes starter settings configurations for common deployment scenarios, including sandbox-specific examples. Use these as starting points and adjust them to fit your needs. ## Advanced usage ### Custom proxy configuration For organizations requiring advanced network security, you can implement a custom proxy to: * Decrypt and inspect HTTPS traffic * Apply custom filtering rules * Log all network requests * Integrate with existing security infrastructure ```json theme={null} { "sandbox": { "network": { "httpProxyPort": 8080, "socksProxyPort": 8081 } } } ``` ### Integration with existing security tools The sandboxed bash tool works alongside: * **Permission rules**: Combine with [permission settings](/en/permissions) for defense-in-depth * **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation * **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence) ## Best practices 1. **Start restrictive**: Begin with minimal permissions and expand as needed 2. **Monitor logs**: Review sandbox violation attempts to understand Claude Code's needs 3. **Use environment-specific configs**: Different sandbox rules for development vs. production contexts 4. **Combine with permissions**: Use sandboxing alongside IAM policies for comprehensive security 5. **Test configurations**: Verify your sandbox settings don't block legitimate workflows ## Open source The sandbox runtime is available as an open source npm package for use in your own agent projects. This enables the broader AI agent community to build safer, more secure autonomous systems. This can also be used to sandbox other programs you may wish to run. For example, to sandbox an MCP server you could run: ```bash theme={null} npx @anthropic-ai/sandbox-runtime ``` For implementation details and source code, visit the [GitHub repository](https://github.com/anthropic-experimental/sandbox-runtime). ## Limitations * **Performance overhead**: Minimal, but some filesystem operations may be slightly slower * **Compatibility**: Some tools that require specific system access patterns may need configuration adjustments, or may even need to be run outside of the sandbox * **Platform support**: Supports macOS, Linux, and WSL2. WSL1 is not supported. Native Windows support is planned. ## See also * [Security](/en/security) - Comprehensive security features and best practices * [Permissions](/en/permissions) - Permission configuration and access control * [Settings](/en/settings) - Complete configuration reference * [CLI reference](/en/cli-reference) - Command-line options --- # Source: https://code.claude.com/docs/en/security.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Security > Learn about Claude Code's security safeguards and best practices for safe usage. ## How we approach security ### Security foundation Your code's security is paramount. Claude Code is built with security at its core, developed according to Anthropic's comprehensive security program. Learn more and access resources (SOC 2 Type 2 report, ISO 27001 certificate, etc.) at [Anthropic Trust Center](https://trust.anthropic.com). ### Permission-based architecture Claude Code uses strict read-only permissions by default. When additional actions are needed (editing files, running tests, executing commands), Claude Code requests explicit permission. Users control whether to approve actions once or allow them automatically. We designed Claude Code to be transparent and secure. For example, we require approval for bash commands before executing them, giving you direct control. This approach enables users and organizations to configure permissions directly. For detailed permission configuration, see [Permissions](/en/permissions). ### Built-in protections To mitigate risks in agentic systems: * **Sandboxed bash tool**: [Sandbox](/en/sandboxing) bash commands with filesystem and network isolation, reducing permission prompts while maintaining security. Enable with `/sandbox` to define boundaries where Claude Code can work autonomously * **Write access restriction**: Claude Code can only write to the folder where it was started and its subfolders—it cannot modify files in parent directories without explicit permission. While Claude Code can read files outside the working directory (useful for accessing system libraries and dependencies), write operations are strictly confined to the project scope, creating a clear security boundary * **Prompt fatigue mitigation**: Support for allowlisting frequently used safe commands per-user, per-codebase, or per-organization * **Accept Edits mode**: Batch accept multiple edits while maintaining permission prompts for commands with side effects ### User responsibility Claude Code only has the permissions you grant it. You're responsible for reviewing proposed code and commands for safety before approval. ## Protect against prompt injection Prompt injection is a technique where an attacker attempts to override or manipulate an AI assistant's instructions by inserting malicious text. Claude Code includes several safeguards against these attacks: ### Core protections * **Permission system**: Sensitive operations require explicit approval * **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request * **Input sanitization**: Prevents command injection by processing user inputs * **Command blocklist**: Blocks risky commands that fetch arbitrary content from the web like `curl` and `wget` by default. When explicitly allowed, be aware of [permission pattern limitations](/en/permissions#tool-specific-permission-rules) ### Privacy safeguards We have implemented several safeguards to protect your data, including: * Limited retention periods for sensitive information (see the [Privacy Center](https://privacy.anthropic.com/en/articles/10023548-how-long-do-you-store-my-data) to learn more) * Restricted access to user session data * User control over data training preferences. Consumer users can change their [privacy settings](https://claude.ai/settings/privacy) at any time. For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy). ### Additional safeguards * **Network request approval**: Tools that make network requests require user approval by default * **Isolated context windows**: Web fetch uses a separate context window to avoid injecting potentially malicious prompts * **Trust verification**: First-time codebase runs and new MCP servers require trust verification * Note: Trust verification is disabled when running non-interactively with the `-p` flag * **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted * **Fail-closed matching**: Unmatched commands default to requiring manual approval * **Natural language descriptions**: Complex bash commands include explanations for user understanding * **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/authentication#credential-management) **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system. **Best practices for working with untrusted content**: 1. Review suggested commands before approval 2. Avoid piping untrusted content directly to Claude 3. Verify proposed changes to critical files 4. Use virtual machines (VMs) to run scripts and make tool calls, especially when interacting with external web services 5. Report suspicious behavior with `/bug` While these protections significantly reduce risk, no system is completely immune to all attacks. Always maintain good security practices when working with any AI tool. ## MCP security Claude Code allows users to configure Model Context Protocol (MCP) servers. The list of allowed MCP servers is configured in your source code, as part of Claude Code settings engineers check into source control. We encourage either writing your own MCP servers or using MCP servers from providers that you trust. You are able to configure Claude Code permissions for MCP servers. Anthropic does not manage or audit any MCP servers. ## IDE security See [VS Code security and privacy](/en/vs-code#security-and-privacy) for more information on running Claude Code in an IDE. ## Cloud execution security When using [Claude Code on the web](/en/claude-code-on-the-web), additional security controls are in place: * **Isolated virtual machines**: Each cloud session runs in an isolated, Anthropic-managed VM * **Network access controls**: Network access is limited by default and can be configured to be disabled or allow only specific domains * **Credential protection**: Authentication is handled through a secure proxy that uses a scoped credential inside the sandbox, which is then translated to your actual GitHub authentication token * **Branch restrictions**: Git push operations are restricted to the current working branch * **Audit logging**: All operations in cloud environments are logged for compliance and audit purposes * **Automatic cleanup**: Cloud environments are automatically terminated after session completion For more details on cloud execution, see [Claude Code on the web](/en/claude-code-on-the-web). ## Security best practices ### Working with sensitive code * Review all suggested changes before approval * Use project-specific permission settings for sensitive repositories * Consider using [devcontainers](/en/devcontainer) for additional isolation * Regularly audit your permission settings with `/permissions` ### Team security * Use [managed settings](/en/permissions#managed-settings) to enforce organizational standards * Share approved permission configurations through version control * Train team members on security best practices * Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage) ### Reporting security issues If you discover a security vulnerability in Claude Code: 1. Do not disclose it publicly 2. Report it through our [HackerOne program](https://hackerone.com/anthropic-vdp/reports/new?type=team\&report_type=vulnerability) 3. Include detailed reproduction steps 4. Allow time for us to address the issue before public disclosure ## Related resources * [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands * [Permissions](/en/permissions) - Configure permissions and access controls * [Monitoring usage](/en/monitoring-usage) - Track and audit Claude Code activity * [Development containers](/en/devcontainer) - Secure, isolated environments * [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance --- # Source: https://code.claude.com/docs/en/settings.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code settings > Configure Claude Code with global and project-level settings, and environment variables. Claude Code offers a variety of settings to configure its behavior to meet your needs. You can configure Claude Code by running the `/config` command when using the interactive REPL, which opens a tabbed Settings interface where you can view status information and modify configuration options. ## Configuration scopes Claude Code uses a **scope system** to determine where configurations apply and who they're shared with. Understanding scopes helps you decide how to configure Claude Code for personal use, team collaboration, or enterprise deployment. ### Available scopes | Scope | Location | Who it affects | Shared with team? | | :---------- | :----------------------------------- | :----------------------------------- | :--------------------- | | **Managed** | System-level `managed-settings.json` | All users on the machine | Yes (deployed by IT) | | **User** | `~/.claude/` directory | You, across all projects | No | | **Project** | `.claude/` in repository | All collaborators on this repository | Yes (committed to git) | | **Local** | `.claude/*.local.*` files | You, in this repository only | No (gitignored) | ### When to use each scope **Managed scope** is for: * Security policies that must be enforced organization-wide * Compliance requirements that can't be overridden * Standardized configurations deployed by IT/DevOps **User scope** is best for: * Personal preferences you want everywhere (themes, editor settings) * Tools and plugins you use across all projects * API keys and authentication (stored securely) **Project scope** is best for: * Team-shared settings (permissions, hooks, MCP servers) * Plugins the whole team should have * Standardizing tooling across collaborators **Local scope** is best for: * Personal overrides for a specific project * Testing configurations before sharing with the team * Machine-specific settings that won't work for others ### How scopes interact When the same setting is configured in multiple scopes, more specific scopes take precedence: 1. **Managed** (highest) - can't be overridden by anything 2. **Command line arguments** - temporary session overrides 3. **Local** - overrides project and user settings 4. **Project** - overrides user settings 5. **User** (lowest) - applies when nothing else specifies the setting For example, if a permission is allowed in user settings but denied in project settings, the project setting takes precedence and the permission is blocked. ### What uses scopes Scopes apply to many Claude Code features: | Feature | User location | Project location | Local location | | :-------------- | :------------------------ | :--------------------------------- | :----------------------------- | | **Settings** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` | | **Subagents** | `~/.claude/agents/` | `.claude/agents/` | — | | **MCP servers** | `~/.claude.json` | `.mcp.json` | `~/.claude.json` (per-project) | | **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` | | **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` or `.claude/CLAUDE.md` | `CLAUDE.local.md` | *** ## Settings files The `settings.json` file is our official mechanism for configuring Claude Code through hierarchical settings: * **User settings** are defined in `~/.claude/settings.json` and apply to all projects. * **Project settings** are saved in your project directory: * `.claude/settings.json` for settings that are checked into source control and shared with your team * `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created. * **Managed settings**: For organizations that need centralized control, Claude Code supports `managed-settings.json` and `managed-mcp.json` files that can be deployed to system directories: * macOS: `/Library/Application Support/ClaudeCode/` * Linux and WSL: `/etc/claude-code/` * Windows: `C:\Program Files\ClaudeCode\` These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators. See [Managed settings](/en/permissions#managed-settings) and [Managed MCP configuration](/en/mcp#managed-mcp-configuration) for details. Managed deployments can also restrict **plugin marketplace additions** using `strictKnownMarketplaces`. For more information, see [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions). * **Other configuration** is stored in `~/.claude.json`. This file contains your preferences (theme, notification settings, editor mode), OAuth session, [MCP server](/en/mcp) configurations for user and local scopes, per-project state (allowed tools, trust settings), and various caches. Project-scoped MCP servers are stored separately in `.mcp.json`. Claude Code automatically creates timestamped backups of configuration files and retains the five most recent backups to prevent data loss. ```JSON Example settings.json theme={null} { "$schema": "https://json.schemastore.org/claude-code-settings.json", "permissions": { "allow": [ "Bash(npm run lint)", "Bash(npm run test *)", "Read(~/.zshrc)" ], "deny": [ "Bash(curl *)", "Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)" ] }, "env": { "CLAUDE_CODE_ENABLE_TELEMETRY": "1", "OTEL_METRICS_EXPORTER": "otlp" }, "companyAnnouncements": [ "Welcome to Acme Corp! Review our code guidelines at docs.acme.com", "Reminder: Code reviews required for all PRs", "New security policy in effect" ] } ``` The `$schema` line in the example above points to the [official JSON schema](https://json.schemastore.org/claude-code-settings.json) for Claude Code settings. Adding it to your `settings.json` enables autocomplete and inline validation in VS Code, Cursor, and any other editor that supports JSON schema validation. ### Available settings `settings.json` supports a number of options: | Key | Description | Example | | :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------- | | `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` | | `cleanupPeriodDays` | Sessions inactive for longer than this period are deleted at startup. Setting to `0` immediately deletes all sessions. (default: 30 days) | `20` | | `companyAnnouncements` | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random. | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` | | `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` | | `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` | | `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` | | `permissions` | See table below for structure of permissions. | | | `hooks` | Configure custom commands to run at lifecycle events. See [hooks documentation](/en/hooks) for format | See [hooks](/en/hooks) | | `disableAllHooks` | Disable all [hooks](/en/hooks) | `true` | | `allowManagedHooksOnly` | (Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See [Hook configuration](#hook-configuration) | `true` | | `allowManagedPermissionRulesOnly` | (Managed settings only) Prevent user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply. See [Managed-only settings](/en/permissions#managed-only-settings) | `true` | | `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` | | `otelHeadersHelper` | Script to generate dynamic OpenTelemetry headers. Runs at startup and periodically (see [Dynamic headers](/en/monitoring-usage#dynamic-headers)) | `/bin/generate_otel_headers.sh` | | `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` | | `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` | | `respectGitignore` | Control whether the `@` file picker respects `.gitignore` patterns. When `true` (default), files matching `.gitignore` patterns are excluded from suggestions | `false` | | `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](/en/output-styles) | `"Explanatory"` | | `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts | `claudeai` | | `forceLoginOrgUUID` | Specify the UUID of an organization to automatically select it during login, bypassing the organization selection step. Requires `forceLoginMethod` to be set | `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` | | `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` | | `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` | | `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` | | `allowedMcpServers` | When set in managed-settings.json, allowlist of MCP servers users can configure. Undefined = no restrictions, empty array = lockdown. Applies to all scopes. Denylist takes precedence. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "github" }]` | | `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "filesystem" }]` | | `strictKnownMarketplaces` | When set in managed-settings.json, allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Applies to marketplace additions only. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "acme-corp/plugins" }]` | | `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` | | `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` | | `alwaysThinkingEnabled` | Enable [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) by default for all sessions. Typically configured via the `/config` command rather than editing directly | `true` | | `plansDirectory` | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans` | `"./plans"` | | `showTurnDuration` | Show turn duration messages after responses (e.g., "Cooked for 1m 6s"). Set to `false` to hide these messages | `true` | | `spinnerVerbs` | Customize the action verbs shown in the spinner and turn duration messages. Set `mode` to `"replace"` to use only your verbs, or `"append"` to add them to the defaults | `{"mode": "append", "verbs": ["Pondering", "Crafting"]}` | | `language` | Configure Claude's preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default | `"japanese"` | | `autoUpdatesChannel` | Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` (default) for the most recent release | `"stable"` | | `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` | | `terminalProgressBarEnabled` | Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: `true`) | `false` | ### Permission settings | Keys | Description | Example | | :----------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- | | `allow` | Array of permission rules to allow tool use. See [Permission rule syntax](#permission-rule-syntax) below for pattern matching details | `[ "Bash(git diff *)" ]` | | `ask` | Array of permission rules to ask for confirmation upon tool use. See [Permission rule syntax](#permission-rule-syntax) below | `[ "Bash(git push *)" ]` | | `deny` | Array of permission rules to deny tool use. Use this to exclude sensitive files from Claude Code access. See [Permission rule syntax](#permission-rule-syntax) and [Bash permission limitations](/en/permissions#tool-specific-permission-rules) | `[ "WebFetch", "Bash(curl *)", "Read(./.env)", "Read(./secrets/**)" ]` | | `additionalDirectories` | Additional [working directories](/en/permissions#working-directories) that Claude has access to | `[ "../docs/" ]` | | `defaultMode` | Default [permission mode](/en/permissions#permission-modes) when opening Claude Code | `"acceptEdits"` | | `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. See [managed settings](/en/permissions#managed-settings) | `"disable"` | ### Permission rule syntax Permission rules follow the format `Tool` or `Tool(specifier)`. Rules are evaluated in order: deny rules first, then ask, then allow. The first matching rule wins. Quick examples: | Rule | Effect | | :----------------------------- | :--------------------------------------- | | `Bash` | Matches all Bash commands | | `Bash(npm run *)` | Matches commands starting with `npm run` | | `Read(./.env)` | Matches reading the `.env` file | | `WebFetch(domain:example.com)` | Matches fetch requests to example.com | For the complete rule syntax reference, including wildcard behavior, tool-specific patterns for Read, Edit, WebFetch, MCP, and Task rules, and security limitations of Bash patterns, see [Permission rule syntax](/en/permissions#permission-rule-syntax). ### Sandbox settings Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/en/sandboxing) for details. **Filesystem and network restrictions** are configured via Read, Edit, and WebFetch permission rules, not via these sandbox settings. | Keys | Description | Example | | :---------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------ | | `enabled` | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false | `true` | | `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` | | `excludedCommands` | Commands that should run outside of the sandbox | `["git", "docker"]` | | `allowUnsandboxedCommands` | Allow commands to run outside the sandbox via the `dangerouslyDisableSandbox` parameter. When set to `false`, the `dangerouslyDisableSandbox` escape hatch is completely disabled and all commands must run sandboxed (or be in `excludedCommands`). Useful for enterprise policies that require strict sandboxing. Default: true | `false` | | `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` | | `network.allowAllUnixSockets` | Allow all Unix socket connections in sandbox. Default: false | `true` | | `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` | | `network.allowedDomains` | Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`). | `["github.com", "*.npmjs.org"]` | | `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` | | `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` | | `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false | `true` | **Configuration example:** ```json theme={null} { "sandbox": { "enabled": true, "autoAllowBashIfSandboxed": true, "excludedCommands": ["docker"], "network": { "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"], "allowUnixSockets": [ "/var/run/docker.sock" ], "allowLocalBinding": true } }, "permissions": { "deny": [ "Read(.envrc)", "Read(~/.aws/**)" ] } } ``` **Filesystem and network restrictions** use standard permission rules: * Use `Read` deny rules to block Claude from reading specific files or directories * Use `Edit` allow rules to let Claude write to directories beyond the current working directory * Use `Edit` deny rules to block writes to specific paths * Use `WebFetch` allow/deny rules to control which network domains Claude can access ### Attribution settings Claude Code adds attribution to git commits and pull requests. These are configured separately: * Commits use [git trailers](https://git-scm.com/docs/git-interpret-trailers) (like `Co-Authored-By`) by default, which can be customized or disabled * Pull request descriptions are plain text | Keys | Description | | :------- | :----------------------------------------------------------------------------------------- | | `commit` | Attribution for git commits, including any trailers. Empty string hides commit attribution | | `pr` | Attribution for pull request descriptions. Empty string hides pull request attribution | **Default commit attribution:** ``` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 ``` **Default pull request attribution:** ``` 🤖 Generated with [Claude Code](https://claude.com/claude-code) ``` **Example:** ```json theme={null} { "attribution": { "commit": "Generated with AI\n\nCo-Authored-By: AI ", "pr": "" } } ``` The `attribution` setting takes precedence over the deprecated `includeCoAuthoredBy` setting. To hide all attribution, set `commit` and `pr` to empty strings. ### File suggestion settings Configure a custom command for `@` file path autocomplete. The built-in file suggestion uses fast filesystem traversal, but large monorepos may benefit from project-specific indexing such as a pre-built file index or custom tooling. ```json theme={null} { "fileSuggestion": { "type": "command", "command": "~/.claude/file-suggestion.sh" } } ``` The command runs with the same environment variables as [hooks](/en/hooks), including `CLAUDE_PROJECT_DIR`. It receives JSON via stdin with a `query` field: ```json theme={null} {"query": "src/comp"} ``` Output newline-separated file paths to stdout (currently limited to 15): ``` src/components/Button.tsx src/components/Modal.tsx src/components/Form.tsx ``` **Example:** ```bash theme={null} #!/bin/bash query=$(cat | jq -r '.query') your-repo-file-index --query "$query" | head -20 ``` ### Hook configuration **Managed settings only**: Controls which hooks are allowed to run. This setting can only be configured in [managed settings](#settings-files) and provides administrators with strict control over hook execution. **Behavior when `allowManagedHooksOnly` is `true`:** * Managed hooks and SDK hooks are loaded * User hooks, project hooks, and plugin hooks are blocked **Configuration:** ```json theme={null} { "allowManagedHooksOnly": true } ``` ### Settings precedence Settings apply in order of precedence. From highest to lowest: 1. **Managed settings** (`managed-settings.json`) * Policies deployed by IT/DevOps to system directories * Cannot be overridden by user or project settings 2. **Command line arguments** * Temporary overrides for a specific session 3. **Local project settings** (`.claude/settings.local.json`) * Personal project-specific settings 4. **Shared project settings** (`.claude/settings.json`) * Team-shared project settings in source control 5. **User settings** (`~/.claude/settings.json`) * Personal global settings This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience. For example, if your user settings allow `Bash(npm run *)` but a project's shared settings deny it, the project setting takes precedence and the command is blocked. ### Key points about the configuration system * **Memory files (`CLAUDE.md`)**: Contain instructions and context that Claude loads at startup * **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior * **Skills**: Custom prompts that can be invoked with `/skill-name` or loaded by Claude automatically * **MCP servers**: Extend Claude Code with additional tools and integrations * **Precedence**: Higher-level configurations (Managed) override lower-level ones (User/Project) * **Inheritance**: Settings are merged, with more specific settings adding to or overriding broader ones ### System prompt Claude Code's internal system prompt is not published. To add custom instructions, use `CLAUDE.md` files or the `--append-system-prompt` flag. ### Excluding sensitive files To prevent Claude Code from accessing files containing sensitive information like API keys, secrets, and environment files, use the `permissions.deny` setting in your `.claude/settings.json` file: ```json theme={null} { "permissions": { "deny": [ "Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)", "Read(./config/credentials.json)", "Read(./build)" ] } } ``` This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns are excluded from file discovery and search results, and read operations on these files are denied. ## Subagent configuration Claude Code supports custom AI subagents that can be configured at both user and project levels. These subagents are stored as Markdown files with YAML frontmatter: * **User subagents**: `~/.claude/agents/` - Available across all your projects * **Project subagents**: `.claude/agents/` - Specific to your project and can be shared with your team Subagent files define specialized AI assistants with custom prompts and tool permissions. Learn more about creating and using subagents in the [subagents documentation](/en/sub-agents). ## Plugin configuration Claude Code supports a plugin system that lets you extend functionality with skills, agents, hooks, and MCP servers. Plugins are distributed through marketplaces and can be configured at both user and repository levels. ### Plugin settings Plugin-related settings in `settings.json`: ```json theme={null} { "enabledPlugins": { "formatter@acme-tools": true, "deployer@acme-tools": true, "analyzer@security-plugins": false }, "extraKnownMarketplaces": { "acme-tools": { "source": "github", "repo": "acme-corp/claude-plugins" } } } ``` #### `enabledPlugins` Controls which plugins are enabled. Format: `"plugin-name@marketplace-name": true/false` **Scopes**: * **User settings** (`~/.claude/settings.json`): Personal plugin preferences * **Project settings** (`.claude/settings.json`): Project-specific plugins shared with team * **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed) **Example**: ```json theme={null} { "enabledPlugins": { "code-formatter@team-tools": true, "deployment-tools@team-tools": true, "experimental-features@personal": false } } ``` #### `extraKnownMarketplaces` Defines additional marketplaces that should be made available for the repository. Typically used in repository-level settings to ensure team members have access to required plugin sources. **When a repository includes `extraKnownMarketplaces`**: 1. Team members are prompted to install the marketplace when they trust the folder 2. Team members are then prompted to install plugins from that marketplace 3. Users can skip unwanted marketplaces or plugins (stored in user settings) 4. Installation respects trust boundaries and requires explicit consent **Example**: ```json theme={null} { "extraKnownMarketplaces": { "acme-tools": { "source": { "source": "github", "repo": "acme-corp/claude-plugins" } }, "security-plugins": { "source": { "source": "git", "url": "https://git.example.com/security/plugins.git" } } } } ``` **Marketplace source types**: * `github`: GitHub repository (uses `repo`) * `git`: Any git URL (uses `url`) * `directory`: Local filesystem path (uses `path`, for development only) * `hostPattern`: regex pattern to match marketplace hosts (uses `hostPattern`) #### `strictKnownMarketplaces` **Managed settings only**: Controls which plugin marketplaces users are allowed to add. This setting can only be configured in [`managed-settings.json`](/en/permissions#managed-settings) and provides administrators with strict control over marketplace sources. **Managed settings file locations**: * **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json` * **Linux and WSL**: `/etc/claude-code/managed-settings.json` * **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json` **Key characteristics**: * Only available in managed settings (`managed-settings.json`) * Cannot be overridden by user or project settings (highest precedence) * Enforced BEFORE network/filesystem operations (blocked sources never execute) * Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern`, which uses regex matching **Allowlist behavior**: * `undefined` (default): No restrictions - users can add any marketplace * Empty array `[]`: Complete lockdown - users cannot add any new marketplaces * List of sources: Users can only add marketplaces that match exactly **All supported source types**: The allowlist supports seven marketplace source types. Most sources use exact matching, while `hostPattern` uses regex matching against the marketplace host. 1. **GitHub repositories**: ```json theme={null} { "source": "github", "repo": "acme-corp/approved-plugins" } { "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" } { "source": "github", "repo": "acme-corp/plugins", "ref": "main", "path": "marketplace" } ``` Fields: `repo` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory) 2. **Git repositories**: ```json theme={null} { "source": "git", "url": "https://gitlab.example.com/tools/plugins.git" } { "source": "git", "url": "https://bitbucket.org/acme-corp/plugins.git", "ref": "production" } { "source": "git", "url": "ssh://git@git.example.com/plugins.git", "ref": "v3.1", "path": "approved" } ``` Fields: `url` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory) 3. **URL-based marketplaces**: ```json theme={null} { "source": "url", "url": "https://plugins.example.com/marketplace.json" } { "source": "url", "url": "https://cdn.example.com/marketplace.json", "headers": { "Authorization": "Bearer ${TOKEN}" } } ``` Fields: `url` (required), `headers` (optional: HTTP headers for authenticated access) URL-based marketplaces only download the `marketplace.json` file. They do not download plugin files from the server. Plugins in URL-based marketplaces must use external sources (GitHub, npm, or git URLs) rather than relative paths. For plugins with relative paths, use a Git-based marketplace instead. See [Troubleshooting](/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details. 4. **NPM packages**: ```json theme={null} { "source": "npm", "package": "@acme-corp/claude-plugins" } { "source": "npm", "package": "@acme-corp/approved-marketplace" } ``` Fields: `package` (required, supports scoped packages) 5. **File paths**: ```json theme={null} { "source": "file", "path": "/usr/local/share/claude/acme-marketplace.json" } { "source": "file", "path": "/opt/acme-corp/plugins/marketplace.json" } ``` Fields: `path` (required: absolute path to marketplace.json file) 6. **Directory paths**: ```json theme={null} { "source": "directory", "path": "/usr/local/share/claude/acme-plugins" } { "source": "directory", "path": "/opt/acme-corp/approved-marketplaces" } ``` Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`) 7. **Host pattern matching**: ```json theme={null} { "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" } { "source": "hostPattern", "hostPattern": "^gitlab\\.internal\\.example\\.com$" } ``` Fields: `hostPattern` (required: regex pattern to match against the marketplace host) Use host pattern matching when you want to allow all marketplaces from a specific host without enumerating each repository individually. This is useful for organizations with internal GitHub Enterprise or GitLab servers where developers create their own marketplaces. Host extraction by source type: * `github`: always matches against `github.com` * `git`: extracts hostname from the URL (supports both HTTPS and SSH formats) * `url`: extracts hostname from the URL * `npm`, `file`, `directory`: not supported for host pattern matching **Configuration examples**: Example: allow specific marketplaces only: ```json theme={null} { "strictKnownMarketplaces": [ { "source": "github", "repo": "acme-corp/approved-plugins" }, { "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" }, { "source": "url", "url": "https://plugins.example.com/marketplace.json" }, { "source": "npm", "package": "@acme-corp/compliance-plugins" } ] } ``` Example - Disable all marketplace additions: ```json theme={null} { "strictKnownMarketplaces": [] } ``` Example: allow all marketplaces from an internal git server: ```json theme={null} { "strictKnownMarketplaces": [ { "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" } ] } ``` **Exact matching requirements**: Marketplace sources must match **exactly** for a user's addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields: * The `repo` or `url` must match exactly * The `ref` field must match exactly (or both be undefined) * The `path` field must match exactly (or both be undefined) Examples of sources that **do NOT match**: ```json theme={null} // These are DIFFERENT sources: { "source": "github", "repo": "acme-corp/plugins" } { "source": "github", "repo": "acme-corp/plugins", "ref": "main" } // These are also DIFFERENT: { "source": "github", "repo": "acme-corp/plugins", "path": "marketplace" } { "source": "github", "repo": "acme-corp/plugins" } ``` **Comparison with `extraKnownMarketplaces`**: | Aspect | `strictKnownMarketplaces` | `extraKnownMarketplaces` | | --------------------- | ------------------------------------ | ------------------------------------ | | **Purpose** | Organizational policy enforcement | Team convenience | | **Settings file** | `managed-settings.json` only | Any settings file | | **Behavior** | Blocks non-allowlisted additions | Auto-installs missing marketplaces | | **When enforced** | Before network/filesystem operations | After user trust prompt | | **Can be overridden** | No (highest precedence) | Yes (by higher precedence settings) | | **Source format** | Direct source object | Named marketplace with nested source | | **Use case** | Compliance, security restrictions | Onboarding, standardization | **Format difference**: `strictKnownMarketplaces` uses direct source objects: ```json theme={null} { "strictKnownMarketplaces": [ { "source": "github", "repo": "acme-corp/plugins" } ] } ``` `extraKnownMarketplaces` requires named marketplaces: ```json theme={null} { "extraKnownMarketplaces": { "acme-tools": { "source": { "source": "github", "repo": "acme-corp/plugins" } } } } ``` **Important notes**: * Restrictions are checked BEFORE any network requests or filesystem operations * When blocked, users see clear error messages indicating the source is blocked by managed policy * The restriction applies only to adding NEW marketplaces; previously installed marketplaces remain accessible * Managed settings have the highest precedence and cannot be overridden See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) for user-facing documentation. ### Managing plugins Use the `/plugin` command to manage plugins interactively: * Browse available plugins from marketplaces * Install/uninstall plugins * Enable/disable plugins * View plugin details (commands, agents, hooks provided) * Add/remove marketplaces Learn more about the plugin system in the [plugins documentation](/en/plugins). ## Environment variables Claude Code supports the following environment variables to control its behavior: All environment variables can also be configured in [`settings.json`](#available-settings). This is useful as a way to automatically set environment variables for each session, or to roll out a set of environment variables for your whole team or organization. | Variable | Purpose | | | :--------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | | `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) | | | `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer `) | | | `ANTHROPIC_CUSTOM_HEADERS` | Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers) | | | `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/model-config#environment-variables) | | | `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/en/model-config#environment-variables) | | | `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/en/model-config#environment-variables) | | | `ANTHROPIC_FOUNDRY_API_KEY` | API key for Microsoft Foundry authentication (see [Microsoft Foundry](/en/microsoft-foundry)) | | | `ANTHROPIC_FOUNDRY_BASE_URL` | Full base URL for the Foundry resource (for example, `https://my-resource.services.ai.azure.com/anthropic`). Alternative to `ANTHROPIC_FOUNDRY_RESOURCE` (see [Microsoft Foundry](/en/microsoft-foundry)) | | | `ANTHROPIC_FOUNDRY_RESOURCE` | Foundry resource name (for example, `my-resource`). Required if `ANTHROPIC_FOUNDRY_BASE_URL` is not set (see [Microsoft Foundry](/en/microsoft-foundry)) | | | `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/model-config#environment-variables)) | | | `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) | | | `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock | | | `AWS_BEARER_TOKEN_BEDROCK` | Bedrock API key for authentication (see [Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/)) | | | `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands | | | `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated | | | `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands | | | `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | Set the percentage of context capacity (1-100) at which auto-compaction triggers. By default, auto-compaction triggers at approximately 95% capacity. Use lower values like `50` to compact earlier. Values above the default threshold have no effect. Applies to both main conversations and subagents. This percentage aligns with the `context_window.used_percentage` field available in [status line](/en/statusline) | | | `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command | | | `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | Set to `1` to load CLAUDE.md files from directories specified with `--add-dir`. By default, additional directories do not load memory files | `1` | | `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) | | | `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication | | | `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) | | | `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication | | | `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to disable Anthropic API-specific `anthropic-beta` headers. Use this if experiencing issues like "Unexpected value(s) for the `anthropic-beta` header" when using an LLM gateway with third-party providers | | | `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | Set to `1` to disable all background task functionality, including the `run_in_background` parameter on Bash and subagent tools, auto-backgrounding, and the Ctrl+B shortcut | | | `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Set to `1` to disable the "How is Claude doing?" session quality surveys. Also disabled when using third-party providers or when telemetry is disabled. See [Session quality surveys](/en/data-usage#session-quality-surveys) | | | `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` | Time in milliseconds to wait after the query loop becomes idle before automatically exiting. Useful for automated workflows and scripts using SDK mode | | | `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `true` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution | | | `CLAUDE_CODE_TASK_LIST_ID` | Share a task list across sessions. Set the same ID in multiple Claude Code instances to coordinate on a shared task list. See [Task list](/en/interactive-mode#task-list) | | | `CLAUDE_CODE_TMPDIR` | Override the temp directory used for internal temp files. Claude Code appends `/claude/` to this path. Default: `/tmp` on Unix/macOS, `os.tmpdir()` on Windows | | | `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` | | | `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context | | | `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | Set to `false` to disable prompt suggestions (the "Prompt suggestions" toggle in `/config`). These are the grayed-out predictions that appear in your prompt input after Claude responds. See [Prompt suggestions](/en/interactive-mode#prompt-suggestions) | | | `CLAUDE_CODE_ENABLE_TASKS` | Set to `false` to temporarily revert to the previous TODO list instead of the task tracking system. Default: `true`. See [Task list](/en/interactive-mode#task-list) | | | `CLAUDE_CODE_ENABLE_TELEMETRY` | Set to `1` to enable OpenTelemetry data collection for metrics and logging. Required before configuring OTel exporters. See [Monitoring](/en/monitoring-usage) | | | `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | Override the default token limit for file reads. Useful when you need to read larger files in full | | | `CLAUDE_CODE_HIDE_ACCOUNT_INFO` | Set to `1` to hide your email address and organization name from the Claude Code UI. Useful when streaming or recording | | | `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions | | | `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Default: 32,000. Maximum: 64,000. Increasing this value reduces the effective context window available before [auto-compaction](/en/costs#reduce-token-usage) triggers. | | | `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic OpenTelemetry headers in milliseconds (default: 1740000 / 29 minutes). See [Dynamic headers](/en/monitoring-usage#dynamic-headers) | | | `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) | | | `CLAUDE_CODE_SHELL_PREFIX` | Command prefix to wrap all bash commands (for example, for logging or auditing). Example: `/path/to/logger.sh` will execute `/path/to/logger.sh ` | | | `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) | | | `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) | | | `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (for example, when using an LLM gateway) | | | `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/model-config) | | | `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) | | | `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) | | | `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) | | | `CLAUDE_CONFIG_DIR` | Customize where Claude Code stores its configuration and data files | | | `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. | | | `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command | | | `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages | | | `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting | | | `DISABLE_INSTALLATION_CHECKS` | Set to `1` to disable installation warnings. Use only when manually managing the installation location, as this can mask issues with standard installations | | | `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text | | | `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) | | | `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models | | | `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models | | | `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models | | | `DISABLE_TELEMETRY` | Set to `1` to opt out of Statsig telemetry (note that Statsig events do not include user data like code, file paths, or bash commands) | | | `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/en/mcp#scale-with-mcp-tool-search). Values: `auto` (default, enables at 10% context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `true` (always on), `false` (disabled) | | | `FORCE_AUTOUPDATE_PLUGINS` | Set to `true` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` | | | `HTTP_PROXY` | Specify HTTP proxy server for network connections | | | `HTTPS_PROXY` | Specify HTTPS proxy server for network connections | | | `IS_DEMO` | Set to `true` to enable demo mode: hides email and organization from the UI, skips onboarding, and hides internal commands. Useful for streaming or recording sessions | | | `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens (default: 25000) | | | `MAX_THINKING_TOKENS` | Override the [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) token budget. Thinking is enabled at max budget (31,999 tokens) by default. Use this to limit the budget (for example, `MAX_THINKING_TOKENS=10000`) or disable thinking entirely (`MAX_THINKING_TOKENS=0`). Extended thinking improves performance on complex reasoning and coding tasks but impacts [prompt caching efficiency](https://docs.claude.com/en/docs/build-with-claude/prompt-caching#caching-with-thinking-blocks). | | | `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup | | | `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution | | | `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy | | | `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Maximum number of characters for skill metadata shown to the [Skill tool](/en/skills#control-who-invokes-a-skill) (default: 15000). Legacy name kept for backwards compatibility. | | | `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` instead of `rg` included with Claude Code | | | `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI | | | `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI | | | `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI | | | `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI | | | `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI | | ## Tools available to Claude Claude Code has access to a set of powerful tools that help it understand and modify your codebase: | Tool | Description | Permission Required | | :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ | | **AskUserQuestion** | Asks multiple-choice questions to gather requirements or clarify ambiguity | No | | **Bash** | Executes shell commands in your environment (see [Bash tool behavior](#bash-tool-behavior) below) | Yes | | **TaskOutput** | Retrieves output from a background task (bash shell or subagent) | No | | **Edit** | Makes targeted edits to specific files | Yes | | **ExitPlanMode** | Prompts the user to exit plan mode and start coding | Yes | | **Glob** | Finds files based on pattern matching | No | | **Grep** | Searches for patterns in file contents | No | | **KillShell** | Kills a running background bash shell by its ID | No | | **MCPSearch** | Searches for and loads MCP tools when [tool search](/en/mcp#scale-with-mcp-tool-search) is enabled | No | | **NotebookEdit** | Modifies Jupyter notebook cells | Yes | | **Read** | Reads the contents of files | No | | **Skill** | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes | | **Task** | Runs a sub-agent to handle complex, multi-step tasks | No | | **TaskCreate** | Creates a new task in the task list | No | | **TaskGet** | Retrieves full details for a specific task | No | | **TaskList** | Lists all tasks with their current status | No | | **TaskUpdate** | Updates task status, dependencies, details, or deletes tasks | No | | **WebFetch** | Fetches content from a specified URL | Yes | | **WebSearch** | Performs web searches with domain filtering | Yes | | **Write** | Creates or overwrites files | Yes | | **LSP** | Code intelligence via language servers. Reports type errors and warnings automatically after file edits. Also supports navigation operations: jump to definitions, find references, get type info, list symbols, find implementations, trace call hierarchies. Requires a [code intelligence plugin](/en/discover-plugins#code-intelligence) and its language server binary | No | Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/permissions#tool-specific-permission-rules). ### Bash tool behavior The Bash tool executes shell commands with the following persistence behavior: * **Working directory persists**: When Claude changes the working directory (for example, `cd /path/to/dir`), subsequent Bash commands will execute in that directory. You can use `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1` to reset to the project directory after each command. * **Environment variables do NOT persist**: Environment variables set in one Bash command (for example, `export MY_VAR=value`) are **not** available in subsequent Bash commands. Each Bash command runs in a fresh shell environment. To make environment variables available in Bash commands, you have **three options**: **Option 1: Activate environment before starting Claude Code** (simplest approach) Activate your virtual environment in your terminal before launching Claude Code: ```bash theme={null} conda activate myenv # or: source /path/to/venv/bin/activate claude ``` This works for shell environments but environment variables set within Claude's Bash commands will not persist between commands. **Option 2: Set CLAUDE\_ENV\_FILE before starting Claude Code** (persistent environment setup) Export the path to a shell script containing your environment setup: ```bash theme={null} export CLAUDE_ENV_FILE=/path/to/env-setup.sh claude ``` Where `/path/to/env-setup.sh` contains: ```bash theme={null} conda activate myenv # or: source /path/to/venv/bin/activate # or: export MY_VAR=value ``` Claude Code will source this file before each Bash command, making the environment persistent across all commands. **Option 3: Use a SessionStart hook** (project-specific configuration) Configure in `.claude/settings.json`: ```json theme={null} { "hooks": { "SessionStart": [{ "matcher": "startup", "hooks": [{ "type": "command", "command": "echo 'conda activate myenv' >> \"$CLAUDE_ENV_FILE\"" }] }] } } ``` The hook writes to `$CLAUDE_ENV_FILE`, which is then sourced before each Bash command. This is ideal for team-shared project configurations. See [SessionStart hooks](/en/hooks#persist-environment-variables) for more details on Option 3. ### Extending tools with hooks You can run custom commands before or after any tool executes using [Claude Code hooks](/en/hooks-guide). For example, you could automatically run a Python formatter after Claude modifies Python files, or prevent modifications to production configuration files by blocking Write operations to certain paths. ## See also * [Permissions](/en/permissions): permission system, rule syntax, tool-specific patterns, and managed policies * [Authentication](/en/authentication): set up user access to Claude Code * [Troubleshooting](/en/troubleshooting): solutions for common configuration issues --- # Source: https://code.claude.com/docs/en/setup.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Set up Claude Code > Install, authenticate, and start using Claude Code on your development machine. ## System requirements * **Operating Systems**: macOS 13.0+, Ubuntu 20.04+/Debian 10+, or Windows 10 1809+ / Windows Server 2019+ (with WSL 1, WSL 2, or Git for Windows) * **Hardware**: 4 GB+ RAM * **Network**: Internet connection required (see [network configuration](/en/network-config#network-access-requirements)) * **Shell**: Works best in Bash or Zsh * **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries) ### Additional dependencies * **ripgrep**: Usually included with Claude Code. If search fails, see [search troubleshooting](/en/troubleshooting#search-and-discovery-issues). * **[Node.js 18+](https://nodejs.org/en/download)**: Only required for [deprecated npm installation](#npm-installation-deprecated) ## Installation To install Claude Code, use one of the following methods: **macOS, Linux, WSL:** ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash ``` **Windows PowerShell:** ```powershell theme={null} irm https://claude.ai/install.ps1 | iex ``` **Windows CMD:** ```batch theme={null} curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd ``` Native installations automatically update in the background to keep you on the latest version. ```sh theme={null} brew install --cask claude-code ``` Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes. ```powershell theme={null} winget install Anthropic.ClaudeCode ``` WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes. After the installation process completes, navigate to your project and start Claude Code: ```bash theme={null} cd your-awesome-project claude ``` If you encounter any issues during installation, consult the [troubleshooting guide](/en/troubleshooting). Run `claude doctor` after installation to check your installation type and version. **Alpine Linux and other musl/uClibc-based distributions**: The native installer requires `libgcc`, `libstdc++`, and `ripgrep`. For Alpine: `apk add libgcc libstdc++ ripgrep`. Set `USE_BUILTIN_RIPGREP=0`. ### Authentication #### For individuals 1. **Claude Pro or Max plan** (recommended): Subscribe to Claude's [Pro or Max plan](https://claude.ai/pricing) for a unified subscription that includes both Claude Code and Claude on the web. Manage your account in one place and log in with your Claude.ai account. 2. **Claude Console**: Connect through the [Claude Console](https://console.anthropic.com) and complete the OAuth process. Requires active billing in the Anthropic Console. A "Claude Code" workspace is automatically created for usage tracking and cost management. You can't create API keys for the Claude Code workspace; it's dedicated exclusively for Claude Code usage. #### For teams and organizations 1. **Claude for Teams or Enterprise** (recommended): Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or [Claude for Enterprise](https://anthropic.com/contact-sales) for centralized billing, team management, and access to both Claude Code and Claude on the web. Team members log in with their Claude.ai accounts. 2. **Claude Console with team billing**: Set up a shared [Claude Console](https://console.anthropic.com) organization with team billing. Invite team members and assign roles for usage tracking. 3. **Cloud providers**: Configure Claude Code to use [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) for deployments with your existing cloud infrastructure. ### Install a specific version The native installer accepts either a specific version number or a release channel (`latest` or `stable`). The channel you choose at install time becomes your default for auto-updates. See [Configure release channel](#configure-release-channel) for more information. To install the latest version (default): ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash ``` ```powershell theme={null} irm https://claude.ai/install.ps1 | iex ``` ```batch theme={null} curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd ``` To install the stable version: ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash -s stable ``` ```powershell theme={null} & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) stable ``` ```batch theme={null} curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd stable && del install.cmd ``` To install a specific version number: ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58 ``` ```powershell theme={null} & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58 ``` ```batch theme={null} curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 1.0.58 && del install.cmd ``` ### Binary integrity and code signing * SHA256 checksums for all platforms are published in the release manifests, currently located at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json` (example: replace `{VERSION}` with `2.0.30`) * Signed binaries are distributed for the following platforms: * macOS: Signed by "Anthropic PBC" and notarized by Apple * Windows: Signed by "Anthropic, PBC" ## NPM installation (deprecated) NPM installation is deprecated. Use the [native installation](#installation) method when possible. To migrate an existing npm installation to native, run `claude install`. **Global npm installation** ```sh theme={null} npm install -g @anthropic-ai/claude-code ``` Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. If you encounter permission errors, see [troubleshooting permission errors](/en/troubleshooting#command-not-found-claude-or-permission-errors) for recommended solutions. ## Windows setup **Option 1: Claude Code within WSL** * Both WSL 1 and WSL 2 are supported * WSL 2 supports [sandboxing](/en/sandboxing) for enhanced security. WSL 1 does not support sandboxing. **Option 2: Claude Code on native Windows with Git Bash** * Requires [Git for Windows](https://git-scm.com/downloads/win) * For portable Git installations, specify the path to your `bash.exe`: ```powershell theme={null} $env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe" ``` ## Update Claude Code ### Auto updates Claude Code automatically keeps itself up to date to ensure you have the latest features and security fixes. * **Update checks**: Performed on startup and periodically while running * **Update process**: Downloads and installs automatically in the background * **Notifications**: You'll see a notification when updates are installed * **Applying updates**: Updates take effect the next time you start Claude Code Homebrew and WinGet installations do not auto-update. Use `brew upgrade claude-code` or `winget upgrade Anthropic.ClaudeCode` to update manually. **Known issue:** Claude Code may notify you of updates before the new version is available in these package managers. If an upgrade fails, wait and try again later. ### Configure release channel Configure which release channel Claude Code follows for both auto-updates and `claude update` with the `autoUpdatesChannel` setting: * `"latest"` (default): Receive new features as soon as they're released * `"stable"`: Use a version that is typically about one week old, skipping releases with major regressions Configure this via `/config` → **Auto-update channel**, or add it to your [settings.json file](/en/settings): ```json theme={null} { "autoUpdatesChannel": "stable" } ``` For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/en/permissions#managed-settings). ### Disable auto-updates Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/settings): ```bash theme={null} export DISABLE_AUTOUPDATER=1 ``` ### Update manually ```bash theme={null} claude update ``` ## Uninstall Claude Code If you need to uninstall Claude Code, follow the instructions for your installation method. ### Native installation Remove the Claude Code binary and version files: **macOS, Linux, WSL:** ```bash theme={null} rm -f ~/.local/bin/claude rm -rf ~/.local/share/claude ``` **Windows PowerShell:** ```powershell theme={null} Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force ``` **Windows CMD:** ```batch theme={null} del "%USERPROFILE%\.local\bin\claude.exe" rmdir /s /q "%USERPROFILE%\.local\share\claude" ``` ### Homebrew installation ```bash theme={null} brew uninstall --cask claude-code ``` ### WinGet installation ```powershell theme={null} winget uninstall Anthropic.ClaudeCode ``` ### NPM installation ```bash theme={null} npm uninstall -g @anthropic-ai/claude-code ``` ### Clean up configuration files (optional) Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history. To remove Claude Code settings and cached data: **macOS, Linux, WSL:** ```bash theme={null} # Remove user settings and state rm -rf ~/.claude rm ~/.claude.json # Remove project-specific settings (run from your project directory) rm -rf .claude rm -f .mcp.json ``` **Windows PowerShell:** ```powershell theme={null} # Remove user settings and state Remove-Item -Path "$env:USERPROFILE\.claude" -Recurse -Force Remove-Item -Path "$env:USERPROFILE\.claude.json" -Force # Remove project-specific settings (run from your project directory) Remove-Item -Path ".claude" -Recurse -Force Remove-Item -Path ".mcp.json" -Force ``` **Windows CMD:** ```batch theme={null} REM Remove user settings and state rmdir /s /q "%USERPROFILE%\.claude" del "%USERPROFILE%\.claude.json" REM Remove project-specific settings (run from your project directory) rmdir /s /q ".claude" del ".mcp.json" ``` --- # Source: https://code.claude.com/docs/en/skills.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Extend Claude with skills > Create, manage, and share skills to extend Claude's capabilities in Claude Code. Includes custom slash commands. Skills extend what Claude can do. Create a `SKILL.md` file with instructions, and Claude adds it to its toolkit. Claude uses skills when relevant, or you can invoke one directly with `/skill-name`. For built-in commands like `/help` and `/compact`, see [interactive mode](/en/interactive-mode#built-in-commands). **Custom slash commands have been merged into skills.** A file at `.claude/commands/review.md` and a skill at `.claude/skills/review/SKILL.md` both create `/review` and work the same way. Your existing `.claude/commands/` files keep working. Skills add optional features: a directory for supporting files, frontmatter to [control whether you or Claude invokes them](#control-who-invokes-a-skill), and the ability for Claude to load them automatically when relevant. Claude Code skills follow the [Agent Skills](https://agentskills.io) open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like [invocation control](#control-who-invokes-a-skill), [subagent execution](#run-skills-in-a-subagent), and [dynamic context injection](#inject-dynamic-context). ## Getting started ### Create your first skill This example creates a skill that teaches Claude to explain code using visual diagrams and analogies. Since it uses default frontmatter, Claude can load it automatically when you ask how something works, or you can invoke it directly with `/explain-code`. Create a directory for the skill in your personal skills folder. Personal skills are available across all your projects. ```bash theme={null} mkdir -p ~/.claude/skills/explain-code ``` Every skill needs a `SKILL.md` file with two parts: YAML frontmatter (between `---` markers) that tells Claude when to use the skill, and markdown content with instructions Claude follows when the skill is invoked. The `name` field becomes the `/slash-command`, and the `description` helps Claude decide when to load it automatically. Create `~/.claude/skills/explain-code/SKILL.md`: ```yaml theme={null} --- name: explain-code description: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks "how does this work?" --- When explaining code, always include: 1. **Start with an analogy**: Compare the code to something from everyday life 2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships 3. **Walk through the code**: Explain step-by-step what happens 4. **Highlight a gotcha**: What's a common mistake or misconception? Keep explanations conversational. For complex concepts, use multiple analogies. ``` You can test it two ways: **Let Claude invoke it automatically** by asking something that matches the description: ``` How does this code work? ``` **Or invoke it directly** with the skill name: ``` /explain-code src/auth/login.ts ``` Either way, Claude should include an analogy and ASCII diagram in its explanation. ### Where skills live Where you store a skill determines who can use it: | Location | Path | Applies to | | :--------- | :------------------------------------------------------- | :----------------------------- | | Enterprise | See [managed settings](/en/permissions#managed-settings) | All users in your organization | | Personal | `~/.claude/skills//SKILL.md` | All your projects | | Project | `.claude/skills//SKILL.md` | This project only | | Plugin | `/skills//SKILL.md` | Where plugin is enabled | When skills share the same name across levels, higher-priority locations win: enterprise > personal > project. Plugin skills use a `plugin-name:skill-name` namespace, so they cannot conflict with other levels. If you have files in `.claude/commands/`, those work the same way, but if a skill and a command share the same name, the skill takes precedence. #### Automatic discovery from nested directories When you work with files in subdirectories, Claude Code automatically discovers skills from nested `.claude/skills/` directories. For example, if you're editing a file in `packages/frontend/`, Claude Code also looks for skills in `packages/frontend/.claude/skills/`. This supports monorepo setups where packages have their own skills. Each skill is a directory with `SKILL.md` as the entrypoint: ``` my-skill/ ├── SKILL.md # Main instructions (required) ├── template.md # Template for Claude to fill in ├── examples/ │ └── sample.md # Example output showing expected format └── scripts/ └── validate.sh # Script Claude can execute ``` The `SKILL.md` contains the main instructions and is required. Other files are optional and let you build more powerful skills: templates for Claude to fill in, example outputs showing the expected format, scripts Claude can execute, or detailed reference documentation. Reference these files from your `SKILL.md` so Claude knows what they contain and when to load them. See [Add supporting files](#add-supporting-files) for more details. Files in `.claude/commands/` still work and support the same [frontmatter](#frontmatter-reference). Skills are recommended since they support additional features like supporting files. ## Configure skills Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows. ### Types of skill content Skill files can contain any instructions, but thinking about how you want to invoke them helps guide what to include: **Reference content** adds knowledge Claude applies to your current work. Conventions, patterns, style guides, domain knowledge. This content runs inline so Claude can use it alongside your conversation context. ```yaml theme={null} --- name: api-conventions description: API design patterns for this codebase --- When writing API endpoints: - Use RESTful naming conventions - Return consistent error formats - Include request validation ``` **Task content** gives Claude step-by-step instructions for a specific action, like deployments, commits, or code generation. These are often actions you want to invoke directly with `/skill-name` rather than letting Claude decide when to run them. Add `disable-model-invocation: true` to prevent Claude from triggering it automatically. ```yaml theme={null} --- name: deploy description: Deploy the application to production context: fork disable-model-invocation: true --- Deploy the application: 1. Run the test suite 2. Build the application 3. Push to the deployment target ``` Your `SKILL.md` can contain anything, but thinking through how you want the skill invoked (by you, by Claude, or both) and where you want it to run (inline or in a subagent) helps guide what to include. For complex skills, you can also [add supporting files](#add-supporting-files) to keep the main skill focused. ### Frontmatter reference Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file: ```yaml theme={null} --- name: my-skill description: What this skill does disable-model-invocation: true allowed-tools: Read, Grep --- Your skill instructions here... ``` All fields are optional. Only `description` is recommended so Claude knows when to use the skill. | Field | Required | Description | | :------------------------- | :---------- | :---------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | No | Display name for the skill. If omitted, uses the directory name. Lowercase letters, numbers, and hyphens only (max 64 characters). | | `description` | Recommended | What the skill does and when to use it. Claude uses this to decide when to apply the skill. If omitted, uses the first paragraph of markdown content. | | `argument-hint` | No | Hint shown during autocomplete to indicate expected arguments. Example: `[issue-number]` or `[filename] [format]`. | | `disable-model-invocation` | No | Set to `true` to prevent Claude from automatically loading this skill. Use for workflows you want to trigger manually with `/name`. Default: `false`. | | `user-invocable` | No | Set to `false` to hide from the `/` menu. Use for background knowledge users shouldn't invoke directly. Default: `true`. | | `allowed-tools` | No | Tools Claude can use without asking permission when this skill is active. | | `model` | No | Model to use when this skill is active. | | `context` | No | Set to `fork` to run in a forked subagent context. | | `agent` | No | Which subagent type to use when `context: fork` is set. | | `hooks` | No | Hooks scoped to this skill's lifecycle. See [Hooks in skills and agents](/en/hooks#hooks-in-skills-and-agents) for configuration format. | #### Available string substitutions Skills support string substitution for dynamic values in the skill content: | Variable | Description | | :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | | `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: `. | | `$ARGUMENTS[N]` | Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. | | `$N` | Shorthand for `$ARGUMENTS[N]`, such as `$0` for the first argument or `$1` for the second. | | `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. | **Example using substitutions:** ```yaml theme={null} --- name: session-logger description: Log activity for this session --- Log the following to logs/${CLAUDE_SESSION_ID}.log: $ARGUMENTS ``` ### Add supporting files Skills can include multiple files in their directory. This keeps `SKILL.md` focused on the essentials while letting Claude access detailed reference material only when needed. Large reference docs, API specifications, or example collections don't need to load into context every time the skill runs. ``` my-skill/ ├── SKILL.md (required - overview and navigation) ├── reference.md (detailed API docs - loaded when needed) ├── examples.md (usage examples - loaded when needed) └── scripts/ └── helper.py (utility script - executed, not loaded) ``` Reference supporting files from `SKILL.md` so Claude knows what each file contains and when to load it: ```markdown theme={null} ## Additional resources - For complete API details, see [reference.md](reference.md) - For usage examples, see [examples.md](examples.md) ``` Keep `SKILL.md` under 500 lines. Move detailed reference material to separate files. ### Control who invokes a skill By default, both you and Claude can invoke any skill. You can type `/skill-name` to invoke it directly, and Claude can load it automatically when relevant to your conversation. Two frontmatter fields let you restrict this: * **`disable-model-invocation: true`**: Only you can invoke the skill. Use this for workflows with side effects or that you want to control timing, like `/commit`, `/deploy`, or `/send-slack-message`. You don't want Claude deciding to deploy because your code looks ready. * **`user-invocable: false`**: Only Claude can invoke the skill. Use this for background knowledge that isn't actionable as a command. A `legacy-system-context` skill explains how an old system works. Claude should know this when relevant, but `/legacy-system-context` isn't a meaningful action for users to take. This example creates a deploy skill that only you can trigger. The `disable-model-invocation: true` field prevents Claude from running it automatically: ```yaml theme={null} --- name: deploy description: Deploy the application to production disable-model-invocation: true --- Deploy $ARGUMENTS to production: 1. Run the test suite 2. Build the application 3. Push to the deployment target 4. Verify the deployment succeeded ``` Here's how the two fields affect invocation and context loading: | Frontmatter | You can invoke | Claude can invoke | When loaded into context | | :------------------------------- | :------------- | :---------------- | :----------------------------------------------------------- | | (default) | Yes | Yes | Description always in context, full skill loads when invoked | | `disable-model-invocation: true` | Yes | No | Description not in context, full skill loads when you invoke | | `user-invocable: false` | No | Yes | Description always in context, full skill loads when invoked | In a regular session, skill descriptions are loaded into context so Claude knows what's available, but full skill content only loads when invoked. [Subagents with preloaded skills](/en/sub-agents#preload-skills-into-subagents) work differently: the full skill content is injected at startup. ### Restrict tool access Use the `allowed-tools` field to limit which tools Claude can use when a skill is active. This skill creates a read-only mode where Claude can explore files but not modify them: ```yaml theme={null} --- name: safe-reader description: Read files without making changes allowed-tools: Read, Grep, Glob --- ``` ### Pass arguments to skills Both you and Claude can pass arguments when invoking a skill. Arguments are available via the `$ARGUMENTS` placeholder. This skill fixes a GitHub issue by number. The `$ARGUMENTS` placeholder gets replaced with whatever follows the skill name: ```yaml theme={null} --- name: fix-issue description: Fix a GitHub issue disable-model-invocation: true --- Fix GitHub issue $ARGUMENTS following our coding standards. 1. Read the issue description 2. Understand the requirements 3. Implement the fix 4. Write tests 5. Create a commit ``` When you run `/fix-issue 123`, Claude receives "Fix GitHub issue 123 following our coding standards..." If you invoke a skill with arguments but the skill doesn't include `$ARGUMENTS`, Claude Code appends `ARGUMENTS: ` to the end of the skill content so Claude still sees what you typed. To access individual arguments by position, use `$ARGUMENTS[N]` or the shorter `$N`: ```yaml theme={null} --- name: migrate-component description: Migrate a component from one framework to another --- Migrate the $ARGUMENTS[0] component from $ARGUMENTS[1] to $ARGUMENTS[2]. Preserve all existing behavior and tests. ``` Running `/migrate-component SearchBar React Vue` replaces `$ARGUMENTS[0]` with `SearchBar`, `$ARGUMENTS[1]` with `React`, and `$ARGUMENTS[2]` with `Vue`. The same skill using the `$N` shorthand: ```yaml theme={null} --- name: migrate-component description: Migrate a component from one framework to another --- Migrate the $0 component from $1 to $2. Preserve all existing behavior and tests. ``` ## Advanced patterns ### Inject dynamic context The `!`command\`\` syntax runs shell commands before the skill content is sent to Claude. The command output replaces the placeholder, so Claude receives actual data, not the command itself. This skill summarizes a pull request by fetching live PR data with the GitHub CLI. The `!`gh pr diff\`\` and other commands run first, and their output gets inserted into the prompt: ```yaml theme={null} --- name: pr-summary description: Summarize changes in a pull request context: fork agent: Explore allowed-tools: Bash(gh *) --- ## Pull request context - PR diff: !`gh pr diff` - PR comments: !`gh pr view --comments` - Changed files: !`gh pr diff --name-only` ## Your task Summarize this pull request... ``` When this skill runs: 1. Each `!`command\`\` executes immediately (before Claude sees anything) 2. The output replaces the placeholder in the skill content 3. Claude receives the fully-rendered prompt with actual PR data This is preprocessing, not something Claude executes. Claude only sees the final result. To enable [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) in a skill, include the word "ultrathink" anywhere in your skill content. ### Run skills in a subagent Add `context: fork` to your frontmatter when you want a skill to run in isolation. The skill content becomes the prompt that drives the subagent. It won't have access to your conversation history. `context: fork` only makes sense for skills with explicit instructions. If your skill contains guidelines like "use these API conventions" without a task, the subagent receives the guidelines but no actionable prompt, and returns without meaningful output. Skills and [subagents](/en/sub-agents) work together in two directions: | Approach | System prompt | Task | Also loads | | :--------------------------- | :---------------------------------------- | :-------------------------- | :--------------------------- | | Skill with `context: fork` | From agent type (`Explore`, `Plan`, etc.) | SKILL.md content | CLAUDE.md | | Subagent with `skills` field | Subagent's markdown body | Claude's delegation message | Preloaded skills + CLAUDE.md | With `context: fork`, you write the task in your skill and pick an agent type to execute it. For the inverse (defining a custom subagent that uses skills as reference material), see [Subagents](/en/sub-agents#preload-skills-into-subagents). #### Example: Research skill using Explore agent This skill runs research in a forked Explore agent. The skill content becomes the task, and the agent provides read-only tools optimized for codebase exploration: ```yaml theme={null} --- name: deep-research description: Research a topic thoroughly context: fork agent: Explore --- Research $ARGUMENTS thoroughly: 1. Find relevant files using Glob and Grep 2. Read and analyze the code 3. Summarize findings with specific file references ``` When this skill runs: 1. A new isolated context is created 2. The subagent receives the skill content as its prompt ("Research \$ARGUMENTS thoroughly...") 3. The `agent` field determines the execution environment (model, tools, and permissions) 4. Results are summarized and returned to your main conversation The `agent` field specifies which subagent configuration to use. Options include built-in agents (`Explore`, `Plan`, `general-purpose`) or any custom subagent from `.claude/agents/`. If omitted, uses `general-purpose`. ### Restrict Claude's skill access By default, Claude can invoke any skill that doesn't have `disable-model-invocation: true` set. Skills that define `allowed-tools` grant Claude access to those tools without per-use approval when the skill is active. Your [permission settings](/en/permissions) still govern baseline approval behavior for all other tools. Built-in commands like `/compact` and `/init` are not available through the Skill tool. Three ways to control which skills Claude can invoke: **Disable all skills** by denying the Skill tool in `/permissions`: ``` # Add to deny rules: Skill ``` **Allow or deny specific skills** using [permission rules](/en/permissions): ``` # Allow only specific skills Skill(commit) Skill(review-pr *) # Deny specific skills Skill(deploy *) ``` Permission syntax: `Skill(name)` for exact match, `Skill(name *)` for prefix match with any arguments. **Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude's context entirely. The `user-invocable` field only controls menu visibility, not Skill tool access. Use `disable-model-invocation: true` to block programmatic invocation. ## Share skills Skills can be distributed at different scopes depending on your audience: * **Project skills**: Commit `.claude/skills/` to version control * **Plugins**: Create a `skills/` directory in your [plugin](/en/plugins) * **Managed**: Deploy organization-wide through [managed settings](/en/permissions#managed-settings) ### Generate visual output Skills can bundle and run scripts in any language, giving Claude capabilities beyond what's possible in a single prompt. One powerful pattern is generating visual output: interactive HTML files that open in your browser for exploring data, debugging, or creating reports. This example creates a codebase explorer: an interactive tree view where you can expand and collapse directories, see file sizes at a glance, and identify file types by color. Create the Skill directory: ```bash theme={null} mkdir -p ~/.claude/skills/codebase-visualizer/scripts ``` Create `~/.claude/skills/codebase-visualizer/SKILL.md`. The description tells Claude when to activate this Skill, and the instructions tell Claude to run the bundled script: ````yaml theme={null} --- name: codebase-visualizer description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files. allowed-tools: Bash(python *) --- # Codebase Visualizer Generate an interactive HTML tree view that shows your project's file structure with collapsible directories. ## Usage Run the visualization script from your project root: ```bash python ~/.claude/skills/codebase-visualizer/scripts/visualize.py . ``` This creates `codebase-map.html` in the current directory and opens it in your default browser. ## What the visualization shows - **Collapsible directories**: Click folders to expand/collapse - **File sizes**: Displayed next to each file - **Colors**: Different colors for different file types - **Directory totals**: Shows aggregate size of each folder ```` Create `~/.claude/skills/codebase-visualizer/scripts/visualize.py`. This script scans a directory tree and generates a self-contained HTML file with: * A **summary sidebar** showing file count, directory count, total size, and number of file types * A **bar chart** breaking down the codebase by file type (top 8 by size) * A **collapsible tree** where you can expand and collapse directories, with color-coded file type indicators The script requires Python but uses only built-in libraries, so there are no packages to install: ```python expandable theme={null} #!/usr/bin/env python3 """Generate an interactive collapsible tree visualization of a codebase.""" import json import sys import webbrowser from pathlib import Path from collections import Counter IGNORE = {'.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build'} def scan(path: Path, stats: dict) -> dict: result = {"name": path.name, "children": [], "size": 0} try: for item in sorted(path.iterdir()): if item.name in IGNORE or item.name.startswith('.'): continue if item.is_file(): size = item.stat().st_size ext = item.suffix.lower() or '(no ext)' result["children"].append({"name": item.name, "size": size, "ext": ext}) result["size"] += size stats["files"] += 1 stats["extensions"][ext] += 1 stats["ext_sizes"][ext] += size elif item.is_dir(): stats["dirs"] += 1 child = scan(item, stats) if child["children"]: result["children"].append(child) result["size"] += child["size"] except PermissionError: pass return result def generate_html(data: dict, stats: dict, output: Path) -> None: ext_sizes = stats["ext_sizes"] total_size = sum(ext_sizes.values()) or 1 sorted_exts = sorted(ext_sizes.items(), key=lambda x: -x[1])[:8] colors = { '.js': '#f7df1e', '.ts': '#3178c6', '.py': '#3776ab', '.go': '#00add8', '.rs': '#dea584', '.rb': '#cc342d', '.css': '#264de4', '.html': '#e34c26', '.json': '#6b7280', '.md': '#083fa1', '.yaml': '#cb171e', '.yml': '#cb171e', '.mdx': '#083fa1', '.tsx': '#3178c6', '.jsx': '#61dafb', '.sh': '#4eaa25', } lang_bars = "".join( f'
{ext}' f'
' f'{(size/total_size)*100:.1f}%
' for ext, size in sorted_exts ) def fmt(b): if b < 1024: return f"{b} B" if b < 1048576: return f"{b/1024:.1f} KB" return f"{b/1048576:.1f} MB" html = f''' Codebase Explorer

📁 {data["name"]}

    ''' output.write_text(html) if __name__ == '__main__': target = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve() stats = {"files": 0, "dirs": 0, "extensions": Counter(), "ext_sizes": Counter()} data = scan(target, stats) out = Path('codebase-map.html') generate_html(data, stats, out) print(f'Generated {out.absolute()}') webbrowser.open(f'file://{out.absolute()}') ``` To test, open Claude Code in any project and ask "Visualize this codebase." Claude runs the script, generates `codebase-map.html`, and opens it in your browser. This pattern works for any visual output: dependency graphs, test coverage reports, API documentation, or database schema visualizations. The bundled script does the heavy lifting while Claude handles orchestration. ## Troubleshooting ### Skill not triggering If Claude doesn't use your skill when expected: 1. Check the description includes keywords users would naturally say 2. Verify the skill appears in `What skills are available?` 3. Try rephrasing your request to match the description more closely 4. Invoke it directly with `/skill-name` if the skill is user-invocable ### Skill triggers too often If Claude uses your skill when you don't want it: 1. Make the description more specific 2. Add `disable-model-invocation: true` if you only want manual invocation ### Claude doesn't see all my skills Skill descriptions are loaded into context so Claude knows what's available. If you have many skills, they may exceed the character budget (default 15,000 characters). Run `/context` to check for a warning about excluded skills. To increase the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable. ## Related resources * **[Subagents](/en/sub-agents)**: delegate tasks to specialized agents * **[Plugins](/en/plugins)**: package and distribute skills with other extensions * **[Hooks](/en/hooks)**: automate workflows around tool events * **[Memory](/en/memory)**: manage CLAUDE.md files for persistent context * **[Interactive mode](/en/interactive-mode#built-in-commands)**: built-in commands and shortcuts * **[Permissions](/en/permissions)**: control tool and skill access --- # Source: https://code.claude.com/docs/en/slack.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Claude Code in Slack > Delegate coding tasks directly from your Slack workspace Claude Code in Slack brings the power of Claude Code directly into your Slack workspace. When you mention `@Claude` with a coding task, Claude automatically detects the intent and creates a Claude Code session on the web, allowing you to delegate development work without leaving your team conversations. This integration is built on the existing Claude for Slack app but adds intelligent routing to Claude Code on the web for coding-related requests. ## Use cases * **Bug investigation and fixes**: Ask Claude to investigate and fix bugs as soon as they're reported in Slack channels. * **Quick code reviews and modifications**: Have Claude implement small features or refactor code based on team feedback. * **Collaborative debugging**: When team discussions provide crucial context (e.g., error reproductions or user reports), Claude can use that information to inform its debugging approach. * **Parallel task execution**: Kick off coding tasks in Slack while you continue other work, receiving notifications when complete. ## Prerequisites Before using Claude Code in Slack, ensure you have the following: | Requirement | Details | | :--------------------- | :----------------------------------------------------------------------------- | | Claude Plan | Pro, Max, Team, or Enterprise with Claude Code access (premium seats) | | Claude Code on the web | Access to [Claude Code on the web](/en/claude-code-on-the-web) must be enabled | | GitHub Account | Connected to Claude Code on the web with at least one repository authenticated | | Slack Authentication | Your Slack account linked to your Claude account via the Claude app | ## Setting up Claude Code in Slack A workspace administrator must install the Claude app from the Slack App Marketplace. Visit the [Slack App Marketplace](https://slack.com/marketplace/A08SF47R6P4) and click "Add to Slack" to begin the installation process. After the app is installed, authenticate your individual Claude account: 1. Open the Claude app in Slack by clicking on "Claude" in your Apps section 2. Navigate to the App Home tab 3. Click "Connect" to link your Slack account with your Claude account 4. Complete the authentication flow in your browser Ensure your Claude Code on the web is properly configured: * Visit [claude.ai/code](https://claude.ai/code) and sign in with the same account you connected to Slack * Connect your GitHub account if not already connected * Authenticate at least one repository that you want Claude to work with After connecting your accounts, configure how Claude handles your messages in Slack. Navigate to the Claude App Home in Slack to find the **Routing Mode** setting. | Mode | Behavior | | :-------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Code only** | Claude routes all @mentions to Claude Code sessions. Best for teams using Claude in Slack exclusively for development tasks. | | **Code + Chat** | Claude analyzes each message and intelligently routes between Claude Code (for coding tasks) and Claude Chat (for writing, analysis, and general questions). Best for teams who want a single @Claude entry point for all types of work. | In Code + Chat mode, if Claude routes a message to Chat but you wanted a coding session, you can click "Retry as Code" to create a Claude Code session instead. Similarly, if it's routed to Code but you wanted a Chat session, you can choose that option in that thread. ## How it works ### Automatic detection When you mention @Claude in a Slack channel or thread, Claude automatically analyzes your message to determine if it's a coding task. If Claude detects coding intent, it will route your request to Claude Code on the web instead of responding as a regular chat assistant. You can also explicitly tell Claude to handle a request as a coding task, even if it doesn't automatically detect it. Claude Code in Slack only works in channels (public or private). It does not work in direct messages (DMs). ### Context gathering **From threads**: When you @mention Claude in a thread, it gathers context from all messages in that thread to understand the full conversation. **From channels**: When mentioned directly in a channel, Claude looks at recent channel messages for relevant context. This context helps Claude understand the problem, select the appropriate repository, and inform its approach to the task. When @Claude is invoked in Slack, Claude is given access to the conversation context to better understand your request. Claude may follow directions from other messages in the context, so users should make sure to only use Claude in trusted Slack conversations. ### Session flow 1. **Initiation**: You @mention Claude with a coding request 2. **Detection**: Claude analyzes your message and detects coding intent 3. **Session creation**: A new Claude Code session is created on claude.ai/code 4. **Progress updates**: Claude posts status updates to your Slack thread as work progresses 5. **Completion**: When finished, Claude @mentions you with a summary and action buttons 6. **Review**: Click "View Session" to see the full transcript, or "Create PR" to open a pull request ## User interface elements ### App Home The App Home tab shows your connection status and allows you to connect or disconnect your Claude account from Slack. ### Message actions * **View Session**: Opens the full Claude Code session in your browser where you can see all work performed, continue the session, or make additional requests. * **Create PR**: Creates a pull request directly from the session's changes. * **Retry as Code**: If Claude initially responds as a chat assistant but you wanted a coding session, click this button to retry the request as a Claude Code task. * **Change Repo**: Allows you to select a different repository if Claude chose incorrectly. ### Repository selection Claude automatically selects a repository based on context from your Slack conversation. If multiple repositories could apply, Claude may display a dropdown allowing you to choose the correct one. ## Access and permissions ### User-level access | Access Type | Requirement | | :------------------- | :-------------------------------------------------------------- | | Claude Code Sessions | Each user runs sessions under their own Claude account | | Usage & Rate Limits | Sessions count against the individual user's plan limits | | Repository Access | Users can only access repositories they've personally connected | | Session History | Sessions appear in your Claude Code history on claude.ai/code | ### Workspace admin permissions Slack workspace administrators control whether the Claude app can be installed in the workspace. Individual users then authenticate with their own Claude accounts to use the integration. ## What's accessible where **In Slack**: You'll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible. **On the web**: The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests. ## Best practices ### Writing effective requests * **Be specific**: Include file names, function names, or error messages when relevant. * **Provide context**: Mention the repository or project if it's not clear from the conversation. * **Define success**: Explain what "done" looks like—should Claude write tests? Update documentation? Create a PR? * **Use threads**: Reply in threads when discussing bugs or features so Claude can gather the full context. ### When to use Slack vs. web **Use Slack when**: Context already exists in a Slack discussion, you want to kick off a task asynchronously, or you're collaborating with teammates who need visibility. **Use the web directly when**: You need to upload files, want real-time interaction during development, or are working on longer, more complex tasks. ## Troubleshooting ### Sessions not starting 1. Verify your Claude account is connected in the Claude App Home 2. Check that you have Claude Code on the web access enabled 3. Ensure you have at least one GitHub repository connected to Claude Code ### Repository not showing 1. Connect the repository in Claude Code on the web at [claude.ai/code](https://claude.ai/code) 2. Verify your GitHub permissions for that repository 3. Try disconnecting and reconnecting your GitHub account ### Wrong repository selected 1. Click the "Change Repo" button to select a different repository 2. Include the repository name in your request for more accurate selection ### Authentication errors 1. Disconnect and reconnect your Claude account in the App Home 2. Ensure you're signed into the correct Claude account in your browser 3. Check that your Claude plan includes Claude Code access ### Session expiration 1. Sessions remain accessible in your Claude Code history on the web 2. You can continue or reference past sessions from [claude.ai/code](https://claude.ai/code) ## Current limitations * **GitHub only**: Currently supports repositories on GitHub. * **One PR at a time**: Each session can create one pull request. * **Rate limits apply**: Sessions use your individual Claude plan's rate limits. * **Web access required**: Users must have Claude Code on the web access; those without it will only get standard Claude chat responses. ## Related resources Learn more about Claude Code on the web General Claude for Slack documentation Install the Claude app from the Slack Marketplace Get additional support --- # Source: https://code.claude.com/docs/en/slash-commands.md # Slash commands > Control Claude's behavior during an interactive session with slash commands. ## Built-in slash commands | Command | Purpose | | :------------------------ | :-------------------------------------------------------------------------------------------------------------------------- | | `/add-dir` | Add additional working directories | | `/agents` | Manage custom AI subagents for specialized tasks | | `/bashes` | List and manage background tasks | | `/bug` | Report bugs (sends conversation to Anthropic) | | `/clear` | Clear conversation history | | `/compact [instructions]` | Compact conversation with optional focus instructions | | `/config` | Open the Settings interface (Config tab) | | `/context` | Visualize current context usage as a colored grid | | `/cost` | Show token usage statistics. See [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details. | | `/doctor` | Checks the health of your Claude Code installation | | `/exit` | Exit the REPL | | `/export [filename]` | Export the current conversation to a file or clipboard | | `/help` | Get usage help | | `/hooks` | Manage hook configurations for tool events | | `/ide` | Manage IDE integrations and show status | | `/init` | Initialize project with `CLAUDE.md` guide | | `/install-github-app` | Set up Claude GitHub Actions for a repository | | `/login` | Switch Anthropic accounts | | `/logout` | Sign out from your Anthropic account | | `/mcp` | Manage MCP server connections and OAuth authentication | | `/memory` | Edit `CLAUDE.md` memory files | | `/model` | Select or change the AI model | | `/output-style [style]` | Set the output style directly or from a selection menu | | `/permissions` | View or update [permissions](/en/iam#configuring-permissions) | | `/plugin` | Manage Claude Code plugins | | `/pr-comments` | View pull request comments | | `/privacy-settings` | View and update your privacy settings | | `/release-notes` | View release notes | | `/resume` | Resume a conversation | | `/review` | Request code review | | `/rewind` | Rewind the conversation and/or code | | `/sandbox` | Enable sandboxed bash tool with filesystem and network isolation for safer, more autonomous execution | | `/security-review` | Complete a security review of pending changes on the current branch | | `/stats` | Visualize daily usage, session history, streaks, and model preferences | | `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity | | `/statusline` | Set up Claude Code's status line UI | | `/terminal-setup` | Install Shift+Enter key binding for newlines (iTerm2 and VSCode only) | | `/todos` | List current TODO items | | `/usage` | For subscription plans only: show plan usage limits and rate limit status | | `/vim` | Enter vim mode for alternating insert and command modes | ## Custom slash commands Custom slash commands allow you to define frequently used prompts as Markdown files that Claude Code can execute. Commands are organized by scope (project-specific or personal) and support namespacing through directory structures. ### Syntax ``` / [arguments] ``` #### Parameters | Parameter | Description | | :--------------- | :---------------------------------------------------------------- | | `` | Name derived from the Markdown filename (without `.md` extension) | | `[arguments]` | Optional arguments passed to the command | ### Command types #### Project commands Commands stored in your repository and shared with your team. When listed in `/help`, these commands show "(project)" after their description. **Location**: `.claude/commands/` The following example creates the `/optimize` command: ```bash theme={null} # Create a project command mkdir -p .claude/commands echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md ``` #### Personal commands Commands available across all your projects. When listed in `/help`, these commands show "(user)" after their description. **Location**: `~/.claude/commands/` The following example creates the `/security-review` command: ```bash theme={null} # Create a personal command mkdir -p ~/.claude/commands echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md ``` ### Features #### Namespacing Use subdirectories to group related commands. Subdirectories appear in the command description but don't affect the command name. For example: * `.claude/commands/frontend/component.md` creates `/component` with description "(project:frontend)" * `~/.claude/commands/component.md` creates `/component` with description "(user)" If a project command and user command share the same name, the project command takes precedence and the user command is silently ignored. For example, if both `.claude/commands/deploy.md` and `~/.claude/commands/deploy.md` exist, `/deploy` runs the project version. Commands in different subdirectories can share names since the subdirectory appears in the description to distinguish them. For example, `.claude/commands/frontend/test.md` and `.claude/commands/backend/test.md` both create `/test`, but show as "(project:frontend)" and "(project:backend)" respectively. #### Arguments Pass dynamic values to commands using argument placeholders: ##### All arguments with `$ARGUMENTS` The `$ARGUMENTS` placeholder captures all arguments passed to the command: ```bash theme={null} # Command definition echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md # Usage > /fix-issue 123 high-priority # $ARGUMENTS becomes: "123 high-priority" ``` ##### Individual arguments with `$1`, `$2`, etc. Access specific arguments individually using positional parameters (similar to shell scripts): ```bash theme={null} # Command definition echo 'Review PR #$1 with priority $2 and assign to $3' > .claude/commands/review-pr.md # Usage > /review-pr 456 high alice # $1 becomes "456", $2 becomes "high", $3 becomes "alice" ``` Use positional arguments when you need to: * Access arguments individually in different parts of your command * Provide defaults for missing arguments * Build more structured commands with specific parameter roles #### Bash command execution Execute bash commands before the slash command runs using the `!` prefix. The output is included in the command context. You *must* include `allowed-tools` with the `Bash` tool, but you can choose the specific bash commands to allow. For example: ```markdown theme={null} --- allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*) description: Create a git commit --- ## Context - Current git status: !`git status` - Current git diff (staged and unstaged changes): !`git diff HEAD` - Current branch: !`git branch --show-current` - Recent commits: !`git log --oneline -10` ## Your task Based on the above changes, create a single git commit. ``` #### File references Include file contents in commands using the `@` prefix to [reference files](/en/common-workflows#reference-files-and-directories). For example: ```markdown theme={null} # Reference a specific file Review the implementation in @src/utils/helpers.js # Reference multiple files Compare @src/old-version.js with @src/new-version.js ``` #### Thinking mode Slash commands can trigger extended thinking by including [extended thinking keywords](/en/common-workflows#use-extended-thinking). ### Frontmatter Command files support frontmatter, useful for specifying metadata about the command: | Frontmatter | Purpose | Default | | :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------- | | `allowed-tools` | List of tools the command can use | Inherits from the conversation | | `argument-hint` | The arguments expected for the slash command. Example: `argument-hint: add [tagId] \| remove [tagId] \| list`. This hint is shown to the user when auto-completing the slash command. | None | | `description` | Brief description of the command | Uses the first line from the prompt | | `model` | Specific model string (see [Models overview](https://docs.claude.com/en/docs/about-claude/models/overview)) | Inherits from the conversation | | `disable-model-invocation` | Whether to prevent `SlashCommand` tool from calling this command | false | For example: ```markdown theme={null} --- allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*) argument-hint: [message] description: Create a git commit model: claude-3-5-haiku-20241022 --- Create a git commit with message: $ARGUMENTS ``` Example using positional arguments: ```markdown theme={null} --- argument-hint: [pr-number] [priority] [assignee] description: Review pull request --- Review PR #$1 with priority $2 and assign to $3. Focus on security, performance, and code style. ``` ## Plugin commands [Plugins](/en/plugins) can provide custom slash commands that integrate seamlessly with Claude Code. Plugin commands work exactly like user-defined commands but are distributed through [plugin marketplaces](/en/plugin-marketplaces). ### How plugin commands work Plugin commands are: * **Namespaced**: Commands can use the format `/plugin-name:command-name` to avoid conflicts (plugin prefix is optional unless there are name collisions) * **Automatically available**: Once a plugin is installed and enabled, its commands appear in `/help` * **Fully integrated**: Support all command features (arguments, frontmatter, bash execution, file references) ### Plugin command structure **Location**: `commands/` directory in plugin root **File format**: Markdown files with frontmatter **Basic command structure**: ```markdown theme={null} --- description: Brief description of what the command does --- # Command Name Detailed instructions for Claude on how to execute this command. Include specific guidance on parameters, expected outcomes, and any special considerations. ``` **Advanced command features**: * **Arguments**: Use placeholders like `{arg1}` in command descriptions * **Subdirectories**: Organize commands in subdirectories for namespacing * **Bash integration**: Commands can execute shell scripts and programs * **File references**: Commands can reference and modify project files ### Invocation patterns ```shell Direct command (when no conflicts) theme={null} /command-name ``` ```shell Plugin-prefixed (when needed for disambiguation) theme={null} /plugin-name:command-name ``` ```shell With arguments (if command supports them) theme={null} /command-name arg1 arg2 ``` ## MCP slash commands MCP servers can expose prompts as slash commands that become available in Claude Code. These commands are dynamically discovered from connected MCP servers. ### Command format MCP commands follow the pattern: ``` /mcp____ [arguments] ``` ### Features #### Dynamic discovery MCP commands are automatically available when: * An MCP server is connected and active * The server exposes prompts through the MCP protocol * The prompts are successfully retrieved during connection #### Arguments MCP prompts can accept arguments defined by the server: ``` # Without arguments > /mcp__github__list_prs # With arguments > /mcp__github__pr_review 456 > /mcp__jira__create_issue "Bug title" high ``` #### Naming conventions Server and prompt names are normalized: * Spaces and special characters become underscores * Names are lowercase for consistency ### Managing MCP connections Use the `/mcp` command to: * View all configured MCP servers * Check connection status * Authenticate with OAuth-enabled servers * Clear authentication tokens * View available tools and prompts from each server ### MCP permissions and wildcards Wildcards aren't supported in [permissions for MCP tools](/en/iam#tool-specific-permission-rules). To approve all tools from an MCP server, use the server name alone, without wildcards: * `mcp__github` (approves all GitHub tools) To approve specific tools, list each one explicitly: * `mcp__github__get_issue` * `mcp__github__list_issues` ## `SlashCommand` tool The `SlashCommand` tool allows Claude to execute [custom slash commands](/en/slash-commands#custom-slash-commands) programmatically during a conversation. This gives Claude the ability to invoke custom commands on your behalf when appropriate. To encourage Claude to use the `SlashCommand` tool, reference the command by name, including the slash, in your prompts or `CLAUDE.md` file. For example: ``` > Run /write-unit-test when you are about to start writing tests. ``` This tool puts each available custom slash command's metadata into context up to the character budget limit. You can use `/context` to monitor token usage and follow the operations below to manage context. ### `SlashCommand` tool supported commands `SlashCommand` tool only supports custom slash commands that: * Are user-defined. Built-in commands like `/compact` and `/init` are *not* supported. * Have the `description` frontmatter field populated. The description is used in the context. For Claude Code versions >= 1.0.124, you can see which custom slash commands `SlashCommand` tool can invoke by running `claude --debug` and triggering a query. ### Disable `SlashCommand` tool To prevent Claude from executing any slash commands via the tool: ```bash theme={null} /permissions # Add to deny rules: SlashCommand ``` This also removes the SlashCommand tool and command descriptions from context. ### Disable specific commands only To prevent a specific slash command from becoming available, add `disable-model-invocation: true` to the slash command's frontmatter. This also removes the command's metadata from context. ### `SlashCommand` permission rules The permission rules support: * **Exact match**: `SlashCommand:/commit` (allows only `/commit` with no arguments) * **Prefix match**: `SlashCommand:/review-pr:*` (allows `/review-pr` with any arguments) ### Character budget limit The `SlashCommand` tool includes a character budget to limit the size of command descriptions shown to Claude. This prevents token overflow when many commands are available. The budget includes each custom slash command's name, arguments, and description. * **Default limit**: 15,000 characters * **Custom limit**: Set via `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable When the character budget is exceeded, Claude sees only a subset of the available commands. In `/context`, a warning shows "M of N commands". ## Skills vs slash commands **Slash commands** and **Agent Skills** serve different purposes in Claude Code: ### Use slash commands for **Quick, frequently used prompts**: * Simple prompt snippets you use often * Quick reminders or templates * Frequently used instructions that fit in one file **Examples**: * `/review` → "Review this code for bugs and suggest improvements" * `/explain` → "Explain this code in simple terms" * `/optimize` → "Analyze this code for performance issues" ### Use Skills for **Comprehensive capabilities with structure**: * Complex workflows with multiple steps * Capabilities requiring scripts or utilities * Knowledge organized across multiple files * Team workflows you want to standardize **Examples**: * PDF processing Skill with form-filling scripts and validation * Data analysis Skill with reference docs for different data types * Documentation Skill with style guides and templates ### Key differences | Aspect | Slash Commands | Agent Skills | | -------------- | -------------------------------- | ----------------------------------- | | **Complexity** | Simple prompts | Complex capabilities | | **Structure** | Single .md file | Directory with SKILL.md + resources | | **Discovery** | Explicit invocation (`/command`) | Automatic (based on context) | | **Files** | One file only | Multiple files, scripts, templates | | **Scope** | Project or personal | Project or personal | | **Sharing** | Via git | Via git | ### Example comparison **As a slash command**: ```markdown theme={null} # .claude/commands/review.md Review this code for: - Security vulnerabilities - Performance issues - Code style violations ``` Usage: `/review` (manual invocation) **As a Skill**: ``` .claude/skills/code-review/ ├── SKILL.md (overview and workflows) ├── SECURITY.md (security checklist) ├── PERFORMANCE.md (performance patterns) ├── STYLE.md (style guide reference) └── scripts/ └── run-linters.sh ``` Usage: "Can you review this code?" (automatic discovery) The Skill provides richer context, validation scripts, and organized reference material. ### When to use each **Use slash commands**: * You invoke the same prompt repeatedly * The prompt fits in a single file * You want explicit control over when it runs **Use Skills**: * Claude should discover the capability automatically * Multiple files or scripts are needed * Complex workflows with validation steps * Team needs standardized, detailed guidance Both slash commands and Skills can coexist. Use the approach that fits your needs. Learn more about [Agent Skills](/en/skills). ## See also * [Plugins](/en/plugins) - Extend Claude Code with custom commands through plugins * [Identity and Access Management](/en/iam) - Complete guide to permissions, including MCP tool permissions * [Interactive mode](/en/interactive-mode) - Shortcuts, input modes, and interactive features * [CLI reference](/en/cli-reference) - Command-line flags and options * [Settings](/en/settings) - Configuration options * [Memory management](/en/memory) - Managing Claude's memory across sessions --- > To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt --- # Source: https://code.claude.com/docs/en/statusline.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Status line configuration > Create a custom status line for Claude Code to display contextual information Make Claude Code your own with a custom status line that displays at the bottom of the Claude Code interface, similar to how terminal prompts (PS1) work in shells like Oh-my-zsh. ## Create a custom status line You can either: * Run `/statusline` to ask Claude Code to help you set up a custom status line. By default, it will try to reproduce your terminal's prompt, but you can provide additional instructions about the behavior you want to Claude Code, such as `/statusline show the model name in orange` * Directly add a `statusLine` command to your `.claude/settings.json`: ```json theme={null} { "statusLine": { "type": "command", "command": "~/.claude/statusline.sh", "padding": 0 // Optional: set to 0 to let status line go to edge } } ``` ## How it Works * The status line is updated when the conversation messages update * Updates run at most every 300 ms * The first line of stdout from your command becomes the status line text * ANSI color codes are supported for styling your status line * Claude Code passes contextual information about the current session (model, directories, etc.) as JSON to your script via stdin ## JSON Input Structure Your status line command receives structured data via stdin in JSON format: ```json theme={null} { "hook_event_name": "Status", "session_id": "abc123...", "transcript_path": "/path/to/transcript.json", "cwd": "/current/working/directory", "model": { "id": "claude-opus-4-1", "display_name": "Opus" }, "workspace": { "current_dir": "/current/working/directory", "project_dir": "/original/project/directory" }, "version": "1.0.80", "output_style": { "name": "default" }, "cost": { "total_cost_usd": 0.01234, "total_duration_ms": 45000, "total_api_duration_ms": 2300, "total_lines_added": 156, "total_lines_removed": 23 }, "context_window": { "total_input_tokens": 15234, "total_output_tokens": 4521, "context_window_size": 200000, "used_percentage": 42.5, "remaining_percentage": 57.5, "current_usage": { "input_tokens": 8500, "output_tokens": 1200, "cache_creation_input_tokens": 5000, "cache_read_input_tokens": 2000 } } } ``` ## Example Scripts ### Simple Status Line ```bash theme={null} #!/bin/bash # Read JSON input from stdin input=$(cat) # Extract values using jq MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name') CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir') echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}" ``` ### Git-Aware Status Line ```bash theme={null} #!/bin/bash # Read JSON input from stdin input=$(cat) # Extract values using jq MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name') CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir') # Show git branch if in a git repo GIT_BRANCH="" if git rev-parse --git-dir > /dev/null 2>&1; then BRANCH=$(git branch --show-current 2>/dev/null) if [ -n "$BRANCH" ]; then GIT_BRANCH=" | 🌿 $BRANCH" fi fi echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}$GIT_BRANCH" ``` ### Python Example ```python theme={null} #!/usr/bin/env python3 import json import sys import os # Read JSON from stdin data = json.load(sys.stdin) # Extract values model = data['model']['display_name'] current_dir = os.path.basename(data['workspace']['current_dir']) # Check for git branch git_branch = "" if os.path.exists('.git'): try: with open('.git/HEAD', 'r') as f: ref = f.read().strip() if ref.startswith('ref: refs/heads/'): git_branch = f" | 🌿 {ref.replace('ref: refs/heads/', '')}" except: pass print(f"[{model}] 📁 {current_dir}{git_branch}") ``` ### Node.js Example ```javascript theme={null} #!/usr/bin/env node const fs = require('fs'); const path = require('path'); // Read JSON from stdin let input = ''; process.stdin.on('data', chunk => input += chunk); process.stdin.on('end', () => { const data = JSON.parse(input); // Extract values const model = data.model.display_name; const currentDir = path.basename(data.workspace.current_dir); // Check for git branch let gitBranch = ''; try { const headContent = fs.readFileSync('.git/HEAD', 'utf8').trim(); if (headContent.startsWith('ref: refs/heads/')) { gitBranch = ` | 🌿 ${headContent.replace('ref: refs/heads/', '')}`; } } catch (e) { // Not a git repo or can't read HEAD } console.log(`[${model}] 📁 ${currentDir}${gitBranch}`); }); ``` ### Helper Function Approach For more complex bash scripts, you can create helper functions: ```bash theme={null} #!/bin/bash # Read JSON input once input=$(cat) # Helper functions for common extractions get_model_name() { echo "$input" | jq -r '.model.display_name'; } get_current_dir() { echo "$input" | jq -r '.workspace.current_dir'; } get_project_dir() { echo "$input" | jq -r '.workspace.project_dir'; } get_version() { echo "$input" | jq -r '.version'; } get_cost() { echo "$input" | jq -r '.cost.total_cost_usd'; } get_duration() { echo "$input" | jq -r '.cost.total_duration_ms'; } get_lines_added() { echo "$input" | jq -r '.cost.total_lines_added'; } get_lines_removed() { echo "$input" | jq -r '.cost.total_lines_removed'; } get_input_tokens() { echo "$input" | jq -r '.context_window.total_input_tokens'; } get_output_tokens() { echo "$input" | jq -r '.context_window.total_output_tokens'; } get_context_window_size() { echo "$input" | jq -r '.context_window.context_window_size'; } # Use the helpers MODEL=$(get_model_name) DIR=$(get_current_dir) echo "[$MODEL] 📁 ${DIR##*/}" ``` ### Context Window Usage Display the percentage of context window consumed. The `context_window` object contains: * `total_input_tokens` / `total_output_tokens`: Cumulative totals across the entire session * `used_percentage`: Pre-calculated percentage of context window used (0-100) * `remaining_percentage`: Pre-calculated percentage of context window remaining (0-100) * `current_usage`: Current context window usage from the last API call (may be `null` if no messages yet) * `input_tokens`: Input tokens in current context * `output_tokens`: Output tokens generated * `cache_creation_input_tokens`: Tokens written to cache * `cache_read_input_tokens`: Tokens read from cache You can use the pre-calculated `used_percentage` and `remaining_percentage` fields directly, or calculate from `current_usage` for more control. **Simple approach using pre-calculated percentages:** ```bash theme={null} #!/bin/bash input=$(cat) MODEL=$(echo "$input" | jq -r '.model.display_name') PERCENT_USED=$(echo "$input" | jq -r '.context_window.used_percentage // 0') echo "[$MODEL] Context: ${PERCENT_USED}%" ``` **Advanced approach with manual calculation:** ```bash theme={null} #!/bin/bash input=$(cat) MODEL=$(echo "$input" | jq -r '.model.display_name') CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size') USAGE=$(echo "$input" | jq '.context_window.current_usage') if [ "$USAGE" != "null" ]; then # Calculate current context from current_usage fields CURRENT_TOKENS=$(echo "$USAGE" | jq '.input_tokens + .cache_creation_input_tokens + .cache_read_input_tokens') PERCENT_USED=$((CURRENT_TOKENS * 100 / CONTEXT_SIZE)) echo "[$MODEL] Context: ${PERCENT_USED}%" else echo "[$MODEL] Context: 0%" fi ``` ## Tips * Keep your status line concise - it should fit on one line * Use emojis (if your terminal supports them) and colors to make information scannable * Use `jq` for JSON parsing in Bash (see examples above) * Test your script by running it manually with mock JSON input: `echo '{"model":{"display_name":"Test"},"workspace":{"current_dir":"/test"}}' | ./statusline.sh` * Consider caching expensive operations (like git status) if needed ## Troubleshooting * If your status line doesn't appear, check that your script is executable (`chmod +x`) * Ensure your script outputs to stdout (not stderr) --- # Source: https://code.claude.com/docs/en/sub-agents.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Create custom subagents > Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management. Subagents are specialized AI assistants that handle specific types of tasks. Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns results. Subagents help you: * **Preserve context** by keeping exploration and implementation out of your main conversation * **Enforce constraints** by limiting which tools a subagent can use * **Reuse configurations** across projects with user-level subagents * **Specialize behavior** with focused system prompts for specific domains * **Control costs** by routing tasks to faster, cheaper models like Haiku Claude uses each subagent's description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it. Claude Code includes several built-in subagents like **Explore**, **Plan**, and **general-purpose**. You can also create custom subagents to handle specific tasks. This page covers the [built-in subagents](#built-in-subagents), [how to create your own](#quickstart-create-your-first-subagent), [full configuration options](#configure-subagents), [patterns for working with subagents](#work-with-subagents), and [example subagents](#example-subagents). ## Built-in subagents Claude Code includes built-in subagents that Claude automatically uses when appropriate. Each inherits the parent conversation's permissions with additional tool restrictions. A fast, read-only agent optimized for searching and analyzing codebases. * **Model**: Haiku (fast, low-latency) * **Tools**: Read-only tools (denied access to Write and Edit tools) * **Purpose**: File discovery, code search, codebase exploration Claude delegates to Explore when it needs to search or understand a codebase without making changes. This keeps exploration results out of your main conversation context. When invoking Explore, Claude specifies a thoroughness level: **quick** for targeted lookups, **medium** for balanced exploration, or **very thorough** for comprehensive analysis. A research agent used during [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to gather context before presenting a plan. * **Model**: Inherits from main conversation * **Tools**: Read-only tools (denied access to Write and Edit tools) * **Purpose**: Codebase research for planning When you're in plan mode and Claude needs to understand your codebase, it delegates research to the Plan subagent. This prevents infinite nesting (subagents cannot spawn other subagents) while still gathering necessary context. A capable agent for complex, multi-step tasks that require both exploration and action. * **Model**: Inherits from main conversation * **Tools**: All tools * **Purpose**: Complex research, multi-step operations, code modifications Claude delegates to general-purpose when the task requires both exploration and modification, complex reasoning to interpret results, or multiple dependent steps. Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically, so you don't need to use them directly. | Agent | Model | When Claude uses it | | :---------------- | :------- | :------------------------------------------------------- | | Bash | Inherits | Running terminal commands in a separate context | | statusline-setup | Sonnet | When you run `/statusline` to configure your status line | | Claude Code Guide | Haiku | When you ask questions about Claude Code features | Beyond these built-in subagents, you can create your own with custom prompts, tool restrictions, permission modes, hooks, and skills. The following sections show how to get started and customize subagents. ## Quickstart: create your first subagent Subagents are defined in Markdown files with YAML frontmatter. You can [create them manually](#write-subagent-files) or use the `/agents` command. This walkthrough guides you through creating a user-level subagent with the `/agent` command. The subagent reviews code and suggests improvements for the codebase. In Claude Code, run: ``` /agents ``` Select **Create new agent**, then choose **User-level**. This saves the subagent to `~/.claude/agents/` so it's available in all your projects. Select **Generate with Claude**. When prompted, describe the subagent: ``` A code improvement agent that scans files and suggests improvements for readability, performance, and best practices. It should explain each issue, show the current code, and provide an improved version. ``` Claude generates the system prompt and configuration. Press `e` to open it in your editor if you want to customize it. For a read-only reviewer, deselect everything except **Read-only tools**. If you keep all tools selected, the subagent inherits all tools available to the main conversation. Choose which model the subagent uses. For this example agent, select **Sonnet**, which balances capability and speed for analyzing code patterns. Pick a background color for the subagent. This helps you identify which subagent is running in the UI. Save the subagent. It's available immediately (no restart needed). Try it: ``` Use the code-improver agent to suggest improvements in this project ``` Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions. You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements. You can also create subagents manually as Markdown files, define them via CLI flags, or distribute them through plugins. The following sections cover all configuration options. ## Configure subagents ### Use the /agents command The `/agents` command provides an interactive interface for managing subagents. Run `/agents` to: * View all available subagents (built-in, user, project, and plugin) * Create new subagents with guided setup or Claude generation * Edit existing subagent configuration and tool access * Delete custom subagents * See which subagents are active when duplicates exist This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly. ### Choose the subagent scope Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, the higher-priority location wins. | Location | Scope | Priority | How to create | | :--------------------------- | :---------------------- | :---------- | :------------------------------------ | | `--agents` CLI flag | Current session | 1 (highest) | Pass JSON when launching Claude Code | | `.claude/agents/` | Current project | 2 | Interactive or manual | | `~/.claude/agents/` | All your projects | 3 | Interactive or manual | | Plugin's `agents/` directory | Where plugin is enabled | 4 (lowest) | Installed with [plugins](/en/plugins) | **Project subagents** (`.claude/agents/`) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively. **User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects. **CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts: ```bash theme={null} claude --agents '{ "code-reviewer": { "description": "Expert code reviewer. Use proactively after code changes.", "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.", "tools": ["Read", "Grep", "Glob", "Bash"], "model": "sonnet" } }' ``` The `--agents` flag accepts JSON with the same fields as [frontmatter](#supported-frontmatter-fields). Use `prompt` for the system prompt (equivalent to the markdown body in file-based subagents). See the [CLI reference](/en/cli-reference#agents-flag-format) for the full JSON format. **Plugin subagents** come from [plugins](/en/plugins) you've installed. They appear in `/agents` alongside your custom subagents. See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin subagents. ### Write subagent files Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown: Subagents are loaded at session start. If you create a subagent by manually adding a file, restart your session or use `/agents` to load it immediately. ```markdown theme={null} --- name: code-reviewer description: Reviews code for quality and best practices tools: Read, Glob, Grep model: sonnet --- You are a code reviewer. When invoked, analyze the code and provide specific, actionable feedback on quality, security, and best practices. ``` The frontmatter defines the subagent's metadata and configuration. The body becomes the system prompt that guides the subagent's behavior. Subagents receive only this system prompt (plus basic environment details like working directory), not the full Claude Code system prompt. #### Supported frontmatter fields The following fields can be used in the YAML frontmatter. Only `name` and `description` are required. | Field | Required | Description | | :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | Yes | Unique identifier using lowercase letters and hyphens | | `description` | Yes | When Claude should delegate to this subagent | | `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted | | `disallowedTools` | No | Tools to deny, removed from inherited or specified list | | `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, or `inherit`. Defaults to `inherit` | | `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` | | `skills` | No | [Skills](/en/skills) to load into the subagent's context at startup. The full skill content is injected, not just made available for invocation. Subagents don't inherit skills from the parent conversation | | `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent | ### Choose a model The `model` field controls which [AI model](/en/model-config) the subagent uses: * **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku` * **inherit**: Use the same model as the main conversation * **Omitted**: If not specified, defaults to `inherit` (uses the same model as the main conversation) ### Control subagent capabilities You can control what subagents can do through tool access, permission modes, and conditional rules. #### Available tools Subagents can use any of Claude Code's [internal tools](/en/settings#tools-available-to-claude). By default, subagents inherit all tools from the main conversation, including MCP tools. To restrict tools, use the `tools` field (allowlist) or `disallowedTools` field (denylist): ```yaml theme={null} --- name: safe-researcher description: Research agent with restricted capabilities tools: Read, Grep, Glob, Bash disallowedTools: Write, Edit --- ``` #### Permission modes The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode. | Mode | Behavior | | :------------------ | :----------------------------------------------------------------- | | `default` | Standard permission checking with prompts | | `acceptEdits` | Auto-accept file edits | | `dontAsk` | Auto-deny permission prompts (explicitly allowed tools still work) | | `bypassPermissions` | Skip all permission checks | | `plan` | Plan mode (read-only exploration) | Use `bypassPermissions` with caution. It skips all permission checks, allowing the subagent to execute any operation without approval. If the parent uses `bypassPermissions`, this takes precedence and cannot be overridden. #### Preload skills into subagents Use the `skills` field to inject skill content into a subagent's context at startup. This gives the subagent domain knowledge without requiring it to discover and load skills during execution. ```yaml theme={null} --- name: api-developer description: Implement API endpoints following team conventions skills: - api-conventions - error-handling-patterns --- Implement API endpoints. Follow the conventions and patterns from the preloaded skills. ``` The full content of each skill is injected into the subagent's context, not just made available for invocation. Subagents don't inherit skills from the parent conversation; you must list them explicitly. This is the inverse of [running a skill in a subagent](/en/skills#run-skills-in-a-subagent). With `skills` in a subagent, the subagent controls the system prompt and loads skill content. With `context: fork` in a skill, the skill content is injected into the agent you specify. Both use the same underlying system. #### Conditional rules with hooks For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others. This example creates a subagent that only allows read-only database queries. The `PreToolUse` hook runs the script specified in `command` before each Bash command executes: ```yaml theme={null} --- name: db-reader description: Execute read-only database queries tools: Bash hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/validate-readonly-query.sh" --- ``` Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the Bash command, and [exits with code 2](/en/hooks#exit-code-2-behavior-per-event) to block write operations: ```bash theme={null} #!/bin/bash # ./scripts/validate-readonly-query.sh INPUT=$(cat) COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty') # Block SQL write operations (case-insensitive) if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then echo "Blocked: Only SELECT queries are allowed" >&2 exit 2 fi exit 0 ``` See [Hook input](/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/en/hooks#exit-code-output) for how exit codes affect behavior. #### Disable specific subagents You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](/en/settings#permission-settings). Use the format `Task(subagent-name)` where `subagent-name` matches the subagent's name field. ```json theme={null} { "permissions": { "deny": ["Task(Explore)", "Task(my-custom-agent)"] } } ``` This works for both built-in and custom subagents. You can also use the `--disallowedTools` CLI flag: ```bash theme={null} claude --disallowedTools "Task(Explore)" ``` See [Permissions documentation](/en/permissions#tool-specific-permission-rules) for more details on permission rules. ### Define hooks for subagents Subagents can define [hooks](/en/hooks) that run during the subagent's lifecycle. There are two ways to configure hooks: 1. **In the subagent's frontmatter**: Define hooks that run only while that subagent is active 2. **In `settings.json`**: Define hooks that run in the main session when subagents start or stop #### Hooks in subagent frontmatter Define hooks directly in the subagent's markdown file. These hooks only run while that specific subagent is active and are cleaned up when it finishes. All [hook events](/en/hooks#hook-events) are supported. The most common events for subagents are: | Event | Matcher input | When it fires | | :------------ | :------------ | :------------------------------------------------------------------ | | `PreToolUse` | Tool name | Before the subagent uses a tool | | `PostToolUse` | Tool name | After the subagent uses a tool | | `Stop` | (none) | When the subagent finishes (converted to `SubagentStop` at runtime) | This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`: ```yaml theme={null} --- name: code-reviewer description: Review code changes with automatic linting hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/validate-command.sh $TOOL_INPUT" PostToolUse: - matcher: "Edit|Write" hooks: - type: command command: "./scripts/run-linter.sh" --- ``` `Stop` hooks in frontmatter are automatically converted to `SubagentStop` events. #### Project-level hooks for subagent events Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session. | Event | Matcher input | When it fires | | :-------------- | :-------------- | :------------------------------- | | `SubagentStart` | Agent type name | When a subagent begins execution | | `SubagentStop` | (none) | When any subagent completes | `SubagentStart` supports matchers to target specific agent types by name. `SubagentStop` fires for all subagent completions regardless of matcher values. This example runs a setup script only when the `db-agent` subagent starts, and a cleanup script when any subagent stops: ```json theme={null} { "hooks": { "SubagentStart": [ { "matcher": "db-agent", "hooks": [ { "type": "command", "command": "./scripts/setup-db-connection.sh" } ] } ], "SubagentStop": [ { "hooks": [ { "type": "command", "command": "./scripts/cleanup-db-connection.sh" } ] } ] } } ``` See [Hooks](/en/hooks) for the complete hook configuration format. ## Work with subagents ### Understand automatic delegation Claude automatically delegates tasks based on the task description in your request, the `description` field in subagent configurations, and current context. To encourage proactive delegation, include phrases like "use proactively" in your subagent's description field. You can also request a specific subagent explicitly: ``` Use the test-runner subagent to fix failing tests Have the code-reviewer subagent look at my recent changes ``` ### Run subagents in foreground or background Subagents can run in the foreground (blocking) or background (concurrent): * **Foreground subagents** block the main conversation until complete. Permission prompts and clarifying questions (like [`AskUserQuestion`](/en/settings#tools-available-to-claude)) are passed through to you. * **Background subagents** run concurrently while you continue working. Before launching, Claude Code prompts for any tool permissions the subagent will need, ensuring it has the necessary approvals upfront. Once running, the subagent inherits these permissions and auto-denies anything not pre-approved. If a background subagent needs to ask clarifying questions, that tool call fails but the subagent continues. MCP tools are not available in background subagents. If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts. Claude decides whether to run subagents in the foreground or background based on the task. You can also: * Ask Claude to "run this in the background" * Press **Ctrl+B** to background a running task To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/settings#environment-variables). ### Common patterns #### Isolate high-volume operations One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context. By delegating these to a subagent, the verbose output stays in the subagent's context while only the relevant summary returns to your main conversation. ``` Use a subagent to run the test suite and report only the failing tests with their error messages ``` #### Run parallel research For independent investigations, spawn multiple subagents to work simultaneously: ``` Research the authentication, database, and API modules in parallel using separate subagents ``` Each subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths don't depend on each other. When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context. #### Chain subagents For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent. ``` Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them ``` ### Choose between subagents and main conversation Use the **main conversation** when: * The task needs frequent back-and-forth or iterative refinement * Multiple phases share significant context (planning → implementation → testing) * You're making a quick, targeted change * Latency matters. Subagents start fresh and may need time to gather context Use **subagents** when: * The task produces verbose output you don't need in your main context * You want to enforce specific tool restrictions or permissions * The work is self-contained and can return a summary Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context. Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation. ### Manage subagent context #### Resume subagents Each subagent invocation creates a new instance with fresh context. To continue an existing subagent's work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work: ``` Use the code-reviewer subagent to review the authentication module [Agent completes] Continue that code review and now analyze the authorization logic [Claude resumes the subagent with full context from previous conversation] ``` You can also ask Claude for the agent ID if you want to reference it explicitly, or find IDs in the transcript files at `~/.claude/projects/{project}/{sessionId}/subagents/`. Each transcript is stored as `agent-{agentId}.jsonl`. Subagent transcripts persist independently of the main conversation: * **Main conversation compaction**: When the main conversation compacts, subagent transcripts are unaffected. They're stored in separate files. * **Session persistence**: Subagent transcripts persist within their session. You can [resume a subagent](#resume-subagents) after restarting Claude Code by resuming the same session. * **Automatic cleanup**: Transcripts are cleaned up based on the `cleanupPeriodDays` setting (default: 30 days). #### Auto-compaction Subagents support automatic compaction using the same logic as the main conversation. By default, auto-compaction triggers at approximately 95% capacity. To trigger compaction earlier, set `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` to a lower percentage (for example, `50`). See [environment variables](/en/settings#environment-variables) for details. Compaction events are logged in subagent transcript files: ```json theme={null} { "type": "system", "subtype": "compact_boundary", "compactMetadata": { "trigger": "auto", "preTokens": 167189 } } ``` The `preTokens` value shows how many tokens were used before compaction occurred. ## Example subagents These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude. **Best practices:** * **Design focused subagents:** each subagent should excel at one specific task * **Write detailed descriptions:** Claude uses the description to decide when to delegate * **Limit tool access:** grant only necessary permissions for security and focus * **Check into version control:** share project subagents with your team ### Code reviewer A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access (no Edit or Write) and a detailed prompt that specifies exactly what to look for and how to format output. ```markdown theme={null} --- name: code-reviewer description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code. tools: Read, Grep, Glob, Bash model: inherit --- You are a senior code reviewer ensuring high standards of code quality and security. When invoked: 1. Run git diff to see recent changes 2. Focus on modified files 3. Begin review immediately Review checklist: - Code is clear and readable - Functions and variables are well-named - No duplicated code - Proper error handling - No exposed secrets or API keys - Input validation implemented - Good test coverage - Performance considerations addressed Provide feedback organized by priority: - Critical issues (must fix) - Warnings (should fix) - Suggestions (consider improving) Include specific examples of how to fix issues. ``` ### Debugger A subagent that can both analyze and fix issues. Unlike the code reviewer, this one includes Edit because fixing bugs requires modifying code. The prompt provides a clear workflow from diagnosis to verification. ```markdown theme={null} --- name: debugger description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues. tools: Read, Edit, Bash, Grep, Glob --- You are an expert debugger specializing in root cause analysis. When invoked: 1. Capture error message and stack trace 2. Identify reproduction steps 3. Isolate the failure location 4. Implement minimal fix 5. Verify solution works Debugging process: - Analyze error messages and logs - Check recent code changes - Form and test hypotheses - Add strategic debug logging - Inspect variable states For each issue, provide: - Root cause explanation - Evidence supporting the diagnosis - Specific code fix - Testing approach - Prevention recommendations Focus on fixing the underlying issue, not the symptoms. ``` ### Data scientist A domain-specific subagent for data analysis work. This example shows how to create subagents for specialized workflows outside of typical coding tasks. It explicitly sets `model: sonnet` for more capable analysis. ```markdown theme={null} --- name: data-scientist description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries. tools: Bash, Read, Write model: sonnet --- You are a data scientist specializing in SQL and BigQuery analysis. When invoked: 1. Understand the data analysis requirement 2. Write efficient SQL queries 3. Use BigQuery command line tools (bq) when appropriate 4. Analyze and summarize results 5. Present findings clearly Key practices: - Write optimized SQL queries with proper filters - Use appropriate aggregations and joins - Include comments explaining complex logic - Format results for readability - Provide data-driven recommendations For each analysis: - Explain the query approach - Document any assumptions - Highlight key findings - Suggest next steps based on data Always ensure queries are efficient and cost-effective. ``` ### Database query validator A subagent that allows Bash access but validates commands to permit only read-only SQL queries. This example shows how to use `PreToolUse` hooks for conditional validation when you need finer control than the `tools` field provides. ```markdown theme={null} --- name: db-reader description: Execute read-only database queries. Use when analyzing data or generating reports. tools: Bash hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/validate-readonly-query.sh" --- You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data. When asked to analyze data: 1. Identify which tables contain the relevant data 2. Write efficient SELECT queries with appropriate filters 3. Present results clearly with context You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access. ``` Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the command being executed, and checks it against a list of SQL write operations. If a write operation is detected, the script [exits with code 2](/en/hooks#exit-code-2-behavior-per-event) to block execution and returns an error message to Claude via stderr. Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration: ```bash theme={null} #!/bin/bash # Blocks SQL write operations, allows SELECT queries # Read JSON input from stdin INPUT=$(cat) # Extract the command field from tool_input using jq COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty') if [ -z "$COMMAND" ]; then exit 0 fi # Block write operations (case-insensitive) if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2 exit 2 fi exit 0 ``` Make the script executable: ```bash theme={null} chmod +x ./scripts/validate-readonly-query.sh ``` The hook receives JSON via stdin with the Bash command in `tool_input.command`. Exit code 2 blocks the operation and feeds the error message back to Claude. See [Hooks](/en/hooks#exit-code-output) for details on exit codes and [Hook input](/en/hooks#pretooluse-input) for the complete input schema. ## Next steps Now that you understand subagents, explore these related features: * [Distribute subagents with plugins](/en/plugins) to share subagents across teams or projects * [Run Claude Code programmatically](/en/headless) with the Agent SDK for CI/CD and automation * [Use MCP servers](/en/mcp) to give subagents access to external tools and data --- # Source: https://code.claude.com/docs/en/terminal-config.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Optimize your terminal setup > Claude Code works best when your terminal is properly configured. Follow these guidelines to optimize your experience. ### Themes and appearance Claude cannot control the theme of your terminal. That's handled by your terminal application. You can match Claude Code's theme to your terminal any time via the `/config` command. For additional customization of the Claude Code interface itself, you can configure a [custom status line](/en/statusline) to display contextual information like the current model, working directory, or git branch at the bottom of your terminal. ### Line breaks You have several options for entering line breaks into Claude Code: * **Quick escape**: Type `\` followed by Enter to create a newline * **Shift+Enter**: Works out of the box in iTerm2, WezTerm, Ghostty, and Kitty * **Keyboard shortcut**: Set up a keybinding to insert a newline in other terminals **Set up Shift+Enter for other terminals** Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter for VS Code, Alacritty, Zed, and Warp. The `/terminal-setup` command is only visible in terminals that require manual configuration. If you're using iTerm2, WezTerm, Ghostty, or Kitty, you won't see this command because Shift+Enter already works natively. **Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app)** **For Mac Terminal.app:** 1. Open Settings → Profiles → Keyboard 2. Check "Use Option as Meta Key" **For iTerm2 and VS Code terminal:** 1. Open Settings → Profiles → Keys 2. Under General, set Left/Right Option key to "Esc+" ### Notification setup Never miss when Claude completes a task with proper notification configuration: #### iTerm 2 system notifications For iTerm 2 alerts when tasks complete: 1. Open iTerm 2 Preferences 2. Navigate to Profiles → Terminal 3. Enable "Silence bell" and Filter Alerts → "Send escape sequence-generated alerts" 4. Set your preferred notification delay Note that these notifications are specific to iTerm 2 and not available in the default macOS Terminal. #### Custom notification hooks For advanced notification handling, you can create [notification hooks](/en/hooks#notification) to run your own logic. ### Handling large inputs When working with extensive code or long instructions: * **Avoid direct pasting**: Claude Code may struggle with very long pasted content * **Use file-based workflows**: Write content to a file and ask Claude to read it * **Be aware of VS Code limitations**: The VS Code terminal is particularly prone to truncating long pastes ### Vim Mode Claude Code supports a subset of Vim keybindings that can be enabled with `/vim` or configured via `/config`. The supported subset includes: * Mode switching: `Esc` (to NORMAL), `i`/`I`, `a`/`A`, `o`/`O` (to INSERT) * Navigation: `h`/`j`/`k`/`l`, `w`/`e`/`b`, `0`/`$`/`^`, `gg`/`G`, `f`/`F`/`t`/`T` with `;`/`,` repeat * Editing: `x`, `dw`/`de`/`db`/`dd`/`D`, `cw`/`ce`/`cb`/`cc`/`C`, `.` (repeat) * Yank/paste: `yy`/`Y`, `yw`/`ye`/`yb`, `p`/`P` * Text objects: `iw`/`aw`, `iW`/`aW`, `i"`/`a"`, `i'`/`a'`, `i(`/`a(`, `i[`/`a[`, `i{`/`a{` * Indentation: `>>`/`<<` * Line operations: `J` (join lines) See [Interactive mode](/en/interactive-mode#vim-editor-mode) for the complete reference. --- # Source: https://code.claude.com/docs/en/third-party-integrations.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Enterprise deployment overview > Learn how Claude Code can integrate with various third-party services and infrastructure to meet enterprise deployment requirements. Organizations can deploy Claude Code through Anthropic directly or through a cloud provider. This page helps you choose the right configuration. ## Compare deployment options For most organizations, Claude for Teams or Claude for Enterprise provides the best experience. Team members get access to both Claude Code and Claude on the web with a single subscription, centralized billing, and no infrastructure setup required. **Claude for Teams** is self-service and includes collaboration features, admin tools, and billing management. Best for smaller teams that need to get started quickly. **Claude for Enterprise** adds SSO and domain capture, role-based permissions, compliance API access, and managed policy settings for deploying organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements. Learn more about [Team plans](https://support.claude.com/en/articles/9266767-what-is-the-team-plan) and [Enterprise plans](https://support.claude.com/en/articles/9797531-what-is-the-enterprise-plan). If your organization has specific infrastructure requirements, compare the options below:
    Feature Claude for Teams/Enterprise Anthropic Console Amazon Bedrock Google Vertex AI Microsoft Foundry
    Best for Most organizations (recommended) Individual developers AWS-native deployments GCP-native deployments Azure-native deployments
    Billing Teams: \$150/seat (Premium) with PAYG available
    Enterprise: Contact Sales
    PAYG PAYG through AWS PAYG through GCP PAYG through Azure
    Regions Supported [countries](https://www.anthropic.com/supported-countries) Supported [countries](https://www.anthropic.com/supported-countries) Multiple AWS [regions](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) Multiple GCP [regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations) Multiple Azure [regions](https://azure.microsoft.com/en-us/explore/global-infrastructure/products-by-region/)
    Prompt caching Enabled by default Enabled by default Enabled by default Enabled by default Enabled by default
    Authentication Claude.ai SSO or email API key API key or AWS credentials GCP credentials API key or Microsoft Entra ID
    Cost tracking Usage dashboard Usage dashboard AWS Cost Explorer GCP Billing Azure Cost Management
    Includes Claude on web Yes No No No No
    Enterprise features Team management, SSO, usage monitoring None IAM policies, CloudTrail IAM roles, Cloud Audit Logs RBAC policies, Azure Monitor
    Select a deployment option to view setup instructions: * [Claude for Teams or Enterprise](/en/authentication#claude-for-teams-or-enterprise) * [Anthropic Console](/en/authentication#claude-console-authentication) * [Amazon Bedrock](/en/amazon-bedrock) * [Google Vertex AI](/en/google-vertex-ai) * [Microsoft Foundry](/en/microsoft-foundry) ## Configure proxies and gateways Most organizations can use a cloud provider directly without additional configuration. However, you may need to configure a corporate proxy or LLM gateway if your organization has specific network or management requirements. These are different configurations that can be used together: * **Corporate proxy**: Routes traffic through an HTTP/HTTPS proxy. Use this if your organization requires all outbound traffic to pass through a proxy server for security monitoring, compliance, or network policy enforcement. Configure with the `HTTPS_PROXY` or `HTTP_PROXY` environment variables. Learn more in [Enterprise network configuration](/en/network-config). * **LLM Gateway**: A service that sits between Claude Code and the cloud provider to handle authentication and routing. Use this if you need centralized usage tracking across teams, custom rate limiting or budgets, or centralized authentication management. Configure with the `ANTHROPIC_BASE_URL`, `ANTHROPIC_BEDROCK_BASE_URL`, or `ANTHROPIC_VERTEX_BASE_URL` environment variables. Learn more in [LLM gateway configuration](/en/llm-gateway). The following examples show the environment variables to set in your shell or shell profile (`.bashrc`, `.zshrc`). See [Settings](/en/settings) for other configuration methods. ### Amazon Bedrock Route Bedrock traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables): ```bash theme={null} # Enable Bedrock export CLAUDE_CODE_USE_BEDROCK=1 export AWS_REGION=us-east-1 # Configure corporate proxy export HTTPS_PROXY='https://proxy.example.com:8080' ``` Route Bedrock traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables): ```bash theme={null} # Enable Bedrock export CLAUDE_CODE_USE_BEDROCK=1 # Configure LLM gateway export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock' export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # If gateway handles AWS auth ``` ### Microsoft Foundry Route Foundry traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables): ```bash theme={null} # Enable Microsoft Foundry export CLAUDE_CODE_USE_FOUNDRY=1 export ANTHROPIC_FOUNDRY_RESOURCE=your-resource export ANTHROPIC_FOUNDRY_API_KEY=your-api-key # Or omit for Entra ID auth # Configure corporate proxy export HTTPS_PROXY='https://proxy.example.com:8080' ``` Route Foundry traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables): ```bash theme={null} # Enable Microsoft Foundry export CLAUDE_CODE_USE_FOUNDRY=1 # Configure LLM gateway export ANTHROPIC_FOUNDRY_BASE_URL='https://your-llm-gateway.com' export CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1 # If gateway handles Azure auth ``` ### Google Vertex AI Route Vertex AI traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables): ```bash theme={null} # Enable Vertex export CLAUDE_CODE_USE_VERTEX=1 export CLOUD_ML_REGION=us-east5 export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id # Configure corporate proxy export HTTPS_PROXY='https://proxy.example.com:8080' ``` Route Vertex AI traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables): ```bash theme={null} # Enable Vertex export CLAUDE_CODE_USE_VERTEX=1 # Configure LLM gateway export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex' export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # If gateway handles GCP auth ``` Use `/status` in Claude Code to verify your proxy and gateway configuration is applied correctly. ## Best practices for organizations ### Invest in documentation and memory We strongly recommend investing in documentation so that Claude Code understands your codebase. Organizations can deploy CLAUDE.md files at multiple levels: * **Organization-wide**: Deploy to system directories like `/Library/Application Support/ClaudeCode/CLAUDE.md` (macOS) for company-wide standards * **Repository-level**: Create `CLAUDE.md` files in repository roots containing project architecture, build commands, and contribution guidelines. Check these into source control so all users benefit Learn more in [Memory and CLAUDE.md files](/en/memory). ### Simplify deployment If you have a custom development environment, we find that creating a "one click" way to install Claude Code is key to growing adoption across an organization. ### Start with guided usage Encourage new users to try Claude Code for codebase Q\&A, or on smaller bug fixes or feature requests. Ask Claude Code to make a plan. Check Claude's suggestions and give feedback if it's off-track. Over time, as users understand this new paradigm better, then they'll be more effective at letting Claude Code run more agentically. ### Configure security policies Security teams can configure managed permissions for what Claude Code is and is not allowed to do, which cannot be overwritten by local configuration. [Learn more](/en/security). ### Leverage MCP for integrations MCP is a great way to give Claude Code more information, such as connecting to ticket management systems or error logs. We recommend that one central team configures MCP servers and checks a `.mcp.json` configuration into the codebase so that all users benefit. [Learn more](/en/mcp). At Anthropic, we trust Claude Code to power development across every Anthropic codebase. We hope you enjoy using Claude Code as much as we do. ## Next steps Once you've chosen a deployment option and configured access for your team: 1. **Roll out to your team**: Share installation instructions and have team members [install Claude Code](/en/setup) and authenticate with their credentials. 2. **Set up shared configuration**: Create a [CLAUDE.md file](/en/memory) in your repositories to help Claude Code understand your codebase and coding standards. 3. **Configure permissions**: Review [security settings](/en/security) to define what Claude Code can and cannot do in your environment. --- # Source: https://code.claude.com/docs/en/troubleshooting.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Troubleshooting > Discover solutions to common issues with Claude Code installation and usage. ## Common installation issues ### Windows installation issues: errors in WSL You might encounter the following issues in WSL: **OS/platform detection issues**: If you receive an error during installation, WSL may be using Windows `npm`. Try: * Run `npm config set os linux` before installation * Install with `npm install -g @anthropic-ai/claude-code --force --no-os-check` (Do NOT use `sudo`) **Node not found errors**: If you see `exec: node: not found` when running `claude`, your WSL environment may be using a Windows installation of Node.js. You can confirm this with `which npm` and `which node`, which should point to Linux paths starting with `/usr/` rather than `/mnt/c/`. To fix this, try installing Node via your Linux distribution's package manager or via [`nvm`](https://github.com/nvm-sh/nvm). **nvm version conflicts**: If you have nvm installed in both WSL and Windows, you may experience version conflicts when switching Node versions in WSL. This happens because WSL imports the Windows PATH by default, causing Windows nvm/npm to take priority over the WSL installation. You can identify this issue by: * Running `which npm` and `which node` - if they point to Windows paths (starting with `/mnt/c/`), Windows versions are being used * Experiencing broken functionality after switching Node versions with nvm in WSL To resolve this issue, fix your Linux PATH to ensure the Linux node/npm versions take priority: **Primary solution: Ensure nvm is properly loaded in your shell** The most common cause is that nvm isn't loaded in non-interactive shells. Add the following to your shell configuration file (`~/.bashrc`, `~/.zshrc`, etc.): ```bash theme={null} # Load nvm if it exists export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" ``` Or run directly in your current session: ```bash theme={null} source ~/.nvm/nvm.sh ``` **Alternative: Adjust PATH order** If nvm is properly loaded but Windows paths still take priority, you can explicitly prepend your Linux paths to PATH in your shell configuration: ```bash theme={null} export PATH="$HOME/.nvm/versions/node/$(node -v)/bin:$PATH" ``` Avoid disabling Windows PATH importing (`appendWindowsPath = false`) as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development. ### WSL2 sandbox setup [Sandboxing](/en/sandboxing) is supported on WSL2 but requires installing additional packages. If you see an error like "Sandbox requires socat and bubblewrap" when running `/sandbox`, install the dependencies: ```bash theme={null} sudo apt-get install bubblewrap socat ``` ```bash theme={null} sudo dnf install bubblewrap socat ``` WSL1 does not support sandboxing. If you see "Sandboxing requires WSL2", you need to upgrade to WSL2 or run Claude Code without sandboxing. ### Linux and Mac installation issues: permission or command not found errors When installing Claude Code with npm, `PATH` problems may prevent access to `claude`. You may also encounter permission errors if your npm global prefix is not user writable (for example, `/usr`, or `/usr/local`). #### Recommended solution: Native Claude Code installation Claude Code has a native installation that doesn't depend on npm or Node.js. Use the following command to run the native installer. **macOS, Linux, WSL:** ```bash theme={null} # Install stable version (default) curl -fsSL https://claude.ai/install.sh | bash # Install latest version curl -fsSL https://claude.ai/install.sh | bash -s latest # Install specific version number curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58 ``` **Windows PowerShell:** ```powershell theme={null} # Install stable version (default) irm https://claude.ai/install.ps1 | iex # Install latest version & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest # Install specific version number & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58 ``` This command installs the appropriate build of Claude Code for your operating system and architecture and adds a symlink to the installation at `~/.local/bin/claude` (or `%USERPROFILE%\.local\bin\claude.exe` on Windows). Make sure that you have the installation directory in your system PATH. ### Windows: "Claude Code on Windows requires git-bash" Claude Code on native Windows requires [Git for Windows](https://git-scm.com/downloads/win) which includes Git Bash. If Git is installed but not detected: 1. Set the path explicitly in PowerShell before running Claude: ```powershell theme={null} $env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe" ``` 2. Or add it to your system environment variables permanently through System Properties → Environment Variables. If Git is installed in a non-standard location, adjust the path accordingly. ### Windows: "installMethod is native, but claude command not found" If you see this error after installation, the `claude` command isn't in your PATH. Add it manually: Press `Win + R`, type `sysdm.cpl`, and press Enter. Click **Advanced** → **Environment Variables**. Under "User variables", select **Path** and click **Edit**. Click **New** and add: ``` %USERPROFILE%\.local\bin ``` Close and reopen PowerShell or CMD for changes to take effect. Verify installation: ```bash theme={null} claude doctor # Check installation health ``` ## Permissions and authentication ### Repeated permission prompts If you find yourself repeatedly approving the same commands, you can allow specific tools to run without approval using the `/permissions` command. See [Permissions docs](/en/permissions#manage-permissions). ### Authentication issues If you're experiencing authentication problems: 1. Run `/logout` to sign out completely 2. Close Claude Code 3. Restart with `claude` and complete the authentication process again If the browser doesn't open automatically during login, press `c` to copy the OAuth URL to your clipboard, then paste it into your browser manually. If problems persist, try: ```bash theme={null} rm -rf ~/.config/claude-code/auth.json claude ``` This removes your stored authentication information and forces a clean login. ## Configuration file locations Claude Code stores configuration in several locations: | File | Purpose | | :---------------------------- | :------------------------------------------------------- | | `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) | | `.claude/settings.json` | Project settings (checked into source control) | | `.claude/settings.local.json` | Local project settings (not committed) | | `~/.claude.json` | Global state (theme, OAuth, MCP servers) | | `.mcp.json` | Project MCP servers (checked into source control) | | `managed-settings.json` | [Managed settings](/en/settings#settings-files) | | `managed-mcp.json` | [Managed MCP servers](/en/mcp#managed-mcp-configuration) | On Windows, `~` refers to your user home directory, such as `C:\Users\YourName`. **Managed file locations:** * macOS: `/Library/Application Support/ClaudeCode/` * Linux/WSL: `/etc/claude-code/` * Windows: `C:\Program Files\ClaudeCode\` For details on configuring these files, see [Settings](/en/settings) and [MCP](/en/mcp). ### Resetting configuration To reset Claude Code to default settings, you can remove the configuration files: ```bash theme={null} # Reset all user settings and state rm ~/.claude.json rm -rf ~/.claude/ # Reset project-specific settings rm -rf .claude/ rm .mcp.json ``` This will remove all your settings, MCP server configurations, and session history. ## Performance and stability ### High CPU or memory usage Claude Code is designed to work with most development environments, but may consume significant resources when processing large codebases. If you're experiencing performance issues: 1. Use `/compact` regularly to reduce context size 2. Close and restart Claude Code between major tasks 3. Consider adding large build directories to your `.gitignore` file ### Command hangs or freezes If Claude Code seems unresponsive: 1. Press Ctrl+C to attempt to cancel the current operation 2. If unresponsive, you may need to close the terminal and restart ### Search and discovery issues If Search tool, `@file` mentions, custom agents, and custom skills aren't working, install system `ripgrep`: ```bash theme={null} # macOS (Homebrew) brew install ripgrep # Windows (winget) winget install BurntSushi.ripgrep.MSVC # Ubuntu/Debian sudo apt install ripgrep # Alpine Linux apk add ripgrep # Arch Linux pacman -S ripgrep ``` Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/settings#environment-variables). ### Slow or incomplete search results on WSL Disk read performance penalties when [working across file systems on WSL](https://learn.microsoft.com/en-us/windows/wsl/filesystems) may result in fewer-than-expected matches (but not a complete lack of search functionality) when using Claude Code on WSL. `/doctor` will show Search as OK in this case. **Solutions:** 1. **Submit more specific searches**: Reduce the number of files searched by specifying directories or file types: "Search for JWT validation logic in the auth-service package" or "Find use of md5 hash in JS files". 2. **Move project to Linux filesystem**: If possible, ensure your project is located on the Linux filesystem (`/home/`) rather than the Windows filesystem (`/mnt/c/`). 3. **Use native Windows instead**: Consider running Claude Code natively on Windows instead of through WSL, for better file system performance. ## IDE integration issues ### JetBrains IDE not detected on WSL2 If you're using Claude Code on WSL2 with JetBrains IDEs and getting "No available IDEs detected" errors, this is likely due to WSL2's networking configuration or Windows Firewall blocking the connection. #### WSL2 networking modes WSL2 uses NAT networking by default, which can prevent IDE detection. You have two options: **Option 1: Configure Windows Firewall** (recommended) 1. Find your WSL2 IP address: ```bash theme={null} wsl hostname -I # Example output: 172.21.123.456 ``` 2. Open PowerShell as Administrator and create a firewall rule: ```powershell theme={null} New-NetFirewallRule -DisplayName "Allow WSL2 Internal Traffic" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16 -LocalAddress 172.21.0.0/16 ``` (Adjust the IP range based on your WSL2 subnet from step 1) 3. Restart both your IDE and Claude Code **Option 2: Switch to mirrored networking** Add to `.wslconfig` in your Windows user directory: ```ini theme={null} [wsl2] networkingMode=mirrored ``` Then restart WSL with `wsl --shutdown` from PowerShell. These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations. For additional JetBrains configuration tips, see our [JetBrains IDE guide](/en/jetbrains#plugin-settings). ### Reporting Windows IDE integration issues (both native and WSL) If you're experiencing IDE integration problems on Windows, [create an issue](https://github.com/anthropics/claude-code/issues) with the following information: * Environment type: native Windows (Git Bash) or WSL1/WSL2 * WSL networking mode (if applicable): NAT or mirrored * IDE name and version * Claude Code extension/plugin version * Shell type: Bash, Zsh, PowerShell, etc. ### Escape key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals If you're using Claude Code in JetBrains terminals and the `Esc` key doesn't interrupt the agent as expected, this is likely due to a keybinding clash with JetBrains' default shortcuts. To fix this issue: 1. Go to Settings → Tools → Terminal 2. Either: * Uncheck "Move focus to the editor with Escape", or * Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut 3. Apply the changes This allows the `Esc` key to properly interrupt Claude Code operations. ## Markdown formatting issues Claude Code sometimes generates markdown files with missing language tags on code fences, which can affect syntax highlighting and readability in GitHub, editors, and documentation tools. ### Missing language tags in code blocks If you notice code blocks like this in generated markdown: ````markdown theme={null} ``` function example() { return "hello"; } ``` ```` Instead of properly tagged blocks like: ````markdown theme={null} ```javascript function example() { return "hello"; } ``` ```` **Solutions:** 1. **Ask Claude to add language tags**: Request "Add appropriate language tags to all code blocks in this markdown file." 2. **Use post-processing hooks**: Set up automatic formatting hooks to detect and add missing language tags. See [Auto-format code after edits](/en/hooks-guide#auto-format-code-after-edits) for an example of a PostToolUse formatting hook. 3. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed. ### Inconsistent spacing and formatting If generated markdown has excessive blank lines or inconsistent spacing: **Solutions:** 1. **Request formatting corrections**: Ask Claude to "Fix spacing and formatting issues in this markdown file." 2. **Use formatting tools**: Set up hooks to run markdown formatters like `prettier` or custom formatting scripts on generated markdown files. 3. **Specify formatting preferences**: Include formatting requirements in your prompts or project [memory](/en/memory) files. ### Best practices for markdown generation To minimize formatting issues: * **Be explicit in requests**: Ask for "properly formatted markdown with language-tagged code blocks" * **Use project conventions**: Document your preferred markdown style in [`CLAUDE.md`](/en/memory) * **Set up validation hooks**: Use post-processing hooks to automatically verify and fix common formatting issues ## Getting more help If you're experiencing issues not covered here: 1. Use the `/bug` command within Claude Code to report problems directly to Anthropic 2. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues 3. Run `/doctor` to diagnose issues. It checks: * Installation type, version, and search functionality * Auto-update status and available versions * Invalid settings files (malformed JSON, incorrect types) * MCP server configuration errors * Keybinding configuration problems * Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules) * Plugin and agent loading errors 4. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation --- # Source: https://code.claude.com/docs/en/vs-code.md > ## Documentation Index > Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt > Use this file to discover all available pages before exploring further. # Use Claude Code in VS Code > Install and configure the Claude Code extension for VS Code. Get AI coding assistance with inline diffs, @-mentions, plan review, and keyboard shortcuts. VS Code editor with the Claude Code extension panel open on the right side, showing a conversation with Claude The VS Code extension provides a native graphical interface for Claude Code, integrated directly into your IDE. This is the recommended way to use Claude Code in VS Code. With the extension, you can review and edit Claude's plans before accepting them, auto-accept edits as they're made, @-mention files with specific line ranges from your selection, access conversation history, and open multiple conversations in separate tabs or windows. ## Prerequisites * VS Code 1.98.0 or higher * An Anthropic account (you'll sign in when you first open the extension). If you're using a third-party provider like Amazon Bedrock or Google Vertex AI, see [Use third-party providers](#use-third-party-providers) instead. The extension includes the CLI (command-line interface), which you can access from VS Code's integrated terminal for advanced features. See [VS Code extension vs. Claude Code CLI](#vs-code-extension-vs-claude-code-cli) for details. ## Install the extension Click the link for your IDE to install directly: * [Install for VS Code](vscode:extension/anthropic.claude-code) * [Install for Cursor](cursor:extension/anthropic.claude-code) Or in VS Code, press `Cmd+Shift+X` (Mac) or `Ctrl+Shift+X` (Windows/Linux) to open the Extensions view, search for "Claude Code", and click **Install**. If the extension doesn't appear after installation, restart VS Code or run "Developer: Reload Window" from the Command Palette. ## Get started Once installed, you can start using Claude Code through the VS Code interface: Throughout VS Code, the Spark icon indicates Claude Code: Spark icon The quickest way to open Claude is to click the Spark icon in the **Editor Toolbar** (top-right corner of the editor). The icon only appears when you have a file open. VS Code editor showing the Spark icon in the Editor Toolbar Other ways to open Claude Code: * **Command Palette**: `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux), type "Claude Code", and select an option like "Open in New Tab" * **Status Bar**: Click **✱ Claude Code** in the bottom-right corner of the window. This works even when no file is open. When you first open the panel, a **Learn Claude Code** checklist appears. Work through each item by clicking **Show me**, or dismiss it with the X. To reopen it later, uncheck **Hide Onboarding** in VS Code settings under Extensions → Claude Code. You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details. Ask Claude to help with your code or files, whether that's explaining how something works, debugging an issue, or making changes. Claude automatically sees your selected text. Press `Option+K` (Mac) / `Alt+K` (Windows/Linux) to also insert an @-mention reference (like `@file.ts#5-10`) into your prompt. Here's an example of asking about a particular line in a file: VS Code editor with lines 2-3 selected in a Python file, and the Claude Code panel showing a question about those lines with an @-mention reference When Claude wants to edit a file, it shows a side-by-side comparison of the original and proposed changes, then asks for permission. You can accept, reject, or tell Claude what to do instead. VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit For more ideas on what you can do with Claude Code, see [Common workflows](/en/common-workflows). Run "Claude Code: Open Walkthrough" from the Command Palette for a guided tour of the basics. ## Use the prompt box The prompt box supports several features: * **Permission modes**: Click the mode indicator at the bottom of the prompt box to switch modes. In normal mode, Claude asks permission before each action. In Plan mode, Claude describes what it will do and waits for approval before making changes. In auto-accept mode, Claude makes edits without asking. Set the default in VS Code settings under `claudeCode.initialPermissionMode`. * **Command menu**: Click `/` or type `/` to open the command menu. Options include attaching files, switching models, toggling extended thinking, and viewing plan usage (`/usage`). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal. * **Context indicator**: The prompt box shows how much of Claude's context window you're using. Claude automatically compacts when needed, or you can run `/compact` manually. * **Extended thinking**: Lets Claude spend more time reasoning through complex problems. Toggle it on via the command menu (`/`). See [Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) for details. * **Multi-line input**: Press `Shift+Enter` to add a new line without sending. ### Reference files and folders Use @-mentions to give Claude context about specific files or folders. When you type `@` followed by a file or folder name, Claude reads that content and can answer questions about it or make changes to it. Claude Code supports fuzzy matching, so you can type partial names to find what you need: ``` > Explain the logic in @auth (fuzzy matches auth.js, AuthService.ts, etc.) > What's in @src/components/ (include a trailing slash for folders) ``` When you select text in the editor, Claude can see your highlighted code automatically. The prompt box footer shows how many lines are selected. Press `Option+K` (Mac) / `Alt+K` (Windows/Linux) to insert an @-mention with the file path and line numbers (e.g., `@app.ts#5-10`). Click the selection indicator to toggle whether Claude can see your highlighted text - the eye-slash icon means the selection is hidden from Claude. You can also hold `Shift` while dragging files into the prompt box to add them as attachments. Click the X on any attachment to remove it from context. ### Resume past conversations Click the dropdown at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time (Today, Yesterday, Last 7 days, etc.). Click any conversation to resume it with the full message history. For more on resuming sessions, see [Common workflows](/en/common-workflows#resume-previous-conversations). ### Resume remote sessions from Claude.ai If you use [Claude Code on the web](/en/claude-code-on-the-web), you can resume those remote sessions directly in VS Code. This requires signing in with **Claude.ai Subscription**, not Anthropic Console. Click the **Past Conversations** dropdown at the top of the Claude Code panel. The dialog shows two tabs: Local and Remote. Click **Remote** to see sessions from claude.ai. Browse or search your remote sessions. Click any session to download it and continue the conversation locally. Only web sessions started with a GitHub repository appear in the Remote tab. Resuming loads the conversation history locally; changes are not synced back to claude.ai. ## Customize your workflow Once you're up and running, you can reposition the Claude panel, run multiple sessions, or switch to terminal mode. ### Choose where Claude lives You can drag the Claude panel to reposition it anywhere in VS Code. Grab the panel's tab or title bar and drag it to: * **Secondary sidebar**: The right side of the window. Keeps Claude visible while you code. * **Primary sidebar**: The left sidebar with icons for Explorer, Search, etc. * **Editor area**: Opens Claude as a tab alongside your files. Useful for side tasks. Use the sidebar for your main Claude session and open additional tabs for side tasks. Claude remembers your preferred location. Note that the Spark icon only appears in the Activity Bar when the Claude panel is docked to the left. Since Claude defaults to the right side, use the Editor Toolbar icon to open Claude. ### Run multiple conversations Use **Open in New Tab** or **Open in New Window** from the Command Palette to start additional conversations. Each conversation maintains its own history and context, allowing you to work on different tasks in parallel. When using tabs, a small colored dot on the spark icon indicates status: blue means a permission request is pending, orange means Claude finished while the tab was hidden. ### Switch to terminal mode By default, the extension opens a graphical chat panel. If you prefer the CLI-style interface, open the [Use Terminal setting](vscode://settings/claudeCode.useTerminal) and check the box. You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), go to Extensions → Claude Code, and check **Use Terminal**. ## Manage plugins The VS Code extension includes a graphical interface for installing and managing [plugins](/en/plugins). Type `/plugins` in the prompt box to open the **Manage plugins** interface. ### Install plugins The plugin dialog shows two tabs: **Plugins** and **Marketplaces**. In the Plugins tab: * **Installed plugins** appear at the top with toggle switches to enable or disable them * **Available plugins** from your configured marketplaces appear below * Search to filter plugins by name or description * Click **Install** on any available plugin When you install a plugin, choose the installation scope: * **Install for you**: Available in all your projects (user scope) * **Install for this project**: Shared with project collaborators (project scope) * **Install locally**: Only for you, only in this repository (local scope) ### Manage marketplaces Switch to the **Marketplaces** tab to add or remove plugin sources: * Enter a GitHub repo, URL, or local path to add a new marketplace * Click the refresh icon to update a marketplace's plugin list * Click the trash icon to remove a marketplace After making changes, a banner prompts you to restart Claude Code to apply the updates. Plugin management in VS Code uses the same CLI commands under the hood. Plugins and marketplaces you configure in the extension are also available in the CLI, and vice versa. For more about the plugin system, see [Plugins](/en/plugins) and [Plugin marketplaces](/en/plugin-marketplaces). ## VS Code commands and shortcuts Open the Command Palette (`Cmd+Shift+P` on Mac or `Ctrl+Shift+P` on Windows/Linux) and type "Claude Code" to see all available VS Code commands for the Claude Code extension. Some shortcuts depend on which panel is "focused" (receiving keyboard input). When your cursor is in a code file, the editor is focused. When your cursor is in Claude's prompt box, Claude is focused. Use `Cmd+Esc` / `Ctrl+Esc` to toggle between them. These are VS Code commands for controlling the extension. Not all built-in Claude Code commands are available in the extension. See [VS Code extension vs. Claude Code CLI](#vs-code-extension-vs-claude-code-cli) for details. | Command | Shortcut | Description | | -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------ | | Focus Input | `Cmd+Esc` (Mac) / `Ctrl+Esc` (Windows/Linux) | Toggle focus between editor and Claude | | Open in Side Bar | - | Open Claude in the left sidebar | | Open in Terminal | - | Open Claude in terminal mode | | Open in New Tab | `Cmd+Shift+Esc` (Mac) / `Ctrl+Shift+Esc` (Windows/Linux) | Open a new conversation as an editor tab | | Open in New Window | - | Open a new conversation in a separate window | | New Conversation | `Cmd+N` (Mac) / `Ctrl+N` (Windows/Linux) | Start a new conversation (requires Claude to be focused) | | Insert @-Mention Reference | `Option+K` (Mac) / `Alt+K` (Windows/Linux) | Insert a reference to the current file and selection (requires editor to be focused) | | Show Logs | - | View extension debug logs | | Logout | - | Sign out of your Anthropic account | ## Configure settings The extension has two types of settings: * **Extension settings** in VS Code: Control the extension's behavior within VS Code. Open with `Cmd+,` (Mac) or `Ctrl+,` (Windows/Linux), then go to Extensions → Claude Code. You can also type `/` and select **General Config** to open settings. * **Claude Code settings** in `~/.claude/settings.json`: Shared between the extension and CLI. Use for allowed commands, environment variables, hooks, and MCP servers. See [Settings](/en/settings) for details. Add `"$schema": "https://json.schemastore.org/claude-code-settings.json"` to your `settings.json` to get autocomplete and inline validation for all available settings directly in VS Code. ### Extension settings | Setting | Default | Description | | --------------------------------- | --------- | ----------------------------------------------------------------------------------------------------- | | `selectedModel` | `default` | Model for new conversations. Change per-session with `/model`. | | `useTerminal` | `false` | Launch Claude in terminal mode instead of graphical panel | | `initialPermissionMode` | `default` | Controls approval prompts: `default` (ask each time), `plan`, `acceptEdits`, or `bypassPermissions` | | `preferredLocation` | `panel` | Where Claude opens: `sidebar` (right) or `panel` (new tab) | | `autosave` | `true` | Auto-save files before Claude reads or writes them | | `useCtrlEnterToSend` | `false` | Use Ctrl/Cmd+Enter instead of Enter to send prompts | | `enableNewConversationShortcut` | `true` | Enable Cmd/Ctrl+N to start a new conversation | | `hideOnboarding` | `false` | Hide the onboarding checklist (graduation cap icon) | | `respectGitIgnore` | `true` | Exclude .gitignore patterns from file searches | | `environmentVariables` | `[]` | Set environment variables for the Claude process. Use Claude Code settings instead for shared config. | | `disableLoginPrompt` | `false` | Skip authentication prompts (for third-party provider setups) | | `allowDangerouslySkipPermissions` | `false` | Bypass all permission prompts. **Use with extreme caution.** | | `claudeProcessWrapper` | - | Executable path used to launch the Claude process | ## VS Code extension vs. Claude Code CLI Claude Code is available as both a VS Code extension (graphical panel) and a CLI (command-line interface in the terminal). Some features are only available in the CLI. If you need a CLI-only feature, run `claude` in VS Code's integrated terminal. | Feature | CLI | VS Code Extension | | ------------------- | --------------------------------------------- | ---------------------------------------- | | Commands and skills | [All](/en/interactive-mode#built-in-commands) | Subset (type `/` to see available) | | MCP server config | Yes | No (configure via CLI, use in extension) | | Checkpoints | Yes | Yes | | `!` bash shortcut | Yes | No | | Tab completion | Yes | No | ### Rewind with checkpoints The VS Code extension supports checkpoints, which track Claude's file edits and let you rewind to a previous state. Hover over any message to reveal the rewind button, then choose from three options: * **Fork conversation from here**: start a new conversation branch from this message while keeping all code changes intact * **Rewind code to here**: revert file changes back to this point in the conversation while keeping the full conversation history * **Fork conversation and rewind code**: start a new conversation branch and revert file changes to this point For full details on how checkpoints work and their limitations, see [Checkpointing](/en/checkpointing). ### Run CLI in VS Code To use the CLI while staying in VS Code, open the integrated terminal (`` Ctrl+` `` on Windows/Linux or `` Cmd+` `` on Mac) and run `claude`. The CLI automatically integrates with your IDE for features like diff viewing and diagnostic sharing. If using an external terminal, run `/ide` inside Claude Code to connect it to VS Code. ### Switch between extension and CLI The extension and CLI share the same conversation history. To continue an extension conversation in the CLI, run `claude --resume` in the terminal. This opens an interactive picker where you can search for and select your conversation. ### Include terminal output in prompts Reference terminal output in your prompts using `@terminal:name` where `name` is the terminal's title. This lets Claude see command output, error messages, or logs without copy-pasting. ### Monitor background processes When Claude runs long-running commands, the extension shows progress in the status bar. However, visibility for background tasks is limited compared to the CLI. For better visibility, have Claude output the command so you can run it in VS Code's integrated terminal. ### Connect to external tools with MCP MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs. Configure them via CLI, then use them in both extension and CLI. To add an MCP server, open the integrated terminal (`` Ctrl+` `` or `` Cmd+` ``) and run: ```bash theme={null} claude mcp add --transport http github https://api.githubcopilot.com/mcp/ ``` Once configured, ask Claude to use the tools (e.g., "Review PR #456"). Some servers require authentication: run `claude` in the terminal, then type `/mcp` to authenticate. See the [MCP documentation](/en/mcp) for available servers. ## Work with git Claude Code integrates with git to help with version control workflows directly in VS Code. Ask Claude to commit changes, create pull requests, or work across branches. ### Create commits and pull requests Claude can stage changes, write commit messages, and create pull requests based on your work: ``` > commit my changes with a descriptive message > create a pr for this feature > summarize the changes I've made to the auth module ``` When creating pull requests, Claude generates descriptions based on the actual code changes and can add context about testing or implementation decisions. ### Use git worktrees for parallel tasks Git worktrees allow multiple Claude Code sessions to work on separate branches simultaneously, each with isolated files: ```bash theme={null} # Create a worktree for a new feature git worktree add ../project-feature-a -b feature-a # Run Claude Code in each worktree cd ../project-feature-a && claude ``` Each worktree maintains independent file state while sharing git history. This prevents Claude instances from interfering with each other when working on different tasks. For detailed git workflows including PR reviews and branch management, see [Common workflows](/en/common-workflows#create-pull-requests). ## Use third-party providers By default, Claude Code connects directly to Anthropic's API. If your organization uses Amazon Bedrock, Google Vertex AI, or Microsoft Foundry to access Claude, configure the extension to use your provider instead: Open the [Disable Login Prompt setting](vscode://settings/claudeCode.disableLoginPrompt) and check the box. You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), search for "Claude Code login", and check **Disable Login Prompt**. Follow the setup guide for your provider: * [Claude Code on Amazon Bedrock](/en/amazon-bedrock) * [Claude Code on Google Vertex AI](/en/google-vertex-ai) * [Claude Code on Microsoft Foundry](/en/microsoft-foundry) These guides cover configuring your provider in `~/.claude/settings.json`, which ensures your settings are shared between the VS Code extension and the CLI. ## Security and privacy Your code stays private. Claude Code processes your code to provide assistance but does not use it to train models. For details on data handling and how to opt out of logging, see [Data and privacy](/en/data-usage). With auto-edit permissions enabled, Claude Code can modify VS Code configuration files (like `settings.json` or `tasks.json`) that VS Code may execute automatically. To reduce risk when working with untrusted code: * Enable [VS Code Restricted Mode](https://code.visualstudio.com/docs/editor/workspace-trust#_restricted-mode) for untrusted workspaces * Use manual approval mode instead of auto-accept for edits * Review changes carefully before accepting them ## Fix common issues ### Extension won't install * Ensure you have a compatible version of VS Code (1.98.0 or later) * Check that VS Code has permission to install extensions * Try installing directly from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code) ### Spark icon not visible The Spark icon appears in the **Editor Toolbar** (top-right of editor) when you have a file open. If you don't see it: 1. **Open a file**: The icon requires a file to be open. Having just a folder open isn't enough. 2. **Check VS Code version**: Requires 1.98.0 or higher (Help → About) 3. **Restart VS Code**: Run "Developer: Reload Window" from the Command Palette 4. **Disable conflicting extensions**: Temporarily disable other AI extensions (Cline, Continue, etc.) 5. **Check workspace trust**: The extension doesn't work in Restricted Mode Alternatively, click "✱ Claude Code" in the **Status Bar** (bottom-right corner). This works even without a file open. You can also use the **Command Palette** (`Cmd+Shift+P` / `Ctrl+Shift+P`) and type "Claude Code". ### Claude Code never responds If Claude Code isn't responding to your prompts: 1. **Check your internet connection**: Ensure you have a stable internet connection 2. **Start a new conversation**: Try starting a fresh conversation to see if the issue persists 3. **Try the CLI**: Run `claude` from the terminal to see if you get more detailed error messages If problems persist, [file an issue on GitHub](https://github.com/anthropics/claude-code/issues) with details about the error. ## Uninstall the extension To uninstall the Claude Code extension: 1. Open the Extensions view (`Cmd+Shift+X` on Mac or `Ctrl+Shift+X` on Windows/Linux) 2. Search for "Claude Code" 3. Click **Uninstall** To also remove extension data and reset all settings: ```bash theme={null} rm -rf ~/.vscode/globalStorage/anthropic.claude-code ``` For additional help, see the [troubleshooting guide](/en/troubleshooting). ## Next steps Now that you have Claude Code set up in VS Code: * [Explore common workflows](/en/common-workflows) to get the most out of Claude Code * [Set up MCP servers](/en/mcp) to extend Claude's capabilities with external tools. Configure servers using the CLI, then use them in the extension. * [Configure Claude Code settings](/en/settings) to customize allowed commands, hooks, and more. These settings are shared between the extension and CLI.