From 60fe70f8f17522e9094b561528b89ed88a0c5b64 Mon Sep 17 00:00:00 2001 From: Chris Vaillancourt Date: Tue, 9 Dec 2025 09:23:25 -0800 Subject: [PATCH 1/7] fix(update_docs): update URLs for code.claude.com domain - Update LLMS_TXT_URL from docs.claude.com to code.claude.com - Update CLAUDE_CODE_PATTERN regex for new URL structure - Update SKILL.md documentation references to new domain --- skills/working-with-claude-code/SKILL.md | 6 +++--- skills/working-with-claude-code/scripts/update_docs.js | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/skills/working-with-claude-code/SKILL.md b/skills/working-with-claude-code/SKILL.md index 7c8581e..32ba7fb 100644 --- a/skills/working-with-claude-code/SKILL.md +++ b/skills/working-with-claude-code/SKILL.md @@ -7,7 +7,7 @@ description: Use when working with Claude Code CLI, plugins, hooks, MCP servers, ## Overview -This skill provides complete, authoritative documentation for Claude Code directly from docs.claude.com. Instead of guessing about configuration paths, API structures, or feature capabilities, read the official docs stored in this skill's references directory. +This skill provides complete, authoritative documentation for Claude Code directly from code.claude.com. Instead of guessing about configuration paths, API structures, or feature capabilities, read the official docs stored in this skill's references directory. ## When to Use @@ -121,7 +121,7 @@ path: ~/.claude/skills/working-with-claude-code/references/ ## Updating Documentation -The skill includes `scripts/update_docs.js` to fetch the latest documentation from docs.claude.com. +The skill includes `scripts/update_docs.js` to fetch the latest documentation from code.claude.com. Run when: - Documentation seems outdated @@ -133,7 +133,7 @@ node ~/.claude/skills/working-with-claude-code/scripts/update_docs.js ``` The script: -1. Fetches llms.txt from docs.claude.com +1. Fetches llms.txt from code.claude.com 2. Extracts all Claude Code documentation URLs 3. Downloads each page to `references/` 4. Reports success/failures diff --git a/skills/working-with-claude-code/scripts/update_docs.js b/skills/working-with-claude-code/scripts/update_docs.js index 1ed8627..f9a717e 100755 --- a/skills/working-with-claude-code/scripts/update_docs.js +++ b/skills/working-with-claude-code/scripts/update_docs.js @@ -3,7 +3,7 @@ /** * update_docs.js * - * Fetches the latest Claude Code documentation from docs.claude.com + * Fetches the latest Claude Code documentation from code.claude.com * and saves it to the references/ directory. * * Usage: node scripts/update_docs.js @@ -13,8 +13,8 @@ const https = require('https'); const fs = require('fs'); const path = require('path'); -const LLMS_TXT_URL = 'https://docs.claude.com/llms.txt'; -const CLAUDE_CODE_PATTERN = /https:\/\/docs\.claude\.com\/en\/docs\/claude-code\/[^\s)]+\.md/g; +const LLMS_TXT_URL = 'https://code.claude.com/docs/llms.txt'; +const CLAUDE_CODE_PATTERN = /https:\/\/code\.claude\.com\/docs\/en\/[^\s)]+\.md/g; const REFERENCES_DIR = path.join(__dirname, '..', 'references'); /** From a4ba8a2aa83884b84f0a67888225a8bd77c25e00 Mon Sep 17 00:00:00 2001 From: Chris Vaillancourt Date: Tue, 9 Dec 2025 16:52:19 -0800 Subject: [PATCH 2/7] feat(update_docs): add documentation map for quick overview - Add claude_code_docs_map.md to provide hierarchical outline of all docs - Update script to fetch docs map alongside individual pages - Document new file in SKILL.md file listing The docs map provides LLMs with complete structural overview without reading all 47+ individual documentation files. --- skills/working-with-claude-code/SKILL.md | 6 +- .../references/claude_code_docs_map.md | 1017 +++++++++++++++++ .../scripts/update_docs.js | 7 +- 3 files changed, 1027 insertions(+), 3 deletions(-) create mode 100644 skills/working-with-claude-code/references/claude_code_docs_map.md diff --git a/skills/working-with-claude-code/SKILL.md b/skills/working-with-claude-code/SKILL.md index 32ba7fb..fb9678f 100644 --- a/skills/working-with-claude-code/SKILL.md +++ b/skills/working-with-claude-code/SKILL.md @@ -41,6 +41,7 @@ All documentation is stored as individual markdown files in `references/`. Use t ``` references/ +├── claude_code_docs_map.md # Complete hierarchical outline of all docs ├── overview.md # Claude Code introduction ├── quickstart.md # Getting started guide ├── setup.md # Installation and setup @@ -135,8 +136,9 @@ node ~/.claude/skills/working-with-claude-code/scripts/update_docs.js The script: 1. Fetches llms.txt from code.claude.com 2. Extracts all Claude Code documentation URLs -3. Downloads each page to `references/` -4. Reports success/failures +3. Downloads the documentation map (complete hierarchical outline) +4. Downloads each page to `references/` +5. Reports success/failures ## Common Patterns diff --git a/skills/working-with-claude-code/references/claude_code_docs_map.md b/skills/working-with-claude-code/references/claude_code_docs_map.md new file mode 100644 index 0000000..9a4e349 --- /dev/null +++ b/skills/working-with-claude-code/references/claude_code_docs_map.md @@ -0,0 +1,1017 @@ +# null + +# Claude Code Documentation Map + +This is a comprehensive map of all Claude Code documentation pages with their headings, designed for easy navigation by LLMs. + +> **Note:** This file is auto-generated by GitHub Actions. Do not edit manually. +> Last updated: 2025-11-06 00:10:13 UTC + +## Document Structure + +This map uses a hierarchical structure: + +* **##** marks documentation groups (e.g., 'Getting started') +* **###** marks individual documentation pages +* **Nested bullets** show the heading structure within each page +* Each page title links to the full documentation + +## Getting started + +### [overview](https://code.claude.com/docs/en/overview.md) + +* Get started in 30 seconds +* What Claude Code does for you +* Why developers love Claude Code +* Next steps +* Additional resources + +### [quickstart](https://code.claude.com/docs/en/quickstart.md) + +* Before you begin +* Step 1: Install Claude Code +* Step 2: Log in to your account +* Step 3: Start your first session +* Step 4: Ask your first question +* Step 5: Make your first code change +* Step 6: Use Git with Claude Code +* Step 7: Fix a bug or add a feature +* Step 8: Test out other common workflows +* Essential commands +* Pro tips for beginners +* What's next? +* Getting help + +### [common-workflows](https://code.claude.com/docs/en/common-workflows.md) + +* Understand new codebases + * Get a quick codebase overview + * Find relevant code +* Fix bugs efficiently +* Refactor code +* Use specialized subagents +* Use Plan Mode for safe code analysis + * When to use Plan Mode + * How to use Plan Mode + * Example: Planning a complex refactor + * Configure Plan Mode as default +* Work with tests +* Create pull requests +* Handle documentation +* Work with images +* Reference files and directories +* Use extended thinking +* Resume previous conversations +* Run parallel Claude Code sessions with Git worktrees +* Use Claude as a unix-style utility + * Add Claude to your verification process + * Pipe in, pipe out + * Control output format +* Create custom slash commands + * Create project-specific commands + * Add command arguments with \$ARGUMENTS + * Create personal slash commands +* Ask Claude about its capabilities + * Example questions +* Next steps + +### [claude-code-on-the-web](https://code.claude.com/docs/en/claude-code-on-the-web.md) + +* What is Claude Code on the web? +* Who can use Claude Code on the web? +* Getting started +* How it works +* Moving tasks between web and terminal + * From web to terminal +* Cloud environment + * Default image + * Checking available tools + * Language-specific setups + * Environment configuration + * Dependency management + * Local vs remote execution + * Persisting environment variables +* Network access and security + * Network policy + * GitHub proxy + * Security proxy + * Access levels + * Default allowed domains + * Anthropic Services + * Version Control + * Container Registries + * Cloud Platforms + * Package Managers - JavaScript/Node + * Package Managers - Python + * Package Managers - Ruby + * Package Managers - Rust + * Package Managers - Go + * Package Managers - JVM + * Package Managers - Other Languages + * Linux Distributions + * Development Tools & Platforms + * Cloud Services & Monitoring + * Content Delivery & Mirrors + * Schema & Configuration + * Security best practices for customized network access +* Security and isolation +* Pricing and rate limits +* Limitations +* Best practices +* Related resources + +## Build with Claude Code + +### [sub-agents](https://code.claude.com/docs/en/sub-agents.md) + +* What are subagents? +* Key benefits +* Quick start +* Subagent configuration + * File locations + * Plugin agents + * CLI-based configuration + * File format + * Configuration fields + * Model selection + * Available tools +* Managing subagents + * Using the /agents command (Recommended) + * Direct file management +* Using subagents effectively + * Automatic delegation + * Explicit invocation +* Built-in subagents + * Plan subagent +* Example subagents + * Code reviewer + * Debugger + * Data scientist +* Best practices +* Advanced usage + * Chaining subagents + * Dynamic subagent selection + * Resumable subagents +* Performance considerations +* Related documentation + +### [plugins](https://code.claude.com/docs/en/plugins.md) + +* Quickstart + * Prerequisites + * Create your first plugin +* Hello Command + * Plugin structure overview + * Install and manage plugins + * Prerequisites + * Add marketplaces + * Install plugins + * Via interactive menu (recommended for discovery) + * Via direct commands (for quick installation) + * Verify installation + * Set up team plugin workflows + * Develop more complex plugins + * Add Skills to your plugin + * Organize complex plugins + * Test your plugins locally + * Debug plugin issues + * Share your plugins + * Next steps + * For plugin users + * For plugin developers + * For team leads and administrators + * See also + +### [skills](https://code.claude.com/docs/en/skills.md) + +* Prerequisites +* What are Agent Skills? +* Create a Skill + * Personal Skills + * Project Skills + * Plugin Skills +* Write SKILL.md +* Add supporting files +* Restrict tool access with allowed-tools +* View available Skills +* Test a Skill +* Debug a Skill + * Make description specific + * Verify file path + * Check YAML syntax + * View errors +* Share Skills with your team + * Step 1: Add Skill to your project + * Step 2: Commit to git + * Step 3: Team members get Skills automatically +* Update a Skill +* Remove a Skill +* Best practices + * Keep Skills focused + * Write clear descriptions + * Test with your team + * Document Skill versions +* Troubleshooting + * Claude doesn't use my Skill + * Skill has errors + * Multiple Skills conflict +* Examples + * Simple Skill (single file) + * Skill with tool permissions + * Multi-file Skill +* Next steps + +### [output-styles](https://code.claude.com/docs/en/output-styles.md) + +* Built-in output styles +* How output styles work +* Change your output style +* Create a custom output style +* Comparisons to related features + * Output Styles vs. CLAUDE.md vs. --append-system-prompt + * Output Styles vs. [Agents](/en/sub-agents) + * Output Styles vs. [Custom Slash Commands](/en/slash-commands) + +### [hooks-guide](https://code.claude.com/docs/en/hooks-guide.md) + +* Hook Events Overview +* Quickstart + * Prerequisites + * Step 1: Open hooks configuration + * Step 2: Add a matcher + * Step 3: Add the hook + * Step 4: Save your configuration + * Step 5: Verify your hook + * Step 6: Test your hook +* More Examples + * Code Formatting Hook + * Markdown Formatting Hook + * Custom Notification Hook + * File Protection Hook +* Learn more + +### [headless](https://code.claude.com/docs/en/headless.md) + +* Overview +* Basic usage +* Configuration Options +* Multi-turn conversations +* Output Formats + * Text Output (Default) + * JSON Output + * Streaming JSON Output +* Input Formats + * Text Input (Default) + * Streaming JSON Input +* Agent Integration Examples + * SRE Incident Response Bot + * Automated Security Review + * Multi-turn Legal Assistant +* Best Practices +* Related Resources + +### [github-actions](https://code.claude.com/docs/en/github-actions.md) + +* Why use Claude Code GitHub Actions? +* What can Claude do? + * Claude Code Action +* Setup +* Quick setup +* Manual setup +* Upgrading from Beta + * Essential changes + * Breaking Changes Reference + * Before and After Example +* Example use cases + * Basic workflow + * Using slash commands + * Custom automation with prompts + * Common use cases +* Best practices + * CLAUDE.md configuration + * Security considerations + * Optimizing performance + * CI costs +* Configuration examples +* Using with AWS Bedrock & Google Vertex AI + * Prerequisites + * For Google Cloud Vertex AI: + * For AWS Bedrock: +* Troubleshooting + * Claude not responding to @claude commands + * CI not running on Claude's commits + * Authentication errors +* Advanced configuration + * Action parameters + * Using claude\_args + * Alternative integration methods + * Customizing Claude's behavior + +### [gitlab-ci-cd](https://code.claude.com/docs/en/gitlab-ci-cd.md) + +* Why use Claude Code with GitLab? +* How it works +* What can Claude do? +* Setup + * Quick setup + * Manual setup (recommended for production) +* Example use cases + * Turn issues into MRs + * Get implementation help + * Fix bugs quickly +* Using with AWS Bedrock & Google Vertex AI +* Configuration examples + * Basic .gitlab-ci.yml (Claude API) + * AWS Bedrock job example (OIDC) + * Google Vertex AI job example (Workload Identity Federation) +* Best practices + * CLAUDE.md configuration + * Security considerations + * Optimizing performance + * CI costs +* Security and governance +* Troubleshooting + * Claude not responding to @claude commands + * Job can't write comments or open MRs + * Authentication errors +* Advanced configuration + * Common parameters and variables + * Customizing Claude's behavior + +### [mcp](https://code.claude.com/docs/en/mcp.md) + +* What you can do with MCP +* Popular MCP servers +* Installing MCP servers + * Option 1: Add a remote HTTP server + * Option 2: Add a remote SSE server + * Option 3: Add a local stdio server + * Managing your servers + * Plugin-provided MCP servers +* MCP installation scopes + * Local scope + * Project scope + * User scope + * Choosing the right scope + * Scope hierarchy and precedence + * Environment variable expansion in `.mcp.json` +* Practical examples + * Example: Monitor errors with Sentry + * Example: Connect to GitHub for code reviews + * Example: Query your PostgreSQL database +* Authenticate with remote MCP servers +* Add MCP servers from JSON configuration +* Import MCP servers from Claude Desktop +* Use Claude Code as an MCP server +* MCP output limits and warnings +* Use MCP resources + * Reference MCP resources +* Use MCP prompts as slash commands + * Execute MCP prompts +* Enterprise MCP configuration + * Setting up enterprise MCP configuration + * Restricting MCP servers with allowlists and denylists + +### [migration-guide](https://code.claude.com/docs/en/migration-guide.md) + +* Overview +* What's Changed +* Migration Steps + * For TypeScript/JavaScript Projects + * For Python Projects +* Breaking changes + * Python: ClaudeCodeOptions renamed to ClaudeAgentOptions + * System prompt no longer default + * Settings Sources No Longer Loaded by Default +* Why the Rename? +* Getting Help +* Next Steps + +### [troubleshooting](https://code.claude.com/docs/en/troubleshooting.md) + +* Common installation issues + * Windows installation issues: errors in WSL + * Linux and Mac installation issues: permission or command not found errors + * Recommended solution: Native Claude Code installation +* Permissions and authentication + * Repeated permission prompts + * Authentication issues +* Performance and stability + * High CPU or memory usage + * Command hangs or freezes + * Search and discovery issues + * Slow or incomplete search results on WSL +* IDE integration issues + * JetBrains IDE not detected on WSL2 + * WSL2 networking modes + * Reporting Windows IDE integration issues (both native and WSL) + * ESC key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals +* Markdown formatting issues + * Missing language tags in code blocks + * Inconsistent spacing and formatting + * Best practices for markdown generation +* Getting more help + +## Deployment + +### [third-party-integrations](https://code.claude.com/docs/en/third-party-integrations.md) + +* Provider comparison +* Cloud providers +* Corporate infrastructure +* Configuration overview + * Using Bedrock with corporate proxy + * Using Bedrock with LLM Gateway + * Using Vertex AI with corporate proxy + * Using Vertex AI with LLM Gateway + * Authentication configuration +* Choosing the right deployment configuration + * Direct provider access + * Corporate proxy + * LLM Gateway +* Debugging +* Best practices for organizations + * 1. Invest in documentation and memory + * 2. Simplify deployment + * 3. Start with guided usage + * 4. Configure security policies + * 5. Leverage MCP for integrations +* Next steps + +### [amazon-bedrock](https://code.claude.com/docs/en/amazon-bedrock.md) + +* Prerequisites +* Setup + * 1. Submit use case details + * 2. Configure AWS credentials + * Advanced credential configuration + * Example configuration + * Configuration settings explained + * 3. Configure Claude Code + * 4. Model configuration + * 5. Output token configuration +* IAM configuration +* Troubleshooting +* Additional resources + +### [google-vertex-ai](https://code.claude.com/docs/en/google-vertex-ai.md) + +* Prerequisites +* Region Configuration +* Setup + * 1. Enable Vertex AI API + * 2. Request model access + * 3. Configure GCP credentials + * 4. Configure Claude Code + * 5. Model configuration +* IAM configuration +* 1M token context window +* Troubleshooting +* Additional resources + +### [network-config](https://code.claude.com/docs/en/network-config.md) + +* Proxy configuration + * Environment variables + * Basic authentication +* Custom CA certificates +* mTLS authentication +* Network access requirements +* Additional resources + +### [llm-gateway](https://code.claude.com/docs/en/llm-gateway.md) + +* LiteLLM configuration + * Prerequisites + * Basic LiteLLM setup + * Authentication methods + * Static API key + * Dynamic API key with helper + * Unified endpoint (recommended) + * Provider-specific pass-through endpoints (alternative) + * Claude API through LiteLLM + * Amazon Bedrock through LiteLLM + * Google Vertex AI through LiteLLM + * Model selection +* Additional resources + +### [devcontainer](https://code.claude.com/docs/en/devcontainer.md) + +* Key features +* Getting started in 4 steps +* Configuration breakdown +* Security features +* Customization options +* Example use cases + * Secure client work + * Team onboarding + * Consistent CI/CD environments +* Related resources + +### [sandboxing](https://code.claude.com/docs/en/sandboxing.md) + +* Overview +* Why sandboxing matters +* How it works + * Filesystem isolation + * Network isolation + * OS-level enforcement +* Getting started + * Enable sandboxing + * Configure sandboxing +* Security benefits + * Protection against prompt injection + * Reduced attack surface + * Transparent operation +* Security Limitations +* Advanced usage + * Custom proxy configuration + * Integration with existing security tools +* Best practices +* Open source +* Limitations +* See also + +## Administration + +### [setup](https://code.claude.com/docs/en/setup.md) + +* System requirements + * Additional dependencies +* Standard installation +* Windows setup +* Alternative installation methods + * Native installation options + * NPM installation +* Running on AWS or GCP +* Update Claude Code + * Auto updates + * Update manually + +### [iam](https://code.claude.com/docs/en/iam.md) + +* Authentication methods + * Claude API authentication + * Cloud provider authentication +* Access control and permissions + * Permission system + * Configuring permissions + * Permission modes + * Working directories + * Tool-specific permission rules + * Additional permission control with hooks + * Enterprise managed policy settings + * Settings precedence +* Credential management + +### [security](https://code.claude.com/docs/en/security.md) + +* How we approach security + * Security foundation + * Permission-based architecture + * Built-in protections + * User responsibility +* Protect against prompt injection + * Core protections + * Privacy safeguards + * Additional safeguards +* MCP security +* IDE security +* Cloud execution security +* Security best practices + * Working with sensitive code + * Team security + * Reporting security issues +* Related resources + +### [data-usage](https://code.claude.com/docs/en/data-usage.md) + +* Data policies + * Data training policy + * Development Partner Program + * Feedback using the `/bug` command + * Session quality surveys + * Data retention +* Data flow and dependencies + * Cloud execution +* Telemetry services +* Default behaviors by API provider + +### [monitoring-usage](https://code.claude.com/docs/en/monitoring-usage.md) + +* Quick Start +* Administrator Configuration +* Configuration Details + * Common Configuration Variables + * Metrics Cardinality Control + * Dynamic Headers + * Settings Configuration + * Script Requirements + * Important Limitations + * Multi-Team Organization Support + * Example Configurations +* Available Metrics and Events + * Standard Attributes + * Metrics + * Metric Details + * Session Counter + * Lines of Code Counter + * Pull Request Counter + * Commit Counter + * Cost Counter + * Token Counter + * Code Edit Tool Decision Counter + * Active Time Counter + * Events + * User Prompt Event + * Tool Result Event + * API Request Event + * API Error Event + * Tool Decision Event +* Interpreting Metrics and Events Data + * Usage Monitoring + * Cost Monitoring + * Alerting and Segmentation + * Event Analysis +* Backend Considerations + * For Metrics: + * For Events/Logs: +* Service Information +* ROI Measurement Resources +* Security/Privacy Considerations +* Monitoring Claude Code on Amazon Bedrock + +### [costs](https://code.claude.com/docs/en/costs.md) + +* Track your costs + * Using the `/cost` command + * Additional tracking options +* Managing costs for teams + * Rate limit recommendations +* Reduce token usage +* Background token usage +* Tracking version changes and updates + * Current version information + * Understanding changes in Claude Code behavior + * When cost reporting changes + +### [analytics](https://code.claude.com/docs/en/analytics.md) + +* Access analytics + * Required roles +* Available metrics + * Lines of code accepted + * Suggestion accept rate + * Activity + * Spend + * Team insights +* Using analytics effectively + * Monitor adoption + * Measure productivity +* Related resources + +### [plugin-marketplaces](https://code.claude.com/docs/en/plugin-marketplaces.md) + +* Overview + * Prerequisites +* Add and use marketplaces + * Add GitHub marketplaces + * Add Git repositories + * Add local marketplaces for development + * Install plugins from marketplaces + * Verify marketplace installation +* Configure team marketplaces +* Create your own marketplace + * Prerequisites for marketplace creation + * Create the marketplace file + * Marketplace schema + * Required fields + * Optional metadata + * Plugin entries + * Optional plugin fields + * Plugin sources + * Relative paths + * GitHub repositories + * Git repositories + * Advanced plugin entries +* Host and distribute marketplaces + * Host on GitHub (recommended) + * Host on other git services + * Use local marketplaces for development +* Manage marketplace operations + * List known marketplaces + * Update marketplace metadata + * Remove a marketplace +* Troubleshooting marketplaces + * Common marketplace issues + * Marketplace not loading + * Plugin installation failures + * Validation and testing +* Next steps + * For marketplace users + * For marketplace creators + * For organizations +* See also + +## Configuration + +### [settings](https://code.claude.com/docs/en/settings.md) + +* Settings files + * Available settings + * Permission settings + * Sandbox settings + * Settings precedence + * Key points about the configuration system + * System prompt availability + * Excluding sensitive files +* Subagent configuration +* Plugin configuration + * Plugin settings + * `enabledPlugins` + * `extraKnownMarketplaces` + * Managing plugins +* Environment variables +* Tools available to Claude + * Extending tools with hooks +* See also + +### [vs-code](https://code.claude.com/docs/en/vs-code.md) + +* VS Code Extension (Beta) + * Features + * Requirements + * Installation + * How It Works + * Using Third-Party Providers (Vertex and Bedrock) + * Environment Variables + * Not Yet Implemented +* Security Considerations +* Legacy CLI Integration +* Troubleshooting + * Extension Not Installing + * Legacy Integration Not Working + +### [jetbrains](https://code.claude.com/docs/en/jetbrains.md) + +* Supported IDEs +* Features +* Installation + * Marketplace Installation +* Usage + * From Your IDE + * From External Terminals +* Configuration + * Claude Code Settings + * Plugin Settings + * General Settings + * ESC Key Configuration +* Special Configurations + * Remote Development + * WSL Configuration +* Troubleshooting + * Plugin Not Working + * IDE Not Detected + * Command Not Found +* Security Considerations + +### [terminal-config](https://code.claude.com/docs/en/terminal-config.md) + +* Themes and appearance +* Line breaks + * Set up Shift+Enter (VS Code or iTerm2): + * Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app): +* Notification setup + * iTerm 2 system notifications + * Custom notification hooks +* Handling large inputs +* Vim Mode + +### [model-config](https://code.claude.com/docs/en/model-config.md) + +* Available models + * Model aliases + * Setting your model +* Special model behavior + * `default` model setting + * `opusplan` model setting + * Extended context with \[1m] +* Checking your current model +* Environment variables + * Prompt caching configuration + +### [memory](https://code.claude.com/docs/en/memory.md) + +* Determine memory type +* CLAUDE.md imports +* How Claude looks up memories +* Quickly add memories with the `#` shortcut +* Directly edit memories with `/memory` +* Set up project memory +* Organization-level memory management +* Memory best practices + +### [statusline](https://code.claude.com/docs/en/statusline.md) + +* Create a custom status line +* How it Works +* JSON Input Structure +* Example Scripts + * Simple Status Line + * Git-Aware Status Line + * Python Example + * Node.js Example + * Helper Function Approach +* Tips +* Troubleshooting + +## Reference + +### [cli-reference](https://code.claude.com/docs/en/cli-reference.md) + +* CLI commands +* CLI flags + * Agents flag format + * System prompt flags +* See also + +### [interactive-mode](https://code.claude.com/docs/en/interactive-mode.md) + +* Keyboard shortcuts + * General controls + * Multiline input + * Quick commands +* Vim editor mode + * Mode switching + * Navigation (NORMAL mode) + * Editing (NORMAL mode) +* Command history + * Reverse search with Ctrl+R +* Background bash commands + * How backgrounding works + * Bash mode with `!` prefix +* See also + +### [slash-commands](https://code.claude.com/docs/en/slash-commands.md) + +* Built-in slash commands +* Custom slash commands + * Syntax + * Parameters + * Command types + * Project commands + * Personal commands + * Features + * Namespacing + * Arguments + * All arguments with `$ARGUMENTS` + * Individual arguments with `$1`, `$2`, etc. + * Bash command execution + * File references + * Thinking mode + * Frontmatter +* Plugin commands + * How plugin commands work + * Plugin command structure + * Invocation patterns +* MCP slash commands + * Command format + * Features + * Dynamic discovery + * Arguments + * Naming conventions + * Managing MCP connections + * MCP permissions and wildcards +* `SlashCommand` tool + * `SlashCommand` tool supported commands + * Disable `SlashCommand` tool + * Disable specific commands only + * `SlashCommand` permission rules + * Character budget limit +* Skills vs slash commands + * Use slash commands for + * Use Skills for + * Key differences + * Example comparison + * When to use each +* See also + +### [checkpointing](https://code.claude.com/docs/en/checkpointing.md) + +* How checkpoints work + * Automatic tracking + * Rewinding changes +* Common use cases +* Limitations + * Bash command changes not tracked + * External changes not tracked + * Not a replacement for version control +* See also + +### [hooks](https://code.claude.com/docs/en/hooks.md) + +* Configuration + * Structure + * Project-Specific Hook Scripts + * Plugin hooks +* Prompt-Based Hooks + * How prompt-based hooks work + * Configuration + * Response schema + * Supported hook events + * Example: Intelligent Stop hook + * Example: SubagentStop with custom logic + * Comparison with bash command hooks + * Best practices +* Hook Events + * PreToolUse + * PermissionRequest + * PostToolUse + * Notification + * UserPromptSubmit + * Stop + * SubagentStop + * PreCompact + * SessionStart + * Persisting environment variables + * SessionEnd +* Hook Input + * PreToolUse Input + * PermissionRequest + * PostToolUse Input + * Notification Input + * UserPromptSubmit Input + * Stop and SubagentStop Input + * PreCompact Input + * SessionStart Input + * SessionEnd Input +* Hook Output + * Simple: Exit Code + * Exit Code 2 Behavior + * Advanced: JSON Output + * Common JSON Fields + * `PreToolUse` Decision Control + * `PermissionRequest` Decision Control + * `PostToolUse` Decision Control + * `UserPromptSubmit` Decision Control + * `Stop`/`SubagentStop` Decision Control + * `SessionStart` Decision Control + * `SessionEnd` Decision Control + * Exit Code Example: Bash Command Validation + * JSON Output Example: UserPromptSubmit to Add Context and Validation + * JSON Output Example: PreToolUse with Approval +* Working with MCP Tools + * MCP Tool Naming + * Configuring Hooks for MCP Tools +* Examples +* Security Considerations + * Disclaimer + * Security Best Practices + * Configuration Safety +* Hook Execution Details +* Debugging + * Basic Troubleshooting + * Advanced Debugging + * Debug Output Example + +### [plugins-reference](https://code.claude.com/docs/en/plugins-reference.md) + +* Plugin components reference + * Commands + * Agents + * Skills + * Hooks + * MCP servers +* Plugin manifest schema + * Complete schema + * Required fields + * Metadata fields + * Component path fields + * Path behavior rules + * Environment variables +* Plugin directory structure + * Standard plugin layout + * File locations reference +* Debugging and development tools + * Debugging commands + * Common issues +* Distribution and versioning reference + * Version management + +## Resources + +### [legal-and-compliance](https://code.claude.com/docs/en/legal-and-compliance.md) + +* Legal agreements + * License + * Commercial agreements +* Compliance + * Healthcare compliance (BAA) +* Security and trust + * Trust and safety + * Security vulnerability reporting + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/scripts/update_docs.js b/skills/working-with-claude-code/scripts/update_docs.js index f9a717e..1b935ff 100755 --- a/skills/working-with-claude-code/scripts/update_docs.js +++ b/skills/working-with-claude-code/scripts/update_docs.js @@ -14,6 +14,7 @@ const fs = require('fs'); const path = require('path'); const LLMS_TXT_URL = 'https://code.claude.com/docs/llms.txt'; +const DOCS_MAP_URL = 'https://code.claude.com/docs/en/claude_code_docs_map.md'; const CLAUDE_CODE_PATTERN = /https:\/\/code\.claude\.com\/docs\/en\/[^\s)]+\.md/g; const REFERENCES_DIR = path.join(__dirname, '..', 'references'); @@ -86,9 +87,13 @@ async function main() { const urls = await getClaudeCodeUrls(); console.log(`✅ Found ${urls.length} Claude Code documentation pages\n`); + // Fetch documentation map (overview of all docs) + console.log('📥 Downloading documentation map...'); + const mapResult = await fetchAndSaveDoc(DOCS_MAP_URL); + // Fetch all documentation pages console.log('📥 Downloading documentation...'); - const results = []; + const results = [mapResult]; for (const url of urls) { const result = await fetchAndSaveDoc(url); results.push(result); From b715d875d1b5f9ff385c5ce390dfaa6489a491f2 Mon Sep 17 00:00:00 2001 From: Chris Vaillancourt Date: Fri, 12 Dec 2025 11:18:59 -0800 Subject: [PATCH 3/7] docs(skill): update documentation list with new pages Add new documentation files to Quick Reference and file list: - claude-code-on-the-web.md (web-based Claude Code) - desktop.md (desktop application) - sandboxing.md (security isolation) - slack.md (Slack integration) - microsoft-foundry.md (Azure AI Foundry) Remove deprecated migration-guide.md and claude_code_docs_map.md references. --- skills/working-with-claude-code/SKILL.md | 96 +++++++++++++----------- 1 file changed, 51 insertions(+), 45 deletions(-) diff --git a/skills/working-with-claude-code/SKILL.md b/skills/working-with-claude-code/SKILL.md index fb9678f..878367b 100644 --- a/skills/working-with-claude-code/SKILL.md +++ b/skills/working-with-claude-code/SKILL.md @@ -34,6 +34,10 @@ Use this skill when: | Troubleshoot issues | `troubleshooting.md` | | General setup | `setup.md` or `quickstart.md` | | Configuration options | `settings.md` | +| Web-based Claude Code | `claude-code-on-the-web.md` | +| Desktop app | `desktop.md` | +| Sandboxing/security | `sandboxing.md` | +| Slack integration | `slack.md` | ## Documentation Organization @@ -41,49 +45,52 @@ All documentation is stored as individual markdown files in `references/`. Use t ``` references/ -├── claude_code_docs_map.md # Complete hierarchical outline of all docs ├── overview.md # Claude Code introduction -├── quickstart.md # Getting started guide -├── setup.md # Installation and setup -├── plugins.md # Plugin development -├── plugins-reference.md # Plugin API reference -├── plugin-marketplaces.md # Plugin marketplaces -├── skills.md # Skill creation -├── mcp.md # MCP server integration -├── hooks.md # Hooks overview -├── hooks-guide.md # Hooks implementation guide -├── slash-commands.md # Slash command reference -├── sub-agents.md # Subagent usage -├── settings.md # Configuration reference -├── cli-reference.md # CLI command reference -├── common-workflows.md # Common usage patterns -├── interactive-mode.md # Interactive mode guide -├── headless.md # Headless mode guide -├── output-styles.md # Output customization -├── statusline.md # Status line configuration -├── memory.md # Memory and context management -├── checkpointing.md # Checkpointing feature -├── analytics.md # Usage analytics -├── costs.md # Cost tracking -├── monitoring-usage.md # Usage monitoring -├── data-usage.md # Data usage policies -├── security.md # Security features -├── iam.md # IAM integration -├── network-config.md # Network configuration -├── terminal-config.md # Terminal configuration -├── model-config.md # Model configuration -├── llm-gateway.md # LLM gateway setup -├── amazon-bedrock.md # AWS Bedrock integration -├── google-vertex-ai.md # Google Vertex AI integration -├── vs-code.md # VS Code integration -├── jetbrains.md # JetBrains integration -├── devcontainer.md # Dev container support -├── github-actions.md # GitHub Actions integration -├── gitlab-ci-cd.md # GitLab CI/CD integration +├── quickstart.md # Getting started guide +├── setup.md # Installation and setup +├── common-workflows.md # Common usage patterns +├── claude-code-on-the-web.md # Web-based Claude Code +├── desktop.md # Desktop application +├── plugins.md # Plugin development +├── plugins-reference.md # Plugin API reference +├── plugin-marketplaces.md # Plugin marketplaces +├── skills.md # Skill creation +├── mcp.md # MCP server integration +├── hooks.md # Hooks overview +├── hooks-guide.md # Hooks implementation guide +├── slash-commands.md # Slash command reference +├── sub-agents.md # Subagent usage +├── settings.md # Configuration reference +├── cli-reference.md # CLI command reference +├── interactive-mode.md # Interactive mode guide +├── headless.md # Headless mode guide +├── output-styles.md # Output customization +├── statusline.md # Status line configuration +├── memory.md # Memory and context management +├── checkpointing.md # Checkpointing feature +├── sandboxing.md # Sandboxing and security isolation +├── analytics.md # Usage analytics +├── costs.md # Cost tracking +├── monitoring-usage.md # Usage monitoring +├── data-usage.md # Data usage policies +├── security.md # Security features +├── iam.md # IAM integration +├── network-config.md # Network configuration +├── terminal-config.md # Terminal configuration +├── model-config.md # Model configuration +├── llm-gateway.md # LLM gateway setup +├── amazon-bedrock.md # AWS Bedrock integration +├── google-vertex-ai.md # Google Vertex AI integration +├── microsoft-foundry.md # Microsoft Azure AI Foundry +├── vs-code.md # VS Code integration +├── jetbrains.md # JetBrains integration +├── devcontainer.md # Dev container support +├── github-actions.md # GitHub Actions integration +├── gitlab-ci-cd.md # GitLab CI/CD integration +├── slack.md # Slack integration ├── third-party-integrations.md # Other integrations -├── legal-and-compliance.md # Legal information -├── troubleshooting.md # Troubleshooting guide -└── migration-guide.md # Migration guide +├── legal-and-compliance.md # Legal information +└── troubleshooting.md # Troubleshooting guide ``` ## Workflow @@ -134,11 +141,10 @@ node ~/.claude/skills/working-with-claude-code/scripts/update_docs.js ``` The script: -1. Fetches llms.txt from code.claude.com +1. Fetches llms.txt from code.claude.com/docs/ 2. Extracts all Claude Code documentation URLs -3. Downloads the documentation map (complete hierarchical outline) -4. Downloads each page to `references/` -5. Reports success/failures +3. Downloads each page to `references/` +4. Reports success/failures ## Common Patterns From 5be2f6f16ec04435de4d8c1c6221b00650ee56c0 Mon Sep 17 00:00:00 2001 From: Chris Vaillancourt Date: Fri, 12 Dec 2025 11:19:12 -0800 Subject: [PATCH 4/7] docs(references): update all docs from code.claude.com Refresh all 41 existing documentation files with latest content from code.claude.com/docs/. Updates include: - New features and configuration options - Updated CLI commands and flags - Improved examples and workflows - Bug fixes and clarifications --- .../references/amazon-bedrock.md | 67 +- .../references/analytics.md | 9 +- .../references/checkpointing.md | 11 +- .../references/claude-code-on-the-web.md | 489 ++++++++++ .../references/cli-reference.md | 145 ++- .../references/common-workflows.md | 59 +- .../references/costs.md | 7 +- .../references/data-usage.md | 33 +- .../references/desktop.md | 85 ++ .../references/devcontainer.md | 11 +- .../references/github-actions.md | 28 +- .../references/gitlab-ci-cd.md | 13 +- .../references/google-vertex-ai.md | 20 +- .../references/headless.md | 13 +- .../references/hooks-guide.md | 20 +- .../references/hooks.md | 412 +++++++-- .../references/iam.md | 38 +- .../references/interactive-mode.md | 44 +- .../references/jetbrains.md | 21 +- .../references/legal-and-compliance.md | 5 + .../references/llm-gateway.md | 52 +- .../references/mcp.md | 868 ++++++------------ .../references/memory.md | 151 ++- .../references/microsoft-foundry.md | 112 +++ .../references/model-config.md | 54 +- .../references/monitoring-usage.md | 143 ++- .../references/network-config.md | 13 +- .../references/output-styles.md | 61 +- .../references/overview.md | 83 +- .../references/plugin-marketplaces.md | 51 +- .../references/plugins-reference.md | 32 +- .../references/plugins.md | 57 +- .../references/quickstart.md | 73 +- .../references/sandboxing.md | 224 +++++ .../references/security.md | 44 +- .../references/settings.md | 413 ++++++--- .../references/setup.md | 207 ++++- .../references/skills.md | 46 +- .../references/slack.md | 211 +++++ .../references/slash-commands.md | 156 ++-- .../references/statusline.md | 34 +- .../references/sub-agents.md | 233 ++++- .../references/terminal-config.md | 11 +- .../references/third-party-integrations.md | 79 +- .../references/troubleshooting.md | 103 ++- .../references/vs-code.md | 110 ++- 46 files changed, 3698 insertions(+), 1453 deletions(-) create mode 100644 skills/working-with-claude-code/references/claude-code-on-the-web.md create mode 100644 skills/working-with-claude-code/references/desktop.md create mode 100644 skills/working-with-claude-code/references/microsoft-foundry.md create mode 100644 skills/working-with-claude-code/references/sandboxing.md create mode 100644 skills/working-with-claude-code/references/slack.md diff --git a/skills/working-with-claude-code/references/amazon-bedrock.md b/skills/working-with-claude-code/references/amazon-bedrock.md index 6132ed0..1aeaf90 100644 --- a/skills/working-with-claude-code/references/amazon-bedrock.md +++ b/skills/working-with-claude-code/references/amazon-bedrock.md @@ -7,20 +7,20 @@ Before configuring Claude Code with Bedrock, ensure you have: * An AWS account with Bedrock access enabled -* Access to desired Claude models (e.g., Claude Sonnet 4.5) in Bedrock +* 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. Enable model access +### 1. Submit use case details -First, ensure you have access to the required Claude models in your AWS account: +First-time users of Anthropic models are required to submit use case details before invoking a model. This is done once per account. -1. Navigate to the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/) -2. Go to **Model access** in the left navigation -3. Request access to desired Claude models (e.g., Claude Sonnet 4.5) -4. Wait for approval (usually instant for most regions) +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 @@ -48,7 +48,15 @@ aws sso login --profile= export AWS_PROFILE=your-profile-name ``` -**Option D: Bedrock API keys** +**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 @@ -58,7 +66,7 @@ Bedrock API keys provide a simpler authentication method without needing full AW #### 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/docs/claude-code/settings) for file locations). +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. @@ -75,9 +83,9 @@ When Claude Code detects that your AWS credentials are expired (either locally b ##### Configuration settings explained -**`awsAuthRefresh`**: Use this for commands that modify the `.aws` directory (e.g., updating credentials, SSO cache, or config files). Output is shown to the user (but user input is not supported), making it suitable for browser-based authentication flows where the CLI displays a code to enter in the browser. +**`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 cannot modify `.aws` and must directly return credentials. Output is captured silently (not shown to the user). The command must output JSON in this format: +**`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} { @@ -102,11 +110,13 @@ export AWS_REGION=us-east-1 # or your preferred region export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2 ``` +**For VS Code Extension users**: Configure environment variables in the VS Code extension settings instead of exporting them in your shell. See [Using Third-Party Providers in VS Code](/en/vs-code#using-third-party-providers-vertex-and-bedrock) for detailed instructions. All environment variables shown in this guide should work when configured through the VS Code extension settings. + 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/docs/claude-code/settings) for more information. +* 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 @@ -118,7 +128,7 @@ Claude Code uses these default models for Bedrock: | Small/fast model | `us.anthropic.claude-haiku-4-5-20251001-v1:0` | - For Bedrock 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 (e.g., `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: @@ -135,13 +145,11 @@ export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-in export DISABLE_PROMPT_CACHING=1 ``` - - [Prompt caching](/en/docs/build-with-claude/prompt-caching) may not be available in all regions - +[Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) may not be available in all regions. ### 5. Output token configuration -When using Claude Code with Amazon Bedrock, we recommend the following token settings: +These are the recommended token settings for Claude Code with Amazon Bedrock: ```bash theme={null} # Recommended output token settings for Bedrock @@ -151,7 +159,7 @@ 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. +* **`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. @@ -164,6 +172,7 @@ Create an IAM policy with the required permissions for Claude Code: "Version": "2012-10-17", "Statement": [ { + "Sid": "AllowModelAndInferenceProfileAccess", "Effect": "Allow", "Action": [ "bedrock:InvokeModel", @@ -172,8 +181,23 @@ Create an IAM policy with the required permissions for Claude Code: ], "Resource": [ "arn:aws:bedrock:*:*:inference-profile/*", - "arn:aws:bedrock:*:*:application-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" + } + } } ] } @@ -207,3 +231,8 @@ Claude Code uses the Bedrock [Invoke API](https://docs.aws.amazon.com/bedrock/la * [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) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/analytics.md b/skills/working-with-claude-code/references/analytics.md index 828dde1..275433c 100644 --- a/skills/working-with-claude-code/references/analytics.md +++ b/skills/working-with-claude-code/references/analytics.md @@ -83,5 +83,10 @@ Tool acceptance rates and code metrics help you: ## Related resources -* [Monitoring usage with OpenTelemetry](/en/docs/claude-code/monitoring-usage) for custom metrics and alerting -* [Identity and access management](/en/docs/claude-code/iam) for role configuration +* [Monitoring usage with OpenTelemetry](/en/monitoring-usage) for custom metrics and alerting +* [Identity and access management](/en/iam) for role configuration + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/checkpointing.md b/skills/working-with-claude-code/references/checkpointing.md index 3135aed..7f6dd41 100644 --- a/skills/working-with-claude-code/references/checkpointing.md +++ b/skills/working-with-claude-code/references/checkpointing.md @@ -60,6 +60,11 @@ Checkpoints are designed for quick, session-level recovery. For permanent versio ## See also -* [Interactive mode](/en/docs/claude-code/interactive-mode) - Keyboard shortcuts and session controls -* [Slash commands](/en/docs/claude-code/slash-commands) - Accessing checkpoints using `/rewind` -* [CLI reference](/en/docs/claude-code/cli-reference) - Command-line options +* [Interactive mode](/en/interactive-mode) - Keyboard shortcuts and session controls +* [Slash commands](/en/slash-commands) - Accessing checkpoints using `/rewind` +* [CLI reference](/en/cli-reference) - Command-line options + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/claude-code-on-the-web.md b/skills/working-with-claude-code/references/claude-code-on-the-web.md new file mode 100644 index 0000000..e737412 --- /dev/null +++ b/skills/working-with-claude-code/references/claude-code-on-the-web.md @@ -0,0 +1,489 @@ +# 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. This is perfect for: + +* **On the go**: Kick off tasks while commuting or away from laptop +* **Monitoring**: Watch the trajectory and steer the agent's work + +Developers can also move Claude Code sessions from the Claude app to their terminal to continue tasks 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 and create a pull request in GitHub + +## 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 + +## Moving tasks between web and terminal + +### From web to terminal + +After starting a task on the web: + +1. Click the "Open in CLI" button +2. Paste and run the command in your terminal in a checkout of the repo +3. Any existing local changes will be stashed, and the remote session will be loaded +4. Continue working locally + +## 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. + + + 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 +* claude.ai + +#### Version Control + +* github.com +* [www.github.com](http://www.github.com) +* api.github.com +* raw\.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 +* ghcr.io +* mcr.microsoft.com +* \*.data.mcr.microsoft.com + +#### 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 +* 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) +* 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 +* 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 + +#### Content Delivery & Mirrors + +* \*.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) + + + 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) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/cli-reference.md b/skills/working-with-claude-code/references/cli-reference.md index f775dd4..cca72c2 100644 --- a/skills/working-with-claude-code/references/cli-reference.md +++ b/skills/working-with-claude-code/references/cli-reference.md @@ -4,41 +4,58 @@ ## 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 | `claude -c` | -| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` | -| `claude -r "" "query"` | Resume session by ID | `claude -r "abc123" "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/docs/claude-code/mcp). | +| 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 | `claude -c` | +| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` | +| `claude -r "" "query"` | Resume session by ID | `claude -r "abc123" "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` | -| `--agents` | Define custom [subagents](/en/docs/claude-code/sub-agents) dynamically via JSON (see below for format) | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` | -| `--allowedTools` | A list of tools that should be allowed without prompting the user for permission, in addition to [settings.json files](/en/docs/claude-code/settings) | `"Bash(git log:*)" "Bash(git diff:*)" "Read"` | -| `--disallowedTools` | A list of tools that should be disallowed without prompting the user for permission, in addition to [settings.json files](/en/docs/claude-code/settings) | `"Bash(git log:*)" "Bash(git diff:*)" "Edit"` | -| `--print`, `-p` | Print response without interactive mode (see [SDK documentation](/en/docs/claude-code/sdk) for programmatic usage details) | `claude -p "query"` | -| `--append-system-prompt` | Append to system prompt (only with `--print`) | `claude --append-system-prompt "Custom instruction"` | -| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` | -| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` | -| `--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"` | -| `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` | -| `--max-turns` | Limit the number of agentic turns in non-interactive mode | `claude -p --max-turns 3 "query"` | -| `--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` | -| `--permission-mode` | Begin in a specified [permission mode](iam#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"` | -| `--resume` | Resume a specific session by ID, or by choosing in interactive mode | `claude --resume abc123 "query"` | -| `--continue` | Load the most recent conversation in the current directory | `claude --continue` | -| `--dangerously-skip-permissions` | Skip permission prompts (use with caution) | `claude --dangerously-skip-permissions` | +| 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"}}'` | +| `--allowedTools` | A list of tools that should be allowed without prompting the user for permission, in addition to [settings.json files](/en/settings) | `"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"` | +| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` | +| `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` | +| `--dangerously-skip-permissions` | Skip 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"` | +| `--disallowedTools` | A list of tools that should be disallowed without prompting the user for permission, in addition to [settings.json files](/en/settings) | `"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` | +| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` | +| `--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"` | +| `--max-turns` | Limit the number of agentic turns in non-interactive mode | `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` | +| `--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/iam#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"` | +| `--resume`, `-r` | Resume a specific session by ID, or by choosing in interactive mode | `claude --resume abc123 "query"` | +| `--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"` | +| `--tools` | Specify the list of available tools from the built-in set (use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"`) | `claude -p --tools "Bash,Edit,Read" "query"` | +| `--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 @@ -49,12 +66,12 @@ Customize Claude Code's behavior with these command-line flags: 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 (e.g., `["Read", "Edit", "Bash"]`). If omitted, inherits all tools | -| `model` | No | Model alias to use: `sonnet`, `opus`, or `haiku`. If omitted, uses the default subagent model | +| 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`, or `haiku`. If omitted, uses the default subagent model | Example: @@ -73,17 +90,57 @@ claude --agents '{ }' ``` -For more details on creating and using subagents, see the [subagents documentation](/en/docs/claude-code/sub-agents). +For more details on creating and using subagents, see the [subagents documentation](/en/sub-agents). + +### System prompt flags + +Claude Code provides three 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 | + +**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" + ``` + + + `--system-prompt` and `--system-prompt-file` are mutually exclusive. You cannot use both flags simultaneously. + + + + For most use cases, `--append-system-prompt` is recommended as it preserves 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. + For detailed information about print mode (`-p`) including output formats, streaming, verbose logging, and programmatic usage, see the -[SDK documentation](/en/docs/claude-code/sdk). +[SDK documentation](https://docs.claude.com/en/docs/agent-sdk). ## See also -* [Interactive mode](/en/docs/claude-code/interactive-mode) - Shortcuts, input modes, and interactive features -* [Slash commands](/en/docs/claude-code/slash-commands) - Interactive session commands -* [Quickstart guide](/en/docs/claude-code/quickstart) - Getting started with Claude Code -* [Common workflows](/en/docs/claude-code/common-workflows) - Advanced workflows and patterns -* [Settings](/en/docs/claude-code/settings) - Configuration options -* [SDK documentation](/en/docs/claude-code/sdk) - Programmatic usage and integrations +* [Interactive mode](/en/interactive-mode) - Shortcuts, input modes, and interactive features +* [Slash commands](/en/slash-commands) - Interactive session commands +* [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 + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/common-workflows.md b/skills/working-with-claude-code/references/common-workflows.md index 5864ff5..2f3867e 100644 --- a/skills/working-with-claude-code/references/common-workflows.md +++ b/skills/working-with-claude-code/references/common-workflows.md @@ -173,7 +173,7 @@ Suppose you want to use specialized AI subagents to handle specific tasks more e - Claude Code will automatically delegate appropriate tasks to specialized subagents: + Claude Code automatically delegates appropriate tasks to specialized subagents: ``` > review my recent code changes for security issues @@ -201,10 +201,10 @@ Suppose you want to use specialized AI subagents to handle specific tasks more e Then select "Create New subagent" and follow the prompts to define: - * Subagent type (e.g., `api-designer`, `performance-optimizer`) - * When to use it + * 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 - * Its specialized system prompt + * A system prompt describing the agent's role and behavior @@ -214,7 +214,7 @@ Suppose you want to use specialized AI subagents to handle specific tasks more e * 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/docs/claude-code/sub-agents) for detailed examples + * Check the [subagents documentation](/en/sub-agents) for detailed examples *** @@ -235,7 +235,7 @@ Plan Mode instructs Claude to create a plan by analyzing the codebase with read- 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** will first switch 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`. +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** @@ -247,7 +247,7 @@ claude --permission-mode plan **Run "headless" queries in Plan Mode** -You can also run a query in Plan Mode directly with `-p` (i.e., in ["headless mode"](/en/docs/claude-code/sdk/sdk-headless)): +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" @@ -263,7 +263,7 @@ claude --permission-mode plan > I need to refactor our authentication system to use OAuth2. Create a detailed migration plan. ``` -Claude will analyze the current implementation and create a comprehensive plan. Refine with follow-ups: +Claude analyzes the current implementation and create a comprehensive plan. Refine with follow-ups: ``` > What about backward compatibility? @@ -281,7 +281,7 @@ Claude will analyze the current implementation and create a comprehensive plan. } ``` -See [settings documentation](/en/docs/claude-code/settings#available-settings) for more configuration options. +See [settings documentation](/en/settings#available-settings) for more configuration options. *** @@ -315,13 +315,9 @@ Suppose you need to add tests for uncovered code. - - Tips: +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. - * Ask for tests that cover edge cases and error conditions - * Request both unit and integration tests when appropriate - * Have Claude explain the testing strategy - +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. *** @@ -336,7 +332,7 @@ Suppose you need to create a well-documented pull request for your changes. ``` - + ``` > create a pr ``` @@ -488,7 +484,7 @@ Use @ to quickly include files or directories without waiting for Claude to read > 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/docs/claude-code/mcp#use-mcp-resources) for details. + This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/en/mcp#use-mcp-resources) for details. @@ -496,9 +492,9 @@ Use @ to quickly include files or directories without waiting for Claude to read Tips: * File paths can be relative or absolute - * @ file references add CLAUDE.md in the file's directory and parent directories to context + * @ 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 (e.g., "@file1.js and @file2.js") + * You can reference multiple files in a single message (for example, "@file1.js and @file2.js") *** @@ -508,7 +504,7 @@ Use @ to quickly include files or directories without waiting for Claude to read Suppose you're working on complex architectural decisions, challenging bugs, or planning multi-step implementations that require deep reasoning. - [Extended thinking](/en/docs/build-with-claude/extended-thinking) is disabled by default in Claude Code. You can enable it on-demand by using `Tab` to toggle Thinking on, or by using prompts like "think" or "think hard". You can also enable it permanently by setting the [`MAX_THINKING_TOKENS` environment variable](/en/docs/claude-code/settings#environment-variables) in your settings. + [Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is disabled by default in Claude Code. You can enable it on-demand by using `Tab` to toggle Thinking on, or by using prompts like "think" or "think hard". You can also enable it permanently by setting the [`MAX_THINKING_TOKENS` environment variable](/en/settings#environment-variables) in your settings. @@ -517,8 +513,8 @@ Suppose you're working on complex architectural decisions, challenging bugs, or > I need to implement a new authentication system using OAuth2 for our API. Think deeply about the best approach for implementing this in our codebase. ``` - Claude will gather relevant information from your codebase and - use extended thinking, which will be visible in the interface. + Claude gathers relevant information from your codebase and + uses extended thinking, which is visible in the interface. @@ -535,7 +531,7 @@ Suppose you're working on complex architectural decisions, challenging bugs, or Tips to get the most value out of extended thinking: - [Extended thinking](/en/docs/build-with-claude/extended-thinking) is most valuable for complex tasks such as: + [Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is most valuable for complex tasks such as: * Planning complex architectural changes * Debugging intricate issues @@ -550,11 +546,11 @@ Suppose you're working on complex architectural decisions, challenging bugs, or * "think" triggers basic extended thinking * intensifying phrases such as "keep hard", "think more", "think a lot", or "think longer" triggers deeper thinking - For more extended thinking prompting tips, see [Extended thinking tips](/en/docs/build-with-claude/prompt-engineering/extended-thinking-tips). + For more extended thinking prompting tips, see [Extended thinking tips](https://docs.claude.com/en/docs/build-with-claude/prompt-engineering/extended-thinking-tips). - Claude will display its thinking process as italic gray text above the + Claude displays its thinking process as italic gray text above the response. @@ -793,7 +789,7 @@ Suppose you need Claude's output in a specific format, especially when integrati Claude Code supports custom slash commands that you can create to quickly execute specific prompts or tasks. -For more details, see the [Slash commands](/en/docs/claude-code/slash-commands) reference page. +For more details, see the [Slash commands](/en/slash-commands) reference page. ### Create project-specific commands @@ -822,8 +818,8 @@ Suppose you want to create reusable slash commands for your project that all tea Tips: - * Command names are derived from the filename (e.g., `optimize.md` becomes `/optimize`) - * You can organize commands in subdirectories (e.g., `.claude/commands/frontend/component.md` creates `/component` with "(project:frontend)" shown in the description) + * Command names are derived from the filename (for example, `optimize.md` becomes `/optimize`) + * You can organize commands in subdirectories (for example, `.claude/commands/frontend/component.md` creates `/component` with "(project:frontend)" shown in the description) * Project commands are available to everyone who clones the repository * The Markdown file content becomes the prompt sent to Claude when the command is invoked @@ -850,7 +846,7 @@ Suppose you want to create flexible slash commands that can accept additional in > /fix-issue 123 ``` - This will replace \$ARGUMENTS with "123" in the prompt. + This replaces \$ARGUMENTS with "123" in the prompt. @@ -947,3 +943,8 @@ Claude has built-in access to its documentation and can answer questions about i Clone our development container reference implementation. + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/costs.md b/skills/working-with-claude-code/references/costs.md index 9c5a7ed..ed2dd03 100644 --- a/skills/working-with-claude-code/references/costs.md +++ b/skills/working-with-claude-code/references/costs.md @@ -35,7 +35,7 @@ Check [historical usage](https://support.claude.com/en/articles/9534590-cost-and When using Claude API, you can limit the total Claude Code workspace spend. To configure, [follow these instructions](https://support.claude.com/en/articles/9796807-creating-and-managing-workspaces). Admins can view cost and usage reporting by [following these instructions](https://support.claude.com/en/articles/9534590-cost-and-usage-reporting-in-console). -On Bedrock and Vertex, Claude Code does not send metrics from your cloud. In order to get cost metrics, several large enterprises reported using [LiteLLM](/en/docs/claude-code/bedrock-vertex-proxies#litellm), 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. +On Bedrock and Vertex, Claude Code does not send metrics from your cloud. In order to get cost metrics, several large enterprises reported using [LiteLLM](/en/third-party-integrations#litellm), 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 @@ -129,3 +129,8 @@ If you notice changes in how costs are displayed (such as the `/cost` command sh For team deployments, we recommend starting with a small pilot group to establish usage patterns before wider rollout. + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/data-usage.md b/skills/working-with-claude-code/references/data-usage.md index 1d9285f..89f4e64 100644 --- a/skills/working-with-claude-code/references/data-usage.md +++ b/skills/working-with-claude-code/references/data-usage.md @@ -17,7 +17,7 @@ We will train new models using data from Free, Pro, and Max accounts when this s If you're a new user, you can pick your setting for model training during the signup process. You can change your selection at any time in your Privacy Settings. -**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 (e.g. [Developer Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program)). +**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 @@ -27,6 +27,10 @@ If you explicitly opt in to methods to provide us with materials to train on, su 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. + ### Data retention Anthropic retains Claude Code data based on your account type and preferences. @@ -35,7 +39,7 @@ Anthropic retains Claude Code data based on your account type and preferences. * 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](claude.ai/settings/data-privacy-controls). +* 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)**: @@ -49,12 +53,28 @@ For full details, please review our [Commercial Terms of Service](https://www.an ## Data flow and dependencies -Claude Code data flow diagram +Claude Code data flow diagram 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 + + + The above data flow diagram and description applies to Claude Code CLI running locally on your machine. For cloud-based sessions using Claude Code on the web, see the section below. + + +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 storage**: Your repository is cloned to an isolated VM and automatically deleted after session completion +* **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 +* **Data retention**: Code and session data are subject to the retention and usage policies for your account type +* **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. @@ -73,4 +93,9 @@ By default, we disable all non-essential traffic (including error reporting, tel | **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. | | **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. | -All environment variables can be checked into `settings.json` ([read more](/en/docs/claude-code/settings)). +All environment variables can be checked into `settings.json` ([read more](/en/settings)). + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/desktop.md b/skills/working-with-claude-code/references/desktop.md new file mode 100644 index 0000000..18aa492 --- /dev/null +++ b/skills/working-with-claude-code/references/desktop.md @@ -0,0 +1,85 @@ +# Claude Code on desktop + +> Run Claude Code tasks locally or on secure cloud infrastructure with the Claude desktop app + +Claude Code on desktop interface + +## Claude Code on desktop (Preview) + +The Claude desktop app provides a native interface for running multiple Claude Code sessions on your local machine and seamless integration with Claude Code on the web. + +## Features + +Claude Code on desktop provides: + +* **Parallel local sessions with `git` worktrees**: Run multiple Claude Code sessions simultaneously in the same repository, each with its own isolated `git` worktree +* **Include files listed in your `.gitignore` in your worktrees**: Automatically copy files in your `.gitignore`, like `.env`, to new worktrees using `.worktreeinclude` +* **Launch Claude Code on the web**: Kick off secure cloud sessions directly from the desktop app + +## Installation + +Download and install the Claude Desktop app from [claude.ai/download](https://claude.ai/download) + + + Local sessions are not available on Windows arm64 architectures. + + +## Using Git worktrees + +Claude Code on desktop enables running multiple Claude Code sessions in the same repository using Git worktrees. Each session gets its own isolated worktree, allowing Claude to work on different tasks without conflicts. The default location for worktrees is `~/.claude-worktrees` but this can be configured in your settings on the Claude desktop app. + + + If you start a local session in a folder that does not have Git initialized, the desktop app will not create a new worktree. + + +### Copying files ignored with `.gitignore` + +When Claude Code creates a worktree, files ignored via `.gitignore` aren't automatically available. Including a `.worktreeinclude` file solves this by specifying which ignored files should be copied to new worktrees. + +Create a `.worktreeinclude` file in your repository root: + +``` +.env +.env.local +.env.* +**/.claude/settings.local.json +``` + +The file uses `.gitignore`-style patterns. When a worktree is created, files matching these patterns that are also in your `.gitignore` will be copied from your main repository to the worktree. + + + Only files that are both matched by `.worktreeinclude` AND listed in `.gitignore` are copied. This prevents accidentally duplicating tracked files. + + +### Launch Claude Code on the web + +From the desktop app, you can kick off Claude Code sessions that run on Anthropic's secure cloud infrastructure. This is useful for: + +To start a web session from desktop, select a remote environment when creating a new session. + +For more details, see [Claude Code on the web](/en/claude-code-on-the-web). + +## Bundled Claude Code version + +Claude Code on desktop includes a bundled, stable version of Claude Code to ensure a consistent experience for all desktop users. The bundled version is required and downloaded on first launch even if a version of Claude Code exists on the computer. Desktop automatically manages version updates and cleans up old versions. + + + The bundled Claude Code version in Desktop may differ from the latest CLI version. Desktop prioritizes stability while the CLI may have newer features. + + +### 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) +* [Claude Desktop support articles](https://support.claude.com/en/collections/16163169-claude-desktop) +* [Enterprise Configuration](https://support.claude.com/en/articles/12622667-enterprise-configuration) +* [Common workflows](/en/common-workflows) +* [Settings reference](/en/settings) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/devcontainer.md b/skills/working-with-claude-code/references/devcontainer.md index 6d7e241..de2f1aa 100644 --- a/skills/working-with-claude-code/references/devcontainer.md +++ b/skills/working-with-claude-code/references/devcontainer.md @@ -8,7 +8,7 @@ The container's enhanced security measures (isolation and firewall rules) allow While the devcontainer provides substantial protections, no system is completely immune to all attacks. - When executed with `--dangerously-skip-permissions`, devcontainers do not prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials. + 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. @@ -73,5 +73,10 @@ Mirror your devcontainer configuration in CI/CD pipelines to ensure development ## Related resources * [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers) -* [Claude Code security best practices](/en/docs/claude-code/security) -* [Enterprise network configuration](/en/docs/claude-code/network-config) +* [Claude Code security best practices](/en/security) +* [Enterprise network configuration](/en/network-config) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/github-actions.md b/skills/working-with-claude-code/references/github-actions.md index b9d4066..f496a05 100644 --- a/skills/working-with-claude-code/references/github-actions.md +++ b/skills/working-with-claude-code/references/github-actions.md @@ -6,11 +6,15 @@ Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. Claude Code GitHub Actions is built on top of the [Claude Code - SDK](/en/docs/claude-code/sdk), which enables programmatic integration of + 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 @@ -63,8 +67,7 @@ If the `/install-github-app` command fails or you prefer manual setup, please fo 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! + After completing either the quickstart or manual setup, test the action by tagging `@claude` in an issue or PR comment. ## Upgrading from Beta @@ -110,7 +113,7 @@ All beta users must make these changes to their workflow files in order to upgra anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} custom_instructions: "Follow our coding standards" max_turns: "10" - model: "claude-3-5-sonnet-20241022" + model: "claude-sonnet-4-5-20250929" ``` **GA version (v1.0):** @@ -186,7 +189,7 @@ jobs: 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-1-20250805" + claude_args: "--model claude-opus-4-5-20251101" ``` ### Common use cases @@ -209,7 +212,7 @@ Create a `CLAUDE.md` file in your repository root to define code style guideline ### Security considerations -Never commit API keys directly to your repository! +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). @@ -220,7 +223,7 @@ Always use GitHub Secrets for API keys: * Limit action permissions to only what's necessary * Review Claude's suggestions before merging -Always use GitHub Secrets (e.g., `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files. +Always use GitHub Secrets (for example, `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files. ### Optimizing performance @@ -633,7 +636,7 @@ The Claude Code Action v1 uses a simplified configuration: \*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase\ \*\*Required for direct Claude API, not for Bedrock/Vertex -#### Using claude\_args +#### Pass CLI arguments The `claude_args` parameter accepts any Claude Code CLI arguments: @@ -644,7 +647,7 @@ claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929 --mcp-config /pat Common arguments: * `--max-turns`: Maximum conversation turns (default: 10) -* `--model`: Model to use (e.g., `claude-sonnet-4-5-20250929`) +* `--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 @@ -663,7 +666,12 @@ See the [Claude Code Action documentation](https://github.com/anthropics/claude- 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/docs/claude-code/memory) for more details. +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. + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/gitlab-ci-cd.md b/skills/working-with-claude-code/references/gitlab-ci-cd.md index 157a000..4b87bf2 100644 --- a/skills/working-with-claude-code/references/gitlab-ci-cd.md +++ b/skills/working-with-claude-code/references/gitlab-ci-cd.md @@ -9,7 +9,7 @@ - This integration is built on top of the [Claude Code CLI and SDK](/en/docs/claude-code/sdk), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows. + 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? @@ -315,7 +315,7 @@ claude-bedrock: ``` - Model IDs for Bedrock include region-specific prefixes and version suffixes (for example, `us.anthropic.claude-3-7-sonnet-20250219-v1:0`). Pass the desired model via your job configuration or prompt if your workflow supports it. + 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) @@ -379,7 +379,7 @@ Create a `CLAUDE.md` file at the repository root to define coding standards, rev ### Security considerations -Never commit API keys or cloud credentials to your repository! Always use GitLab CI/CD variables: +**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) @@ -404,7 +404,7 @@ When using Claude Code with GitLab CI/CD, be aware of associated costs: * **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](/en/docs/about-claude/pricing) for details + * 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 @@ -460,3 +460,8 @@ 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). + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/google-vertex-ai.md b/skills/working-with-claude-code/references/google-vertex-ai.md index 23c4dc9..fc5188d 100644 --- a/skills/working-with-claude-code/references/google-vertex-ai.md +++ b/skills/working-with-claude-code/references/google-vertex-ai.md @@ -8,7 +8,7 @@ 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 (e.g., Claude Sonnet 4.5) +* Access to desired Claude models (for example, Claude Sonnet 4.5) * Google Cloud SDK (`gcloud`) installed and configured * Quota allocated in desired GCP region @@ -44,7 +44,7 @@ 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 (e.g., Claude Sonnet 4.5) +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 @@ -82,7 +82,7 @@ export VERTEX_REGION_CLAUDE_4_1_OPUS=europe-west1 ``` - [Prompt caching](/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. + [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. @@ -99,7 +99,7 @@ Claude Code uses these default models for Vertex AI: | 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 (e.g., `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: @@ -115,8 +115,7 @@ Assign the required IAM permissions: The `roles/aiplatform.user` role includes the required permissions: -* `aiplatform.endpoints.predict` - Required for model invocation -* `aiplatform.endpoints.computeTokens` - Required for token counting +* `aiplatform.endpoints.predict` - Required for model invocation and token counting For more restrictive permissions, create a custom role with only the permissions above. @@ -126,9 +125,9 @@ For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/d We recommend creating a dedicated GCP project for Claude Code to simplify cost tracking and access control. -### 1M token context window +## 1M token context window -Claude Sonnet 4 and Sonnet 4.5 support the [1M token context window](/en/docs/build-with-claude/context-windows#1m-token-context-window) on Vertex AI. +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. @@ -158,3 +157,8 @@ If you encounter 429 errors: * [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) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/headless.md b/skills/working-with-claude-code/references/headless.md index 8b26268..9f10a01 100644 --- a/skills/working-with-claude-code/references/headless.md +++ b/skills/working-with-claude-code/references/headless.md @@ -33,7 +33,7 @@ Headless mode leverages all the CLI options available in Claude Code. Here are t | `--mcp-config` | Load MCP servers from a JSON file | `claude --mcp-config servers.json` | | `--permission-prompt-tool` | MCP tool for handling permission prompts (only with `--print`) | `claude --permission-prompt-tool mcp__auth__prompt` | -For a complete list of CLI options and features, see the [CLI reference](/en/docs/claude-code/cli-reference) documentation. +For a complete list of CLI options and features, see the [CLI reference](/en/cli-reference) documentation. ## Multi-turn conversations @@ -109,7 +109,7 @@ echo "Explain this code" | claude -p A stream of messages provided via `stdin` where each message represents a user turn. This allows multiple turns of a conversation without re-launching the `claude` binary and allows providing guidance to the model while it is processing a request. -Each message is a JSON 'User message' object, following the same format as the output message schema. Messages are formatted using the [jsonl](https://jsonlines.org/) format where each line of input is a complete JSON object. Streaming JSON input requires `-p` and `--output-format stream-json`. +Each message is a JSON 'User message' object, following the same format as the output message schema. Messages are formatted using the [`jsonl`](https://jsonlines.org/) format where each line of input is a complete JSON object. Streaming JSON input requires `-p` and `--output-format stream-json`. ```bash theme={null} echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Explain this code"}]}}' | claude -p --output-format=stream-json --input-format=stream-json --verbose @@ -200,5 +200,10 @@ claude -p --resume "$session_id" "Generate executive summary of risks" ## Related Resources -* [CLI usage and controls](/en/docs/claude-code/cli-reference) - Complete CLI documentation -* [Common workflows](/en/docs/claude-code/common-workflows) - Step-by-step guides for common use cases +* [CLI usage and controls](/en/cli-reference) - Complete CLI documentation +* [Common workflows](/en/common-workflows) - Step-by-step guides for common use cases + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/hooks-guide.md b/skills/working-with-claude-code/references/hooks-guide.md index 9dd601f..ac75bf1 100644 --- a/skills/working-with-claude-code/references/hooks-guide.md +++ b/skills/working-with-claude-code/references/hooks-guide.md @@ -8,7 +8,7 @@ Code's behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. - For reference documentation on hooks, see [Hooks reference](/en/docs/claude-code/hooks). + For reference documentation on hooks, see [Hooks reference](/en/hooks). Example use cases for hooks include: @@ -31,7 +31,7 @@ suggestions into app-level code that executes every time it is expected to run. You must consider the security implication of hooks as you add them, because hooks run automatically during the agent loop with your current environment's credentials. For example, malicious hooks code can exfiltrate your data. Always review your hooks implementation before registering them. - For full security best practices, see [Security Considerations](/en/docs/claude-code/hooks#security-considerations) in the hooks reference documentation. + For full security best practices, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation. ## Hook Events Overview @@ -40,6 +40,7 @@ Claude Code provides several hook events that run at different points in the workflow: * **PreToolUse**: Runs before tool calls (can block them) +* **PermissionRequest**: Runs when a permission dialog is shown (can allow or deny) * **PostToolUse**: Runs after tool calls complete * **UserPromptSubmit**: Runs when the user submits a prompt, before Claude processes it * **Notification**: Runs when Claude Code sends notifications @@ -63,7 +64,7 @@ Install `jq` for JSON processing in the command line. ### Step 1: Open hooks configuration -Run the `/hooks` [slash command](/en/docs/claude-code/slash-commands) and select +Run the `/hooks` [slash command](/en/slash-commands) and select the `PreToolUse` hook event. `PreToolUse` hooks run before tool calls and can block them while providing @@ -91,7 +92,7 @@ For storage location, select `User settings` since you're logging to your home directory. This hook will then apply to all projects, not just your current project. -Then press Esc until you return to the REPL. Your hook is now registered! +Then press `Esc` until you return to the REPL. Your hook is now registered. ### Step 5: Verify your hook @@ -326,7 +327,12 @@ Block edits to sensitive files: ## Learn more -* For reference documentation on hooks, see [Hooks reference](/en/docs/claude-code/hooks). -* For comprehensive security best practices and safety guidelines, see [Security Considerations](/en/docs/claude-code/hooks#security-considerations) in the hooks reference documentation. -* For troubleshooting steps and debugging techniques, see [Debugging](/en/docs/claude-code/hooks#debugging) in the hooks reference +* For reference documentation on hooks, see [Hooks reference](/en/hooks). +* For comprehensive security best practices and safety guidelines, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation. +* For troubleshooting steps and debugging techniques, see [Debugging](/en/hooks#debugging) in the hooks reference documentation. + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/hooks.md b/skills/working-with-claude-code/references/hooks.md index 20e51fc..fa3a484 100644 --- a/skills/working-with-claude-code/references/hooks.md +++ b/skills/working-with-claude-code/references/hooks.md @@ -3,12 +3,12 @@ > This page provides reference documentation for implementing hooks in Claude Code. - For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/docs/claude-code/hooks-guide). + For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/hooks-guide). ## Configuration -Claude Code hooks are configured in your [settings files](/en/docs/claude-code/settings): +Claude Code hooks are configured in your [settings files](/en/settings): * `~/.claude/settings.json` - User settings * `.claude/settings.json` - Project settings @@ -38,19 +38,18 @@ Hooks are organized by matchers, where each matcher can have multiple hooks: ``` * **matcher**: Pattern to match tool names, case-sensitive (only applicable for - `PreToolUse` and `PostToolUse`) + `PreToolUse`, `PermissionRequest`, and `PostToolUse`) * Simple strings match exactly: `Write` matches only the Write tool * Supports regex: `Edit|Write` or `Notebook.*` * Use `*` to match all tools. You can also use empty string (`""`) or leave `matcher` blank. -* **hooks**: Array of commands to execute when the pattern matches - * `type`: Currently only `"command"` is supported - * `command`: The bash command to execute (can use `$CLAUDE_PROJECT_DIR` - environment variable) - * `timeout`: (Optional) How long a command should run, in seconds, before - canceling that specific command. - -For events like `UserPromptSubmit`, `Notification`, `Stop`, and `SubagentStop` +* **hooks**: Array of hooks to execute when the pattern matches + * `type`: Hook execution type - `"command"` for bash commands or `"prompt"` for LLM-based evaluation + * `command`: (For `type: "command"`) The bash command to execute (can use `$CLAUDE_PROJECT_DIR` environment variable) + * `prompt`: (For `type: "prompt"`) The prompt to send to the LLM for evaluation + * `timeout`: (Optional) How long a hook should run, in seconds, before canceling that specific hook + +For events like `UserPromptSubmit`, `Stop`, and `SubagentStop` that don't use matchers, you can omit the matcher field: ```json theme={null} @@ -96,7 +95,7 @@ ensuring they work regardless of Claude's current directory: ### Plugin hooks -[Plugins](/en/docs/claude-code/plugins) can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled. +[Plugins](/en/plugins) can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled. **How plugin hooks work**: @@ -141,7 +140,138 @@ ensuring they work regardless of Claude's current directory: * `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks) * All standard environment variables are available -See the [plugin components reference](/en/docs/claude-code/plugins-reference#hooks) for details on creating plugin hooks. +See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks. + +## 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 are currently only supported for `Stop` and `SubagentStop` hooks, where they enable intelligent, context-aware decisions. + +### How prompt-based hooks work + +Instead of executing a bash command, prompt-based hooks: + +1. Send the hook input and your prompt to a fast LLM (Haiku) +2. The LLM responds with structured JSON containing a decision +3. Claude Code processes the decision automatically + +### Configuration + +```json theme={null} +{ + "hooks": { + "Stop": [ + { + "hooks": [ + { + "type": "prompt", + "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete." + } + ] + } + ] + } +} +``` + +**Fields:** + +* `type`: Must be `"prompt"` +* `prompt`: 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 +* `timeout`: (Optional) Timeout in seconds (default: 30 seconds) + +### Response schema + +The LLM must respond with JSON containing: + +```json theme={null} +{ + "decision": "approve" | "block", + "reason": "Explanation for the decision", + "continue": false, // Optional: stops Claude entirely + "stopReason": "Message shown to user", // Optional: custom stop message + "systemMessage": "Warning or context" // Optional: shown to user +} +``` + +**Response fields:** + +* `decision`: `"approve"` allows the action, `"block"` prevents it +* `reason`: Explanation shown to Claude when decision is `"block"` +* `continue`: (Optional) If `false`, stops Claude's execution entirely +* `stopReason`: (Optional) Message shown when `continue` is false +* `systemMessage`: (Optional) Additional message shown to the user + +### Supported hook events + +Prompt-based hooks work with any hook event, but are most useful for: + +* **Stop**: Intelligently decide if Claude should continue working +* **SubagentStop**: Evaluate if a subagent has completed its task +* **UserPromptSubmit**: Validate user prompts with LLM assistance +* **PreToolUse**: Make context-aware permission decisions +* **PermissionRequest**: Intelligently allow or deny permission dialogs + +### Example: Intelligent Stop hook + +```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: {\"decision\": \"approve\" or \"block\", \"reason\": \"your explanation\"}", + "timeout": 30 + } + ] + } + ] + } +} +``` + +### Example: SubagentStop with custom logic + +```json theme={null} +{ + "hooks": { + "SubagentStop": [ + { + "hooks": [ + { + "type": "prompt", + "prompt": "Evaluate if this subagent should stop. Input: $ARGUMENTS\n\nCheck if:\n- The subagent completed its assigned task\n- Any errors occurred that need fixing\n- Additional context gathering is needed\n\nReturn: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}" + } + ] + } + ] + } +} +``` + +### Comparison with bash command hooks + +| Feature | Bash Command Hooks | Prompt-Based Hooks | +| --------------------- | ----------------------- | ------------------------------ | +| **Execution** | Runs bash script | Queries LLM | +| **Decision logic** | You implement in code | LLM evaluates context | +| **Setup complexity** | Requires script file | Configure prompt | +| **Context awareness** | Limited to script logic | Natural language understanding | +| **Performance** | Fast (local execution) | Slower (API call) | +| **Use case** | Deterministic rules | Context-aware decisions | + +### Best practices + +* **Be specific in prompts**: Clearly state what you want the LLM to evaluate +* **Include decision criteria**: List the factors the LLM should consider +* **Test your prompts**: Verify the LLM makes correct decisions for your use cases +* **Set appropriate timeouts**: Default is 30 seconds, adjust if needed +* **Use for complex decisions**: Bash hooks are better for simple, deterministic rules + +See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks. ## Hook Events @@ -151,7 +281,7 @@ Runs after Claude creates tool parameters and before processing the tool call. **Common matchers:** -* `Task` - Subagent tasks (see [subagents documentation](/en/docs/claude-code/sub-agents)) +* `Task` - Subagent tasks (see [subagents documentation](/en/sub-agents)) * `Bash` - Shell commands * `Glob` - File pattern matching * `Grep` - Content search @@ -160,6 +290,15 @@ Runs after Claude creates tool parameters and before processing the tool call. * `Write` - File writing * `WebFetch`, `WebSearch` - Web operations +Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool. + +### 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. + +Recognizes the same matcher values as PreToolUse. + ### PostToolUse Runs immediately after a tool completes successfully. @@ -168,12 +307,45 @@ Recognizes the same matcher values as PreToolUse. ### Notification -Runs when Claude Code sends notifications. Notifications are sent when: +Runs when Claude Code sends notifications. Supports matchers to filter by notification type. -1. Claude needs your permission to use a tool. Example: "Claude needs your - permission to use Bash" -2. The prompt input has been idle for at least 60 seconds. "Claude is waiting - for your input" +**Common matchers:** + +* `permission_prompt` - Permission requests from Claude Code +* `idle_prompt` - When Claude is waiting for user input (after 60+ seconds of idle time) +* `auth_success` - Authentication success notifications +* `elicitation_dialog` - When Claude Code needs input for MCP tool elicitation + +You can use matchers to run different hooks for different notification types, or omit the matcher to run hooks for all notifications. + +**Example: Different notifications for different types** + +```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" + } + ] + } + ] + } +} +``` ### UserPromptSubmit @@ -203,7 +375,7 @@ Runs before Claude Code is about to run a compact operation. Runs when Claude Code starts a new session or resumes an existing session (which currently does start a new session under the hood). Useful for loading in -development context like existing issues or recent changes to your codebase. +development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables. **Matchers:** @@ -212,6 +384,51 @@ development context like existing issues or recent changes to your codebase. * `clear` - Invoked from `/clear` * `compact` - Invoked from auto or manual compact. +#### Persisting 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. + +**Example: Setting individual environment variables** + +```bash theme={null} +#!/bin/bash + +if [ -n "$CLAUDE_ENV_FILE" ]; then + echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE" + echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE" + echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE" +fi + +exit 0 +``` + +**Example: Persisting all environment changes from the hook** + +When your setup modifies the environment (for example, `nvm use`), capture and persist all changes by diffing the environment: + +```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 only available for SessionStart hooks. Other hook types do not have access to this variable. + + ### SessionEnd Runs when a Claude Code session ends. Useful for cleanup tasks, logging session @@ -235,6 +452,7 @@ event-specific data: session_id: string transcript_path: string // Path to conversation JSON cwd: string // The current working directory when the hook is invoked + permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions" // Event-specific fields hook_event_name: string @@ -251,12 +469,14 @@ The exact schema for `tool_input` depends on the tool. "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", + "permission_mode": "default", "hook_event_name": "PreToolUse", "tool_name": "Write", "tool_input": { "file_path": "/path/to/file.txt", "content": "file content" - } + }, + "tool_use_id": "toolu_01ABC123..." } ``` @@ -269,6 +489,7 @@ The exact schema for `tool_input` and `tool_response` depends on the tool. "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": { @@ -278,7 +499,8 @@ The exact schema for `tool_input` and `tool_response` depends on the tool. "tool_response": { "filePath": "/path/to/file.txt", "success": true - } + }, + "tool_use_id": "toolu_01ABC123..." } ``` @@ -289,8 +511,10 @@ The exact schema for `tool_input` and `tool_response` depends on the tool. "session_id": "abc123", "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", + "permission_mode": "default", "hook_event_name": "Notification", - "message": "Task completed successfully" + "message": "Claude needs your permission to use Bash", + "notification_type": "permission_prompt" } ``` @@ -301,6 +525,7 @@ The exact schema for `tool_input` and `tool_response` depends on the tool. "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" } @@ -316,6 +541,7 @@ from running indefinitely. { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", + "permission_mode": "default", "hook_event_name": "Stop", "stop_hook_active": true } @@ -330,6 +556,7 @@ For `manual`, `custom_instructions` comes from what the user passes into { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", + "permission_mode": "default", "hook_event_name": "PreCompact", "trigger": "manual", "custom_instructions": "" @@ -342,6 +569,7 @@ For `manual`, `custom_instructions` comes from what the user passes into { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", + "permission_mode": "default", "hook_event_name": "SessionStart", "source": "startup" } @@ -354,6 +582,7 @@ For `manual`, `custom_instructions` comes from what the user passes into "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", + "permission_mode": "default", "hook_event_name": "SessionEnd", "reason": "exit" } @@ -361,7 +590,7 @@ For `manual`, `custom_instructions` comes from what the user passes into ## Hook Output -There are two ways for hooks to return output back to Claude Code. The output +There are two mutually exclusive ways for hooks to return output back to Claude Code. The output communicates whether to block and any feedback that should be shown to Claude and the user. @@ -369,13 +598,16 @@ and the user. Hooks communicate status through exit codes, stdout, and stderr: -* **Exit code 0**: Success. `stdout` is shown to the user in transcript mode - (CTRL-R), except for `UserPromptSubmit` and `SessionStart`, where stdout is - added to the context. -* **Exit code 2**: Blocking error. `stderr` is fed back to Claude to process - automatically. See per-hook-event behavior below. -* **Other exit codes**: Non-blocking error. `stderr` is shown to the user and - execution continues. +* **Exit code 0**: Success. `stdout` is shown to the user in verbose mode + (ctrl+o), except for `UserPromptSubmit` and `SessionStart`, where stdout is + added to the context. JSON output in `stdout` is parsed for structured control + (see [Advanced: JSON Output](#advanced-json-output)). +* **Exit code 2**: Blocking error. Only `stderr` is used as the error message + and fed back to Claude. The format is `[command]: {stderr}`. JSON in `stdout` + is **not** processed for exit code 2. See per-hook-event behavior below. +* **Other exit codes**: Non-blocking error. `stderr` is shown to the user in verbose mode (ctrl+o) with + format `Failed with non-blocking status code: {stderr}`. If `stderr` is empty, + it shows `No stderr output`. Execution continues. Reminder: Claude Code does not see stdout if the exit code is 0, except for @@ -384,21 +616,28 @@ Hooks communicate status through exit codes, stdout, and stderr: #### Exit Code 2 Behavior -| Hook Event | Behavior | -| ------------------ | ------------------------------------------------------------------ | -| `PreToolUse` | Blocks the tool call, shows stderr to Claude | -| `PostToolUse` | Shows stderr to Claude (tool already ran) | -| `Notification` | N/A, shows stderr to user only | -| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only | -| `Stop` | Blocks stoppage, shows stderr to Claude | -| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent | -| `PreCompact` | N/A, shows stderr to user only | -| `SessionStart` | N/A, shows stderr to user only | -| `SessionEnd` | N/A, shows stderr to user only | +| Hook Event | Behavior | +| ------------------- | ------------------------------------------------------------------ | +| `PreToolUse` | Blocks the tool call, shows stderr to Claude | +| `PermissionRequest` | Denies the permission, shows stderr to Claude | +| `PostToolUse` | Shows stderr to Claude (tool already ran) | +| `Notification` | N/A, shows stderr to user only | +| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only | +| `Stop` | Blocks stoppage, shows stderr to Claude | +| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent | +| `PreCompact` | N/A, shows stderr to user only | +| `SessionStart` | N/A, shows stderr to user only | +| `SessionEnd` | N/A, shows stderr to user only | ### Advanced: JSON Output -Hooks can return structured JSON in `stdout` for more sophisticated control: +Hooks can return structured JSON in `stdout` for more sophisticated control. + + + JSON output is only processed when the hook exits with code 0. If your hook + exits with code 2 (blocking error), `stderr` text is used directly—any JSON in `stdout` + is ignored. For other non-zero exit codes, only `stderr` is shown to the user in verbose mode (ctrl+o). + #### Common JSON Fields @@ -440,12 +679,20 @@ to Claude. * `"ask"` asks the user to confirm the tool call in the UI. `permissionDecisionReason` is shown to the user but not to Claude. +Additionally, hooks can modify tool inputs before execution using `updatedInput`: + +* `updatedInput` allows you to modify the tool's input parameters before the tool executes. +* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls. + ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PreToolUse", - "permissionDecision": "allow" | "deny" | "ask", - "permissionDecisionReason": "My reason here" + "permissionDecision": "allow" + "permissionDecisionReason": "My reason here", + "updatedInput": { + "field_to_modify": "new value" + } } } ``` @@ -457,6 +704,27 @@ to Claude. `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. +#### `PermissionRequest` Decision Control + +`PermissionRequest` hooks can allow or deny permission requests shown to the user. + +* For `"behavior": "allow"` you can also optionally pass in an `"updatedInput"` that modifies the tool's input parameters before the tool executes. +* For `"behavior": "deny"` you can also optionally pass in a `"message"` string that tells the model why the permission was denied, and a boolean `"interrupt"` which will stop Claude. + +```json theme={null} +{ + "hookSpecificOutput": { + "hookEventName": "PermissionRequest", + "decision": { + "behavior": "allow", + "updatedInput": { + "command": "npm run lint" + } + } + } +} +``` + #### `PostToolUse` Decision Control `PostToolUse` hooks can provide feedback to Claude after tool execution. @@ -478,13 +746,26 @@ to Claude. #### `UserPromptSubmit` Decision Control -`UserPromptSubmit` hooks can control whether a user prompt is processed. +`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. + +**Adding context (exit code 0):** +There are two ways to add context to the conversation: + +1. **Plain text stdout** (simpler): Any non-JSON text written to stdout is added + as context. This is the easiest way to inject information. + +2. **JSON with `additionalContext`** (structured): Use the JSON format below for + more control. The `additionalContext` field is added as context. -* `"block"` prevents the prompt from being processed. The submitted prompt is - erased from context. `"reason"` is shown to the user but not added to context. -* `undefined` allows the prompt to proceed normally. `"reason"` is ignored. -* `"hookSpecificOutput.additionalContext"` adds the string to the context if not - blocked. +Both methods work with exit code 0. Plain stdout is shown as hook output in +the transcript; `additionalContext` is added more discretely. + +**Blocking prompts:** + +* `"decision": "block"` prevents the prompt from being processed. The submitted + prompt is erased from context. `"reason"` is shown to the user but not added + to context. +* `"decision": undefined` (or omitted) allows the prompt to proceed normally. ```json theme={null} { @@ -497,6 +778,11 @@ to Claude. } ``` + + 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. + + #### `Stop`/`SubagentStop` Decision Control `Stop` and `SubagentStop` hooks can control whether Claude must continue. @@ -590,8 +876,12 @@ if issues: For `UserPromptSubmit` hooks, you can inject context using either method: - * Exit code 0 with stdout: Claude sees the context (special case for `UserPromptSubmit`) - * JSON output: Provides more control over the behavior + * **Plain text stdout** with exit code 0: Simplest approach, prints text + * **JSON output** with exit code 0: Use `"decision": "block"` to reject prompts, + or `additionalContext` for structured context injection + + Remember: Exit code 2 only uses `stderr` for the error message. To block using + JSON (with a custom reason), use `"decision": "block"` with exit code 0. ```python theme={null} @@ -668,7 +958,7 @@ if tool_name == "Read": output = { "decision": "approve", "reason": "Documentation file auto-approved", - "suppressOutput": True # Don't show in transcript mode + "suppressOutput": True # Don't show in verbose mode } print(json.dumps(output)) sys.exit(0) @@ -680,7 +970,7 @@ sys.exit(0) ## Working with MCP Tools Claude Code hooks work seamlessly with -[Model Context Protocol (MCP) tools](/en/docs/claude-code/mcp). When MCP servers +[Model Context Protocol (MCP) tools](/en/mcp). When MCP servers provide tools, they appear with a special naming pattern that you can match in your hooks. @@ -726,7 +1016,7 @@ You can target specific MCP tools or entire MCP servers: ## Examples - For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/docs/claude-code/hooks-guide#more-examples) in the get started guide. + For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/hooks-guide#more-examples) in the get started guide. ## Security Considerations @@ -778,9 +1068,10 @@ This prevents malicious hook modifications from affecting your current session. * **Environment**: Runs in current directory with Claude Code's environment * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the absolute path to the project root directory (where Claude Code was started) + * The `CLAUDE_CODE_REMOTE` environment variable indicates whether the hook is running in a remote (web) environment (`"true"`) or local CLI environment (not set or empty). Use this to run different logic based on execution context. * **Input**: JSON via stdin * **Output**: - * PreToolUse/PostToolUse/Stop/SubagentStop: Progress shown in transcript (Ctrl-R) + * PreToolUse/PermissionRequest/PostToolUse/Stop/SubagentStop: Progress shown in verbose mode (ctrl+o) * Notification/SessionEnd: Logged to debug only (`--debug`) * UserPromptSubmit/SessionStart: stdout added as context for Claude @@ -829,9 +1120,14 @@ Use `claude --debug` to see hook execution details: [DEBUG] Hook command completed with status 0: ``` -Progress messages appear in transcript mode (Ctrl-R) showing: +Progress messages appear in verbose mode (ctrl+o) showing: * Which hook is running * Command being executed * Success/failure status * Output or error messages + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/iam.md b/skills/working-with-claude-code/references/iam.md index c12e61d..9b35515 100644 --- a/skills/working-with-claude-code/references/iam.md +++ b/skills/working-with-claude-code/references/iam.md @@ -4,10 +4,11 @@ ## Authentication methods -Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of three ways: +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 @@ -23,17 +24,17 @@ Setting up Claude Code requires access to Anthropic models. For teams, you can s * "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/docs/claude-code/setup#system-requirements) - * [Install Claude Code](/en/docs/claude-code/setup#installation) + * [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 or Vertex:** +**To set up Claude Code access for your team via Bedrock, Vertex, or Azure:** -1. Follow the [Bedrock docs](/en/docs/claude-code/amazon-bedrock) or [Vertex docs](/en/docs/claude-code/google-vertex-ai) -2. Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/en/docs/claude-code/settings). -3. Users can [install Claude Code](/en/docs/claude-code/setup#installation) +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 @@ -65,7 +66,7 @@ A rule that is just the tool name matches any use of that tool. For example, add #### Permission modes -Claude Code supports several permission modes that can be set as the `defaultMode` in [settings files](/en/docs/claude-code/settings#settings-files): +Claude Code supports several permission modes that can be set as the `defaultMode` in [settings files](/en/settings#settings-files): | Mode | Description | | :------------------ | :--------------------------------------------------------------------------- | @@ -80,7 +81,7 @@ By default, Claude has access to files in the directory where it was launched. Y * **During startup**: Use `--add-dir ` CLI argument * **During session**: Use `/add-dir` slash command -* **Persistent configuration**: Add to `additionalDirectories` in [settings files](/en/docs/claude-code/settings#settings-files) +* **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. @@ -164,19 +165,15 @@ Read & Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore ### Additional permission control with hooks -[Claude Code hooks](/en/docs/claude-code/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. +[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 policy settings For enterprise deployments of Claude Code, we support enterprise managed policy settings that take precedence over user and project settings. This allows system administrators to enforce security policies that users cannot override. -System administrators can deploy policies to: +System administrators can deploy policies to the [managed settings file locations](/en/settings#settings-files). -* macOS: `/Library/Application Support/ClaudeCode/managed-settings.json` -* Linux and WSL: `/etc/claude-code/managed-settings.json` -* Windows: `C:\ProgramData\ClaudeCode\managed-settings.json` - -These policy files follow the same format as regular [settings files](/en/docs/claude-code/settings#settings-files) but cannot be overridden by user or project settings. This ensures consistent security policies across your organization. +These policy files follow the same format as regular [settings files](/en/settings#settings-files) but cannot be overridden by user or project settings. This ensures consistent security policies across your organization. ### Settings precedence @@ -195,6 +192,11 @@ This hierarchy ensures that organizational policies are always enforced while st 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, Bedrock Auth, and Vertex Auth. -* **Custom credential scripts**: The [`apiKeyHelper`](/en/docs/claude-code/settings#available-settings) setting can be configured to run a shell script that returns an API key. +* **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 \ No newline at end of file diff --git a/skills/working-with-claude-code/references/interactive-mode.md b/skills/working-with-claude-code/references/interactive-mode.md index 758e2f6..e3e5aa6 100644 --- a/skills/working-with-claude-code/references/interactive-mode.md +++ b/skills/working-with-claude-code/references/interactive-mode.md @@ -5,23 +5,24 @@ ## Keyboard shortcuts - Keyboard shortcuts may vary by platform and terminal. Press `?` to see available shortcuts for your environment. + Keyboard shortcuts may vary by platform and terminal. Press `?` to see available shortcuts for your environment. For example, Option key combinations on macOS may require configuring your terminal to use Option as a meta/escape key. ### General controls -| Shortcut | Description | Context | -| :------------------------------------------- | :----------------------------------------------------------------------- | :---------------------------------------------------------- | -| `Ctrl+C` | Cancel current input or generation | Standard interrupt | -| `Ctrl+D` | Exit Claude Code session | EOF signal | -| `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` (macOS/Linux) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file | -| `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 | -| `Tab` | Toggle [extended thinking](/en/docs/build-with-claude/extended-thinking) | Switch between Thinking on and Thinking off | -| `Shift+Tab` or `Alt+M` (some configurations) | Toggle permission modes | Switch between Auto-Accept Mode, Plan Mode, and normal mode | +| Shortcut | Description | Context | +| :-------------------------------------------- | :---------------------------------------------------------------------------------------------- | :---------------------------------------------------------- | +| `Ctrl+C` | Cancel current input or generation | Standard interrupt | +| `Ctrl+D` | Exit Claude Code session | EOF signal | +| `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` (macOS/Linux) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file | +| `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 | +| `Tab` | Toggle [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) | Switch between Thinking on and Thinking off | +| `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 | ### Multiline input @@ -42,7 +43,7 @@ | Shortcut | Description | Notes | | :----------- | :--------------------------------- | :------------------------------------------------------------ | | `#` at start | Memory shortcut - add to CLAUDE.md | Prompts for file selection | -| `/` at start | Slash command | See [slash commands](/en/docs/claude-code/slash-commands) | +| `/` at start | Slash command | See [slash commands](/en/slash-commands) | | `!` at start | Bash mode | Run commands directly and add execution output to the session | | `@` | File path mention | Trigger file path autocomplete | @@ -162,8 +163,13 @@ This is useful for quick shell operations while maintaining conversation context ## See also -* [Slash commands](/en/docs/claude-code/slash-commands) - Interactive session commands -* [Checkpointing](/en/docs/claude-code/checkpointing) - Rewind Claude's edits and restore previous states -* [CLI reference](/en/docs/claude-code/cli-reference) - Command-line flags and options -* [Settings](/en/docs/claude-code/settings) - Configuration options -* [Memory management](/en/docs/claude-code/memory) - Managing CLAUDE.md files +* [Slash commands](/en/slash-commands) - Interactive session commands +* [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 + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/jetbrains.md b/skills/working-with-claude-code/references/jetbrains.md index ff4ef78..2e38c50 100644 --- a/skills/working-with-claude-code/references/jetbrains.md +++ b/skills/working-with-claude-code/references/jetbrains.md @@ -20,7 +20,7 @@ The Claude Code plugin works with most JetBrains IDEs, including: * **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 (e.g., @File#L1-99) +* **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 @@ -29,12 +29,10 @@ The Claude Code plugin works with most JetBrains IDEs, including: Find and install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains marketplace and restart your IDE. -### Auto-Installation - -The plugin may also be auto-installed when you run `claude` in the integrated terminal. The IDE must be restarted completely to take effect. +If you haven't installed Claude Code yet, see [our quickstart guide](/en/quickstart) for installation instructions. - After installing the plugin, you must restart your IDE completely for it to take effect. You may need to restart multiple times. + After installing the plugin, you may need to restart your IDE completely for it to take effect. ## Usage @@ -70,7 +68,7 @@ Configure the Claude Code plugin by going to **Settings → Tools → Claude Cod #### General Settings -* **Claude command**: Specify a custom command to run Claude (e.g., `claude`, `/usr/local/bin/claude`, or `npx @anthropic/claude`) +* **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) @@ -104,7 +102,7 @@ The plugin must be installed on the remote host, not on your local client machin ### WSL Configuration - WSL users may need additional configuration for IDE detection to work properly. See our [WSL troubleshooting guide](/en/docs/claude-code/troubleshooting#jetbrains-ide-not-detected-on-wsl2) for detailed setup instructions. + 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: @@ -127,7 +125,7 @@ WSL configuration may require: * 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/docs/claude-code/troubleshooting#jetbrains-ide-not-detected-on-wsl2) +* For WSL users, see the [WSL troubleshooting guide](/en/troubleshooting#jetbrains-ide-not-detected-on-wsl2) ### Command Not Found @@ -147,4 +145,9 @@ When running in JetBrains IDEs, consider: * 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/docs/claude-code/troubleshooting). +For additional help, see our [troubleshooting guide](/en/troubleshooting). + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/legal-and-compliance.md b/skills/working-with-claude-code/references/legal-and-compliance.md index 783ff4f..1ef9ca7 100644 --- a/skills/working-with-claude-code/references/legal-and-compliance.md +++ b/skills/working-with-claude-code/references/legal-and-compliance.md @@ -34,3 +34,8 @@ Anthropic manages our security program through HackerOne. [Use this form to repo *** © Anthropic PBC. All rights reserved. Use is subject to applicable Anthropic Terms of Service. + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/llm-gateway.md b/skills/working-with-claude-code/references/llm-gateway.md index a16e972..22fd38d 100644 --- a/skills/working-with-claude-code/references/llm-gateway.md +++ b/skills/working-with-claude-code/references/llm-gateway.md @@ -1,8 +1,8 @@ # LLM gateway configuration -> Learn how to configure Claude Code with LLM gateway solutions, including LiteLLM setup, authentication methods, and enterprise features like usage tracking and budget management. +> 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, offering: +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 @@ -10,6 +10,37 @@ LLM gateways provide a centralized proxy layer between Claude Code and model pro * **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 @@ -129,17 +160,16 @@ export CLAUDE_CODE_USE_VERTEX=1 export CLOUD_ML_REGION=us-east5 ``` -### Model selection - -By default, the models will use those specified in [Model configuration](/en/docs/claude-code/bedrock-vertex-proxies#model-configuration). - -If you have configured custom model names in LiteLLM, set the aforementioned environment variables to those custom names. - 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/docs/claude-code/settings) -* [Enterprise network configuration](/en/docs/claude-code/network-config) -* [Third-party integrations overview](/en/docs/claude-code/third-party-integrations) +* [Claude Code settings](/en/settings) +* [Enterprise network configuration](/en/network-config) +* [Third-party integrations overview](/en/third-party-integrations) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/mcp.md b/skills/working-with-claude-code/references/mcp.md index bb0ec92..0860ccb 100644 --- a/skills/working-with-claude-code/references/mcp.md +++ b/skills/working-with-claude-code/references/mcp.md @@ -3,494 +3,114 @@ > 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 remoteUrl = server.remotes?.[0]?.url || meta.url; + const remoteType = server.remotes?.[0]?.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 --transport http ${server.name.toLowerCase().replace(/[^a-z0-9]/g, '-')} ${server.urls.http}`; + return `claude mcp add ${serverSlug} --transport http ${server.urls.http}`; } if (server.urls.sse) { - return `claude mcp add --transport sse ${server.name.toLowerCase().replace(/[^a-z0-9]/g, '-')} ${server.urls.sse}`; + return `claude mcp add ${serverSlug} --transport sse ${server.urls.sse}`; } if (server.urls.stdio) { - const envFlags = server.authentication && server.authentication.envVars ? server.authentication.envVars.map(v => `--env ${v}=YOUR_${v.split('_').pop()}`).join(' ') : ''; - const baseCommand = `claude mcp add --transport stdio ${server.name.toLowerCase().replace(/[^a-z0-9]/g, '-')}`; + 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; }; - const servers = [{ - name: "Airtable", - category: "Databases & Data Management", - description: "Read/write records, manage bases and tables", - documentation: "https://github.com/domdomegg/airtable-mcp-server", - urls: { - stdio: "npx -y airtable-mcp-server" - }, - authentication: { - type: "api_key", - envVars: ["AIRTABLE_API_KEY"] - }, - availability: { - claudeCode: true, - mcpConnector: false, - claudeDesktop: true - } - }, { - name: "Figma", - category: "Design & Media", - description: "Generate better code by bringing in full Figma context", - documentation: "https://developers.figma.com", - urls: { - http: "https://mcp.figma.com/mcp" - }, - customCommands: { - claudeCode: "claude mcp add --transport http figma-remote-mcp https://mcp.figma.com/mcp" - }, - availability: { - claudeCode: true, - mcpConnector: false, - claudeDesktop: false - }, - notes: "Visit developers.figma.com for local server setup." - }, { - name: "Asana", - category: "Project Management & Documentation", - description: "Interact with your Asana workspace to keep projects on track", - documentation: "https://developers.asana.com/docs/using-asanas-model-control-protocol-mcp-server", - urls: { - sse: "https://mcp.asana.com/sse" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Atlassian", - category: "Project Management & Documentation", - description: "Manage your Jira tickets and Confluence docs", - documentation: "https://www.atlassian.com/platform/remote-mcp-server", - urls: { - sse: "https://mcp.atlassian.com/v1/sse" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "ClickUp", - category: "Project Management & Documentation", - description: "Task management, project tracking", - documentation: "https://github.com/hauptsacheNet/clickup-mcp", - urls: { - stdio: "npx -y @hauptsache.net/clickup-mcp" - }, - authentication: { - type: "api_key", - envVars: ["CLICKUP_API_KEY", "CLICKUP_TEAM_ID"] - }, - availability: { - claudeCode: true, - mcpConnector: false, - claudeDesktop: true - } - }, { - name: "Cloudflare", - category: "Infrastructure & DevOps", - description: "Build applications, analyze traffic, monitor performance, and manage security settings through Cloudflare", - documentation: "https://developers.cloudflare.com/agents/model-context-protocol/mcp-servers-for-cloudflare/", - urls: {}, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - }, - notes: "Multiple services available. See documentation for specific server URLs. Claude Code can use the Cloudflare CLI if installed." - }, { - name: "Cloudinary", - category: "Design & Media", - description: "Upload, manage, transform, and analyze your media assets", - documentation: "https://cloudinary.com/documentation/cloudinary_llm_mcp#mcp_servers", - urls: {}, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - }, - notes: "Multiple services available. See documentation for specific server URLs." - }, { - name: "Intercom", - category: "Project Management & Documentation", - description: "Access real-time customer conversations, tickets, and user data", - documentation: "https://developers.intercom.com/docs/guides/mcp", - urls: { - http: "https://mcp.intercom.com/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "invideo", - category: "Design & Media", - description: "Build video creation capabilities into your applications", - documentation: "https://invideo.io/ai/mcp", - urls: { - sse: "https://mcp.invideo.io/sse" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Linear", - category: "Project Management & Documentation", - description: "Integrate with Linear's issue tracking and project management", - documentation: "https://linear.app/docs/mcp", - urls: { - http: "https://mcp.linear.app/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Notion", - category: "Project Management & Documentation", - description: "Read docs, update pages, manage tasks", - documentation: "https://developers.notion.com/docs/mcp", - urls: { - http: "https://mcp.notion.com/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: false, - claudeDesktop: false - } - }, { - name: "PayPal", - category: "Payments & Commerce", - description: "Integrate PayPal commerce capabilities, payment processing, transaction management", - documentation: "https://www.paypal.ai/", - urls: { - http: "https://mcp.paypal.com/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Plaid", - category: "Payments & Commerce", - description: "Analyze, troubleshoot, and optimize Plaid integrations. Banking data, financial account linking", - documentation: "https://plaid.com/blog/plaid-mcp-ai-assistant-claude/", - urls: { - sse: "https://api.dashboard.plaid.com/mcp/sse" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Sentry", - category: "Development & Testing Tools", - description: "Monitor errors, debug production issues", - documentation: "https://docs.sentry.io/product/sentry-mcp/", - urls: { - http: "https://mcp.sentry.dev/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: false, - claudeDesktop: false - } - }, { - name: "Square", - category: "Payments & Commerce", - description: "Use an agent to build on Square APIs. Payments, inventory, orders, and more", - documentation: "https://developer.squareup.com/docs/mcp", - urls: { - sse: "https://mcp.squareup.com/sse" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Socket", - category: "Development & Testing Tools", - description: "Security analysis for dependencies", - documentation: "https://github.com/SocketDev/socket-mcp", - urls: { - http: "https://mcp.socket.dev/" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: false, - claudeDesktop: false - } - }, { - name: "Stripe", - category: "Payments & Commerce", - description: "Payment processing, subscription management, and financial transactions", - documentation: "https://docs.stripe.com/mcp", - urls: { - http: "https://mcp.stripe.com" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Workato", - category: "Automation & Integration", - description: "Access any application, workflows or data via Workato, made accessible for AI", - documentation: "https://docs.workato.com/mcp.html", - urls: {}, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - }, - notes: "MCP servers are programmatically generated" - }, { - name: "Zapier", - category: "Automation & Integration", - description: "Connect to nearly 8,000 apps through Zapier's automation platform", - documentation: "https://help.zapier.com/hc/en-us/articles/36265392843917", - urls: {}, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - }, - notes: "Generate a user-specific URL at mcp.zapier.com" - }, { - name: "Box", - category: "Project Management & Documentation", - description: "Ask questions about your enterprise content, get insights from unstructured data, automate content workflows", - documentation: "https://box.dev/guides/box-mcp/remote/", - urls: { - http: "https://mcp.box.com/" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Canva", - category: "Design & Media", - description: "Browse, summarize, autofill, and even generate new Canva designs directly from Claude", - documentation: "https://www.canva.dev/docs/connect/canva-mcp-server-setup/", - urls: { - http: "https://mcp.canva.com/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Daloopa", - category: "Databases & Data Management", - description: "Supplies high quality fundamental financial data sourced from SEC Filings, investor presentations", - documentation: "https://docs.daloopa.com/docs/daloopa-mcp", - urls: { - http: "https://mcp.daloopa.com/server/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Fireflies", - category: "Project Management & Documentation", - description: "Extract valuable insights from meeting transcripts and summaries", - documentation: "https://guide.fireflies.ai/articles/8272956938-learn-about-the-fireflies-mcp-server-model-context-protocol", - urls: { - http: "https://api.fireflies.ai/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "HubSpot", - category: "Databases & Data Management", - description: "Access and manage HubSpot CRM data by fetching contacts, companies, and deals, and creating and updating records", - documentation: "https://developers.hubspot.com/mcp", - urls: { - http: "https://mcp.hubspot.com/anthropic" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Hugging Face", - category: "Development & Testing Tools", - description: "Provides access to Hugging Face Hub information and Gradio AI Applications", - documentation: "https://huggingface.co/settings/mcp", - urls: { - http: "https://huggingface.co/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Jam", - category: "Development & Testing Tools", - description: "Debug faster with AI agents that can access Jam recordings like video, console logs, network requests, and errors", - documentation: "https://jam.dev/docs/debug-a-jam/mcp", - urls: { - http: "https://mcp.jam.dev/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Monday", - category: "Project Management & Documentation", - description: "Manage monday.com boards by creating items, updating columns, assigning owners, setting timelines, adding CRM activities, and writing summaries", - documentation: "https://developer.monday.com/apps/docs/mondaycom-mcp-integration", - urls: { - sse: "https://mcp.monday.com/sse" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Netlify", - category: "Infrastructure & DevOps", - description: "Create, deploy, and manage websites on Netlify. Control all aspects of your site from creating secrets to enforcing access controls to aggregating form submissions", - documentation: "https://docs.netlify.com/build/build-with-ai/netlify-mcp-server/", - urls: { - http: "https://netlify-mcp.netlify.app/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Stytch", - category: "Infrastructure & DevOps", - description: "Configure and manage Stytch authentication services, redirect URLs, email templates, and workspace settings", - documentation: "https://stytch.com/docs/workspace-management/stytch-mcp", - urls: { - http: "http://mcp.stytch.dev/mcp" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }, { - name: "Vercel", - category: "Infrastructure & DevOps", - description: "Vercel's official MCP server, allowing you to search and navigate documentation, manage projects and deployments, and analyze deployment logs—all in one place", - documentation: "https://vercel.com/docs/mcp/vercel-mcp", - urls: { - http: "https://mcp.vercel.com/" - }, - authentication: { - type: "oauth" - }, - availability: { - claudeCode: true, - mcpConnector: true, - claudeDesktop: false - } - }]; + 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; @@ -504,14 +124,6 @@ export const MCPServersTable = ({platform = "all"}) => { throw new Error(`Unknown platform: ${platform}`); } }); - const serversByCategory = filteredServers.reduce((acc, server) => { - if (!acc[server.category]) { - acc[server.category] = []; - } - acc[server.category].push(server); - return acc; - }, {}); - const categoryOrder = ["Development & Testing Tools", "Project Management & Documentation", "Databases & Data Management", "Payments & Commerce", "Design & Media", "Infrastructure & DevOps", "Automation & Integration"]; return <> - - {categoryOrder.map(category => { - if (!serversByCategory[category]) return null; - return
-

{category}

-
- {serversByCategory[category].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.notes && - {server.notes} - } -

- - {commandToShow && <> -

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

-
- - {commandToShow} - -
- } -
; - })} -
-
; + +
+ {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. +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 @@ -600,7 +211,7 @@ 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 Postgres database." +* **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." @@ -710,9 +321,9 @@ claude mcp remove github * `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 (e.g., `--env KEY=value`) - * Configure MCP server startup timeout using the MCP\_TIMEOUT environment variable (e.g., `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 (e.g., `MAX_MCP_OUTPUT_TOKENS=50000`) + * 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 @@ -729,7 +340,7 @@ claude mcp remove github ### Plugin-provided MCP servers -[Plugins](/en/docs/claude-code/plugins) can bundle MCP servers, automatically providing tools and integrations when the plugin is enabled. Plugin MCP servers work identically to user-configured 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**: @@ -790,7 +401,7 @@ Plugin servers appear in the list with indicators showing they come from plugins * **Automatic setup**: No manual MCP configuration needed * **Team consistency**: Everyone gets the same tools when plugin is installed -See the [plugin components reference](/en/docs/claude-code/plugins-reference#mcp-servers) for details on bundling MCP servers with plugins. +See the [plugin components reference](/en/plugins-reference#mcp-servers) for details on bundling MCP servers with plugins. ## MCP installation scopes @@ -798,7 +409,7 @@ MCP servers can be configured at three different scope levels, each serving dist ### Local scope -Local-scoped servers represent the default configuration level and are stored in your project-specific user settings. 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. +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. ```bash theme={null} # Add a local-scoped server (default) @@ -835,7 +446,7 @@ For security reasons, Claude Code prompts for approval before using project-scop ### User scope -User-scoped servers 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. +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 @@ -848,7 +459,15 @@ 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 +* **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) + * **Enterprise managed**: `managed-mcp.json` in system directories (see [Enterprise MCP configuration](#enterprise-mcp-configuration)) + ### Scope hierarchy and precedence @@ -1044,7 +663,7 @@ If you've already configured MCP servers in Claude Desktop, you can import them: * 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 (e.g., `server_1`) + * 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 @@ -1071,12 +690,39 @@ You can use this in Claude Desktop by adding this configuration to claude\_deskt } ``` + + **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 simply exposing Claude Code's tools to your MCP client, so your own client is responsible for implementing user confirmation for individual tool calls. + * 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 @@ -1195,11 +841,7 @@ For organizations that need centralized control over MCP servers, Claude Code su ### Setting up enterprise MCP configuration -System administrators can deploy an enterprise MCP configuration file alongside the managed settings file: - -* **macOS**: `/Library/Application Support/ClaudeCode/managed-mcp.json` -* **Windows**: `C:\ProgramData\ClaudeCode\managed-mcp.json` -* **Linux**: `/etc/claude-code/managed-mcp.json` +System administrators can deploy an enterprise MCP configuration file alongside the managed settings file. See [settings files](/en/settings#settings-files) for the `managed-mcp.json` file locations on each platform. The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file: @@ -1228,42 +870,134 @@ The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file: ### Restricting MCP servers with allowlists and denylists -In addition to providing enterprise-managed servers, administrators can control which MCP servers users are allowed to configure using `allowedMcpServers` and `deniedMcpServers` in the `managed-settings.json` file: +In addition to providing enterprise-managed servers, administrators can control which MCP servers users are allowed to configure using `allowedMcpServers` and `deniedMcpServers` in the [managed settings file](/en/settings#settings-files): + +#### Restriction options + +Each entry in the allowlist or denylist can restrict servers in two 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 + +**Important**: Each entry must have **either** `serverName` **or** `serverCommand`, not both. -* **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json` -* **Windows**: `C:\ProgramData\ClaudeCode\managed-settings.json` -* **Linux**: `/etc/claude-code/managed-settings.json` +#### Example configuration ```json theme={null} { "allowedMcpServers": [ + // Allow by server name { "serverName": "github" }, { "serverName": "sentry" }, - { "serverName": "company-internal" } + + // Allow by exact command (for stdio servers) + { "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] }, + { "serverCommand": ["python", "/usr/local/bin/approved-server.py"] } ], "deniedMcpServers": [ - { "serverName": "filesystem" } + // Block by server name + { "serverName": "dangerous-server" }, + + // Block by exact command (for stdio servers) + { "serverCommand": ["npx", "-y", "unapproved-package"] } ] } ``` -**Allowlist behavior (`allowedMcpServers`)**: +#### 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) always match by name only +* Command restrictions do not apply to remote servers + + + ```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 server names: Users can only configure the specified servers +* List of entries: Users can only configure servers that match by name or command -**Denylist behavior (`deniedMcpServers`)**: +#### Denylist behavior (`deniedMcpServers`) * `undefined` (default): No servers are blocked * Empty array `[]`: No servers are blocked -* List of server names: Specified servers are explicitly blocked across all scopes +* List of entries: Specified servers are explicitly blocked across all scopes -**Important notes**: +#### Important notes * These restrictions apply to all scopes: user, project, local, and even enterprise servers from `managed-mcp.json` -* **Denylist takes absolute precedence**: If a server appears in both lists, it will be blocked +* **Denylist takes absolute precedence**: If a server matches a denylist entry (by name or command), it will be blocked even if it's on the allowlist +* Name-based and command-based restrictions work together: a server passes if it matches **either** a name entry **or** a command entry (unless blocked by denylist) - **Enterprise configuration precedence**: The enterprise MCP configuration has the highest precedence and cannot be overridden by user, local, or project configurations when `useEnterpriseMcpConfigOnly` is enabled. + **Enterprise configuration precedence**: The enterprise MCP configuration has the highest precedence and cannot be overridden by user, local, or project configurations. + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/memory.md b/skills/working-with-claude-code/references/memory.md index 5ba725e..738c464 100644 --- a/skills/working-with-claude-code/references/memory.md +++ b/skills/working-with-claude-code/references/memory.md @@ -8,15 +8,20 @@ Claude Code can remember your preferences across sessions, like style guidelines Claude Code offers four memory locations in a hierarchical structure, each serving a different purpose: -| Memory Type | Location | Purpose | Use Case Examples | Shared With | -| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- | -| **Enterprise policy** | macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`
Linux: `/etc/claude-code/CLAUDE.md`
Windows: `C:\ProgramData\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 | -| **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 | *(Deprecated, see below)* Your sandbox URLs, preferred test data | Just you (current project) | +| Memory Type | Location | Purpose | Use Case Examples | Shared With | +| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- | +| **Enterprise 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: @@ -28,7 +33,7 @@ See @README for project overview and @package.json for available npm commands fo - git workflow @docs/git-instructions.md ``` -Both relative and absolute paths are allowed. In particular, importing files in user's home dir is a convenient way for your team members to provide individual instructions that are not checked into the repository. Previously CLAUDE.local.md served a similar purpose, but is now deprecated in favor of imports since they work better across multiple git worktrees. +Both relative and absolute paths are allowed. In particular, importing files in user's home dir is a convenient way for your team members to provide individual instructions that are not checked into the repository. Imports are an alternative to CLAUDE.local.md that work better across multiple git worktrees. ``` # Individual Preferences @@ -70,7 +75,7 @@ Suppose you want to set up a CLAUDE.md file to store important project informati Bootstrap a CLAUDE.md for your codebase with the following command: ``` -> /init +> /init ``` @@ -82,17 +87,132 @@ Bootstrap a CLAUDE.md for your codebase with the following command: * 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 use braces to match multiple patterns efficiently: + +```markdown theme={null} +--- +paths: src/**/*.{ts,tsx} +--- + +# TypeScript/React Rules +``` + +This expands to match both `src/**/*.ts` and `src/**/*.tsx`. You can also combine multiple patterns with commas: + +```markdown theme={null} +--- +paths: {src,lib}/**/*.ts, tests/**/*.test.ts +--- +``` + +### 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 Enterprise organizations can deploy centrally managed CLAUDE.md files that apply to all users. To set up organization-level memory management: -1. Create the enterprise memory file in the appropriate location for your operating system: - -* macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md` -* Linux/WSL: `/etc/claude-code/CLAUDE.md` -* Windows: `C:\ProgramData\ClaudeCode\CLAUDE.md` +1. Create the enterprise memory file at the **Enterprise 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. @@ -101,3 +221,8 @@ To set up organization-level memory management: * **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. + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/microsoft-foundry.md b/skills/working-with-claude-code/references/microsoft-foundry.md new file mode 100644 index 0000000..3322333 --- /dev/null +++ b/skills/working-with-claude-code/references/microsoft-foundry.md @@ -0,0 +1,112 @@ +# 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 + +# 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/) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/model-config.md b/skills/working-with-claude-code/references/model-config.md index 52b297a..2e7fbbd 100644 --- a/skills/working-with-claude-code/references/model-config.md +++ b/skills/working-with-claude-code/references/model-config.md @@ -4,25 +4,28 @@ ## Available models -For the `model` setting in Claude Code, you can either configure: +For the `model` setting in Claude Code, you can configure either: * A **model alias** -* A full **[model name](/en/docs/about-claude/models/overview#model-names)** -* For Bedrock, an ARN +* 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.1) 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](/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 | +| 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 @@ -80,7 +83,7 @@ and Sonnet's efficiency for execution. For Console/API users, the `[1m]` suffix can be added to full model names to enable a -[1 million token context window](/en/docs/build-with-claude/context-windows#1m-token-context-window). +[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 @@ -88,35 +91,35 @@ enable a ``` Note: Extended context models have -[different pricing](/en/docs/about-claude/pricing#long-context-pricing). +[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/docs/claude-code/statusline) (if configured) +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**, to control the model names that the aliases map to. +names** (or equivalent for your API provider), to control the model names that the aliases map to. -| Env var | 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/docs/claude-code/costs#background-token-usage) | -| `CLAUDE_CODE_SUBAGENT_MODEL` | The model to use for [subagents](/en/docs/claude-code/sub-agents) | +| 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](/en/docs/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers: +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: -| Env var | Description | +| 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 | @@ -124,3 +127,8 @@ Claude Code automatically uses [prompt caching](/en/docs/build-with-claude/promp | `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. + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/monitoring-usage.md b/skills/working-with-claude-code/references/monitoring-usage.md index cb64cae..6f142a8 100644 --- a/skills/working-with-claude-code/references/monitoring-usage.md +++ b/skills/working-with-claude-code/references/monitoring-usage.md @@ -6,11 +6,7 @@ Claude Code supports OpenTelemetry (OTel) metrics and events for monitoring and 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. - - OpenTelemetry support is currently in beta and details are subject to change. - - -## Quick Start +## Quick start Configure OpenTelemetry using environment variables: @@ -43,15 +39,9 @@ claude 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. This allows for centralized control of telemetry settings across an organization. See the [settings precedence](/en/docs/claude-code/settings#settings-precedence) for more information about how settings are applied. +## Administrator configuration -The managed settings file is located at: - -* macOS: `/Library/Application Support/ClaudeCode/managed-settings.json` -* Linux and WSL: `/etc/claude-code/managed-settings.json` -* Windows: `C:\ProgramData\ClaudeCode\managed-settings.json` +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: @@ -72,9 +62,9 @@ Example managed settings configuration: 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 +## Configuration details -### Common Configuration Variables +### Common configuration variables | Environment Variable | Description | Example Values | | ----------------------------------------------- | --------------------------------------------------------- | ------------------------------------ | @@ -94,7 +84,7 @@ Example managed settings configuration: | `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 | -### Metrics Cardinality Control +### Metrics cardinality control The following environment variables control which attributes are included in metrics to manage cardinality: @@ -106,11 +96,11 @@ The following environment variables control which attributes are included in met 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 +### Dynamic headers For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically: -#### Settings Configuration +#### Settings configuration Add to your `.claude/settings.json`: @@ -120,7 +110,7 @@ Add to your `.claude/settings.json`: } ``` -#### Script Requirements +#### Script requirements The script must output valid JSON with string key-value pairs representing HTTP headers: @@ -130,13 +120,13 @@ The script must output valid JSON with string key-value pairs representing HTTP echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}" ``` -#### Important Limitations +#### Important limitations **Headers are fetched only at startup, not during runtime.** This is due to OpenTelemetry exporter architecture limitations. For scenarios requiring frequent token refresh, use an OpenTelemetry Collector as a proxy that can refresh its own headers. -### Multi-Team Organization Support +### 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: @@ -176,10 +166,10 @@ These custom attributes will be included in all metrics and events, allowing you export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization" ``` - Note: Quoting the entire key=value pair (e.g., `"key=value with spaces"`) is not supported by the OpenTelemetry specification and will result in attributes being prefixed with quotes. + 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 +### Example configurations ```bash theme={null} # Console debugging (1-second intervals) @@ -224,19 +214,19 @@ export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 ``` -## Available Metrics and Events +## Available metrics and events -### Standard Attributes +### 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 (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected | +| 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 @@ -253,9 +243,9 @@ Claude Code exports the following metrics: | `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 +### Metric details -#### Session Counter +#### Session counter Incremented at the start of each session. @@ -263,7 +253,7 @@ Incremented at the start of each session. * All [standard attributes](#standard-attributes) -#### Lines of Code Counter +#### Lines of code counter Incremented when code is added or removed. @@ -272,7 +262,7 @@ Incremented when code is added or removed. * All [standard attributes](#standard-attributes) * `type`: (`"added"`, `"removed"`) -#### Pull Request Counter +#### Pull request counter Incremented when creating pull requests via Claude Code. @@ -280,7 +270,7 @@ Incremented when creating pull requests via Claude Code. * All [standard attributes](#standard-attributes) -#### Commit Counter +#### Commit counter Incremented when creating git commits via Claude Code. @@ -288,16 +278,16 @@ Incremented when creating git commits via Claude Code. * All [standard attributes](#standard-attributes) -#### Cost Counter +#### Cost counter Incremented after each API request. **Attributes**: * All [standard attributes](#standard-attributes) -* `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022") +* `model`: Model identifier (for example, "claude-sonnet-4-5-20250929") -#### Token Counter +#### Token counter Incremented after each API request. @@ -305,9 +295,9 @@ Incremented after each API request. * All [standard attributes](#standard-attributes) * `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`) -* `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022") +* `model`: Model identifier (for example, "claude-sonnet-4-5-20250929") -#### Code Edit Tool Decision Counter +#### Code edit tool decision counter Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage. @@ -316,9 +306,9 @@ Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage * All [standard attributes](#standard-attributes) * `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`) * `decision`: User decision (`"accept"`, `"reject"`) -* `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions. +* `language`: Programming language of the edited file (for example, `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions. -#### Active Time Counter +#### 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. @@ -330,7 +320,7 @@ Tracks actual time spent actively using Claude Code (not idle time). This metric Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured): -#### User Prompt Event +#### User prompt event Logged when a user submits a prompt. @@ -344,7 +334,7 @@ Logged when a user submits a prompt. * `prompt_length`: Length of the prompt * `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`) -#### Tool Result Event +#### Tool result event Logged when a tool completes execution. @@ -364,7 +354,7 @@ Logged when a tool completes execution. * `tool_parameters`: JSON string containing tool-specific parameters (when available) * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox` -#### API Request Event +#### API request event Logged for each API request to Claude. @@ -375,7 +365,7 @@ Logged for each API request to Claude. * All [standard attributes](#standard-attributes) * `event.name`: `"api_request"` * `event.timestamp`: ISO 8601 timestamp -* `model`: Model used (e.g., "claude-3-5-sonnet-20241022") +* `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 @@ -383,7 +373,7 @@ Logged for each API request to Claude. * `cache_read_tokens`: Number of tokens read from cache * `cache_creation_tokens`: Number of tokens used for cache creation -#### API Error Event +#### API error event Logged when an API request to Claude fails. @@ -394,13 +384,13 @@ Logged when an API request to Claude fails. * All [standard attributes](#standard-attributes) * `event.name`: `"api_error"` * `event.timestamp`: ISO 8601 timestamp -* `model`: Model used (e.g., "claude-3-5-sonnet-20241022") +* `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 +#### Tool decision event Logged when a tool permission decision is made (accept/reject). @@ -411,15 +401,15 @@ Logged when a tool permission decision is made (accept/reject). * All [standard attributes](#standard-attributes) * `event.name`: `"tool_decision"` * `event.timestamp`: ISO 8601 timestamp -* `tool_name`: Name of the tool (e.g., "Read", "Edit", "Write", "NotebookEdit", etc.) +* `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 +## 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 +### Usage monitoring | Metric | Analysis Opportunity | | ------------------------------------------------------------- | --------------------------------------------------------- | @@ -428,7 +418,7 @@ The metrics exported by Claude Code provide valuable insights into usage pattern | `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 +### Cost monitoring The `claude_code.cost.usage` metric helps with: @@ -439,7 +429,7 @@ The `claude_code.cost.usage` metric helps with: Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex). -### Alerting and Segmentation +### Alerting and segmentation Common alerts to consider: @@ -449,54 +439,54 @@ Common alerts to consider: All metrics can be segmented by `user.account_uuid`, `organization.id`, `session.id`, `model`, and `app.version`. -### Event Analysis +### Event analysis The event data provides detailed insights into Claude Code interactions: -**Tool Usage Patterns**: Analyze tool result events to identify: +**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. +**Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks. -## Backend Considerations +## Backend considerations -Your choice of metrics and logs backends will determine the types of analyses you can perform: +Your choice of metrics and logs backends determines the types of analyses you can perform: -### For Metrics: +### For metrics -* **Time series databases (e.g., Prometheus)**: Rate calculations, aggregated metrics -* **Columnar stores (e.g., ClickHouse)**: Complex queries, unique user analysis -* **Full-featured observability platforms (e.g., Honeycomb, Datadog)**: Advanced querying, visualization, alerting +* **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: +### For events/logs -* **Log aggregation systems (e.g., Elasticsearch, Loki)**: Full-text search, log analysis -* **Columnar stores (e.g., ClickHouse)**: Structured event analysis -* **Full-featured observability platforms (e.g., Honeycomb, Datadog)**: Correlation between metrics and events +* **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 +## 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 (e.g., `linux`, `darwin`, `windows`) +* `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`) * `os.version`: Operating system version string -* `host.arch`: Host architecture (e.g., `amd64`, `arm64`) +* `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 +## 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 +## 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 @@ -505,3 +495,8 @@ For a comprehensive guide on measuring return on investment for Claude Code, inc ## 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). + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/network-config.md b/skills/working-with-claude-code/references/network-config.md index 11a7622..36bb027 100644 --- a/skills/working-with-claude-code/references/network-config.md +++ b/skills/working-with-claude-code/references/network-config.md @@ -5,7 +5,7 @@ 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/docs/claude-code/settings). + All environment variables shown on this page can also be configured in [`settings.json`](/en/settings). ## Proxy configuration @@ -85,6 +85,11 @@ Ensure these URLs are allowlisted in your proxy configuration and firewall rules ## Additional resources -* [Claude Code settings](/en/docs/claude-code/settings) -* [Environment variables reference](/en/docs/claude-code/settings#environment-variables) -* [Troubleshooting guide](/en/docs/claude-code/troubleshooting) +* [Claude Code settings](/en/settings) +* [Environment variables reference](/en/settings#environment-variables) +* [Troubleshooting guide](/en/troubleshooting) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/output-styles.md b/skills/working-with-claude-code/references/output-styles.md index ebee16e..00159db 100644 --- a/skills/working-with-claude-code/references/output-styles.md +++ b/skills/working-with-claude-code/references/output-styles.md @@ -27,33 +27,33 @@ codebase and how Claude operates: Output styles directly modify Claude Code's system prompt. -* Non-default output styles exclude instructions specific to code generation and - efficient output normally built into Claude Code (such as responding concisely - and verifying code with tests). -* Instead, these output styles have their own custom instructions added to the +* 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 the menu and select your output style (this can +* 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/docs/claude-code/settings) -and are saved in `.claude/settings.local.json`. +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 -To set up a new output style with Claude's help, run -`/output-style:new I want an output style that ...` - -By default, output styles created through `/output-style:new` are saved as -markdown files at the user level in `~/.claude/output-styles` and can be used -across projects. They have the following structure: +Custom output styles are Markdown files with frontmatter and the text that will +be added to the system prompt: ```markdown theme={null} --- @@ -72,28 +72,43 @@ tasks. [Your custom instructions here...] [Define how the assistant should behave in this style...] ``` -You can also create your own output style Markdown files and save them either at -the user level (`~/.claude/output-styles`) or the project level -(`.claude/output-styles`). +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 +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 +`--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/docs/claude-code/sub-agents) +### 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. [Custom Slash Commands](/en/docs/claude-code/slash-commands) +### Output Styles vs. [Custom Slash Commands](/en/slash-commands) + +You can think of output styles as "stored system prompts" and custom slash +commands as "stored prompts". + + +--- -You can think of output styles as “stored system prompts” and custom slash -commands as “stored prompts”. +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/overview.md b/skills/working-with-claude-code/references/overview.md index b84b47e..872252c 100644 --- a/skills/working-with-claude-code/references/overview.md +++ b/skills/working-with-claude-code/references/overview.md @@ -6,59 +6,81 @@ Prerequisites: -* [Node.js 18 or newer](https://nodejs.org/en/download/) * A [Claude.ai](https://claude.ai) (recommended) or [Claude Console](https://console.anthropic.com/) account -```bash theme={null} -# Install Claude Code -npm install -g @anthropic-ai/claude-code +**Install Claude Code:** + + + + ```bash theme={null} + curl -fsSL https://claude.ai/install.sh | bash + ``` + + + + ```bash theme={null} + brew install --cask claude-code + ``` + + + + ```powershell theme={null} + irm https://claude.ai/install.ps1 | iex + ``` + -# Navigate to your project -cd your-awesome-project + + ```bash theme={null} + npm install -g @anthropic-ai/claude-code + ``` -# Start coding with Claude + Requires [Node.js 18+](https://nodejs.org/en/download/) + + + +**Start using Claude Code:** + +```bash theme={null} +cd your-project claude -# You'll be prompted to log in on first use ``` -That's it! You're ready to start coding with Claude. [Continue with Quickstart (5 mins) →](/en/docs/claude-code/quickstart) +You'll be prompted to log in on first use. That's it! [Continue with Quickstart (5 minutes) →](/en/quickstart) -(Got specific setup needs or hit issues? See [advanced setup](/en/docs/claude-code/setup) or [troubleshooting](/en/docs/claude-code/troubleshooting).) - - - **New VS Code Extension (Beta)**: Prefer a graphical interface? Our new [VS Code extension](/en/docs/claude-code/vs-code) provides an easy-to-use native IDE experience without requiring terminal familiarity. Simply install from the marketplace and start coding with Claude directly in your sidebar. - + + Claude Code automatically keeps itself up to date. 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/docs/claude-code/mcp) can pull from external datasources like Google Drive, Figma, and Slack. +* **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/docs/claude-code/mcp) lets Claude read your design docs in Google Drive, update your tickets in Jira, or use *your* custom developer tooling. +* **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/docs/claude-code/security), [privacy](/en/docs/claude-code/data-usage), and [compliance](https://trust.anthropic.com/) is built-in. +* **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. ## Next steps - + See Claude Code in action with practical examples - + Step-by-step guides for common workflows - + Solutions for common issues with Claude Code - + Add Claude Code to your IDE @@ -66,15 +88,19 @@ That's it! You're ready to start coding with Claude. [Continue with Quickstart ( ## Additional resources - + + 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 @@ -82,11 +108,16 @@ That's it! You're ready to start coding with Claude. [Continue with Quickstart ( Clone our development container reference implementation - + Discover Claude Code's safeguards and best practices for safe usage - + Understand how Claude Code handles your data + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/plugin-marketplaces.md b/skills/working-with-claude-code/references/plugin-marketplaces.md index 4d65bdf..fe97f17 100644 --- a/skills/working-with-claude-code/references/plugin-marketplaces.md +++ b/skills/working-with-claude-code/references/plugin-marketplaces.md @@ -69,6 +69,14 @@ After adding a marketplace: 2. **Browse plugins**: Use `/plugin` to see available plugins from your marketplace 3. **Test installation**: Try installing a plugin to verify the marketplace works correctly +### Example plugin marketplace + +Claude Code maintains a marketplace of [demo plugins](https://github.com/anthropics/claude-code/tree/main/plugins). These plugins are examples of what's possible with the plugin system. + +```shell Add the marketplace theme={null} +/plugin marketplace add anthropics/claude-code +``` + ## Configure team marketplaces Set up automatic marketplace installation for team projects by specifying required marketplaces in `.claude/settings.json`: @@ -160,7 +168,9 @@ Create `.claude-plugin/marketplace.json` in your repository root: ### Plugin entries - Plugin entries are based on the *plugin manifest schema* (with all fields made optional) plus marketplace-specific fields (`source`, `category`, `tags`, `strict`), with `name` being required. + Plugin entries are based on the *plugin manifest schema* (with all fields made + optional) plus marketplace-specific fields (`source`, `category`, `tags`, + `strict`), with `name` being required. **Required fields:** @@ -181,7 +191,7 @@ Create `.claude-plugin/marketplace.json` in your repository root: | `author` | object | Plugin author information | | `homepage` | string | Plugin homepage or documentation URL | | `repository` | string | Source code repository URL | -| `license` | string | SPDX license identifier (e.g., MIT, Apache-2.0) | +| `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 | @@ -237,7 +247,7 @@ For plugins in the same repository: #### Advanced plugin entries -Plugin entries can override default component locations and provide additional metadata. Note that `${CLAUDE_PLUGIN_ROOT}` is an environment variable that resolves to the plugin's installation directory (for details see [Environment variables](/en/docs/claude-code/plugins-reference#environment-variables)): +Plugin entries can override default component locations and provide additional metadata. Note that `${CLAUDE_PLUGIN_ROOT}` is an environment variable that resolves to the plugin's installation directory (for details see [Environment variables](/en/plugins-reference#environment-variables)): ```json theme={null} { @@ -262,15 +272,17 @@ Plugin entries can override default component locations and provide additional m "./commands/enterprise/", "./commands/experimental/preview.md" ], - "agents": [ - "./agents/security-reviewer.md", - "./agents/compliance-checker.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"}] + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh" + } + ] } ] }, @@ -285,7 +297,13 @@ Plugin entries can override default component locations and provide additional m ``` - **Schema relationship**: Plugin entries use the plugin manifest schema with all fields made optional, plus marketplace-specific fields (`source`, `strict`, `category`, `tags`). This means any field valid in a `plugin.json` file can also be used in a marketplace entry. When `strict: false`, the marketplace entry serves as the complete plugin manifest if no `plugin.json` exists. When `strict: true` (default), marketplace fields supplement the plugin's own manifest file. + **Schema relationship**: Plugin entries use the plugin manifest schema with + all fields made optional, plus marketplace-specific fields (`source`, + `strict`, `category`, `tags`). This means any field valid in a `plugin.json` + file can also be used in a marketplace entry. When `strict: false`, the + marketplace entry serves as the complete plugin manifest if no `plugin.json` + exists. When `strict: true` (default), marketplace fields supplement the + plugin's own manifest file. *** @@ -400,7 +418,7 @@ claude plugin validate . /plugin install test-plugin@marketplace-name ``` -For complete plugin testing workflows, see [Test your plugins locally](/en/docs/claude-code/plugins#test-your-plugins-locally). For technical troubleshooting, see [Plugins reference](/en/docs/claude-code/plugins-reference). +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). *** @@ -427,7 +445,12 @@ For complete plugin testing workflows, see [Test your plugins locally](/en/docs/ ## See also -* [Plugins](/en/docs/claude-code/plugins) - Installing and using plugins -* [Plugins reference](/en/docs/claude-code/plugins-reference) - Complete technical specifications and schemas -* [Plugin development](/en/docs/claude-code/plugins#develop-more-complex-plugins) - Creating your own plugins -* [Settings](/en/docs/claude-code/settings#plugin-configuration) - Plugin configuration options +* [Plugins](/en/plugins) - Installing and using plugins +* [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas +* [Plugin development](/en/plugins#develop-more-complex-plugins) - Creating your own plugins +* [Settings](/en/settings#plugin-configuration) - Plugin configuration options + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/plugins-reference.md b/skills/working-with-claude-code/references/plugins-reference.md index e44ffb7..eb34dbc 100644 --- a/skills/working-with-claude-code/references/plugins-reference.md +++ b/skills/working-with-claude-code/references/plugins-reference.md @@ -3,7 +3,7 @@ > Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications. - For hands-on tutorials and practical usage, see [Plugins](/en/docs/claude-code/plugins). For plugin management across teams and communities, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces). + For hands-on tutorials and practical usage, see [Plugins](/en/plugins). For plugin management across teams and communities, 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. @@ -20,7 +20,7 @@ Plugins add custom slash commands that integrate seamlessly with Claude Code's c **File format**: Markdown files with frontmatter -For complete details on plugin command structure, invocation patterns, and features, see [Plugin commands](/en/docs/claude-code/slash-commands#plugin-commands). +For complete details on plugin command structure, invocation patterns, and features, see [Plugin commands](/en/slash-commands#plugin-commands). ### Agents @@ -86,8 +86,8 @@ skills/ For SKILL.md format and complete Skill authoring guidance, see: -* [Use Skills in Claude Code](/en/docs/claude-code/skills) -* [Agent Skills overview](/en/docs/agents-and-tools/agent-skills/overview#skill-structure) +* [Use Skills in Claude Code](/en/skills) +* [Agent Skills overview](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview#skill-structure) ### Hooks @@ -120,6 +120,7 @@ Plugins can provide event handlers that respond to Claude Code events automatica **Available events**: * `PreToolUse`: Before Claude uses any tool +* `PermissionRequest`: When a permission dialog is shown * `PostToolUse`: After Claude uses any tool * `UserPromptSubmit`: When user submits a prompt * `Notification`: When Claude Code sends notifications @@ -225,7 +226,7 @@ The `plugin.json` file defines your plugin's metadata and configuration. This se | `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` | | `agents` | string\|array | Additional agent files | `"./custom/agents/"` | | `hooks` | string\|object | Hook config path or inline config | `"./hooks.json"` | -| `mcpServers` | string\|object | MCP config path or inline config | `"./mcp.json"` | +| `mcpServers` | string\|object | MCP config path or inline config | `"./custom-mcp-config.json"` | ### Path behavior rules @@ -365,12 +366,17 @@ Follow semantic versioning for plugin releases: ## See also -- [Plugins](/en/docs/claude-code/plugins) - Tutorials and practical usage -- [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces) - Creating and managing marketplaces -- [Slash commands](/en/docs/claude-code/slash-commands) - Command development details -- [Subagents](/en/docs/claude-code/sub-agents) - Agent configuration and capabilities -- [Agent Skills](/en/docs/claude-code/skills) - Extend Claude's capabilities -- [Hooks](/en/docs/claude-code/hooks) - Event handling and automation -- [MCP](/en/docs/claude-code/mcp) - External tool integration -- [Settings](/en/docs/claude-code/settings) - Configuration options for plugins +- [Plugins](/en/plugins) - Tutorials and practical usage +- [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing marketplaces +- [Slash commands](/en/slash-commands) - Command development details +- [Subagents](/en/sub-agents) - Agent configuration and capabilities +- [Agent Skills](/en/skills) - Extend Claude's capabilities +- [Hooks](/en/hooks) - Event handling and automation +- [MCP](/en/mcp) - External tool integration +- [Settings](/en/settings) - Configuration options for plugins ``` + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/plugins.md b/skills/working-with-claude-code/references/plugins.md index e73cc7b..eaf4802 100644 --- a/skills/working-with-claude-code/references/plugins.md +++ b/skills/working-with-claude-code/references/plugins.md @@ -1,12 +1,12 @@ # Plugins -> Extend Claude Code with custom commands, agents, hooks, and MCP servers through the plugin system. +> Extend Claude Code with custom commands, agents, hooks, Skills, and MCP servers through the plugin system. - For complete technical specifications and schemas, see [Plugins reference](/en/docs/claude-code/plugins-reference). For marketplace management, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces). + For complete technical specifications and schemas, see [Plugins reference](/en/plugins-reference). For marketplace management, see [Plugin marketplaces](/en/plugin-marketplaces). -Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. Install plugins from [marketplaces](/en/docs/claude-code/plugin-marketplaces) to add pre-built commands, agents, hooks, and MCP servers, or create your own to automate your workflows. +Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. Install plugins from [marketplaces](/en/plugin-marketplaces) to add pre-built commands, agents, hooks, Skills, and MCP servers, or create your own to automate your workflows. ## Quickstart @@ -145,7 +145,7 @@ my-first-plugin/ * **MCP servers**: Create `.mcp.json` for external tool integration - **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, and MCP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/docs/claude-code/plugins-reference). + **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, and MCP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/plugins-reference). *** @@ -171,7 +171,7 @@ Marketplaces are catalogs of available plugins. Add them to discover and install /plugin ``` -For detailed marketplace management including Git repositories, local development, and team distribution, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces). +For detailed marketplace management including Git repositories, local development, and team distribution, see [Plugin marketplaces](/en/plugin-marketplaces). ### Install plugins @@ -219,7 +219,7 @@ Configure plugins at the repository level to ensure consistent tooling across yo 2. Team members trust the repository folder 3. Plugins install automatically for all team members -For complete instructions including configuration examples, marketplace setup, and rollout best practices, see [Configure team marketplaces](/en/docs/claude-code/plugin-marketplaces#how-to-configure-team-marketplaces). +For complete instructions including configuration examples, marketplace setup, and rollout best practices, see [Configure team marketplaces](/en/plugin-marketplaces#how-to-configure-team-marketplaces). *** @@ -229,15 +229,15 @@ Once you're comfortable with basic plugins, you can create more sophisticated ex ### Add Skills to your plugin -Plugins can include [Agent Skills](/en/docs/claude-code/skills) to extend Claude's capabilities. Skills are model-invoked—Claude autonomously uses them based on the task context. +Plugins can include [Agent Skills](/en/skills) to extend Claude's capabilities. Skills are model-invoked—Claude autonomously uses them based on the task context. To add Skills to your plugin, create a `skills/` directory at your plugin root and add Skill folders with `SKILL.md` files. Plugin Skills are automatically available when the plugin is installed. -For complete Skill authoring guidance, see [Agent Skills](/en/docs/claude-code/skills). +For complete Skill authoring guidance, see [Agent Skills](/en/skills). ### 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/docs/claude-code/plugins-reference#plugin-directory-structure). +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 @@ -324,7 +324,7 @@ When developing plugins, use a local marketplace to test changes iteratively. Th - **For multiple plugins**: Organize plugins in subdirectories like `./plugins/plugin-name` and update your marketplace.json accordingly. See [Plugin sources](/en/docs/claude-code/plugin-marketplaces#plugin-sources) for organization patterns. + **For multiple plugins**: Organize plugins in subdirectories like `./plugins/plugin-name` and update your marketplace.json accordingly. See [Plugin sources](/en/plugin-marketplaces#plugin-sources) for organization patterns. ### Debug plugin issues @@ -333,7 +333,7 @@ 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/docs/claude-code/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques +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 @@ -341,11 +341,11 @@ 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 in your `plugin.json` -3. **Create or use a marketplace**: Distribute through plugin marketplaces for easy installation +3. **Create or use a marketplace**: Distribute through plugin marketplaces for installation 4. **Test with others**: Have team members test the plugin before wider distribution - For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/docs/claude-code/plugins-reference). + For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference). *** @@ -363,13 +363,13 @@ Now that you understand Claude Code's plugin system, here are suggested paths fo ### For plugin developers -* **Create your first marketplace**: [Plugin marketplaces guide](/en/docs/claude-code/plugin-marketplaces) +* **Create your first marketplace**: [Plugin marketplaces guide](/en/plugin-marketplaces) * **Advanced components**: Dive deeper into specific plugin components: - * [Slash commands](/en/docs/claude-code/slash-commands) - Command development details - * [Subagents](/en/docs/claude-code/sub-agents) - Agent configuration and capabilities - * [Agent Skills](/en/docs/claude-code/skills) - Extend Claude's capabilities - * [Hooks](/en/docs/claude-code/hooks) - Event handling and automation - * [MCP](/en/docs/claude-code/mcp) - External tool integration + * [Slash commands](/en/slash-commands) - Command development details + * [Subagents](/en/sub-agents) - Agent configuration and capabilities + * [Agent Skills](/en/skills) - Extend Claude's capabilities + * [Hooks](/en/hooks) - Event handling and automation + * [MCP](/en/mcp) - External tool integration * **Distribution strategies**: Package and share your plugins effectively * **Community contribution**: Consider contributing to community plugin collections @@ -382,10 +382,15 @@ Now that you understand Claude Code's plugin system, here are suggested paths fo ## See also -* [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces) - Creating and managing plugin catalogs -* [Slash commands](/en/docs/claude-code/slash-commands) - Understanding custom commands -* [Subagents](/en/docs/claude-code/sub-agents) - Creating and using specialized agents -* [Agent Skills](/en/docs/claude-code/skills) - Extend Claude's capabilities -* [Hooks](/en/docs/claude-code/hooks) - Automating workflows with event handlers -* [MCP](/en/docs/claude-code/mcp) - Connecting to external tools and services -* [Settings](/en/docs/claude-code/settings) - Configuration options for plugins +* [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing plugin catalogs +* [Slash commands](/en/slash-commands) - Understanding custom commands +* [Subagents](/en/sub-agents) - Creating and using specialized agents +* [Agent Skills](/en/skills) - Extend Claude's capabilities +* [Hooks](/en/hooks) - Automating workflows with event handlers +* [MCP](/en/mcp) - Connecting to external tools and services +* [Settings](/en/settings) - Configuration options for plugins + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/quickstart.md b/skills/working-with-claude-code/references/quickstart.md index aa9b251..d6398e7 100644 --- a/skills/working-with-claude-code/references/quickstart.md +++ b/skills/working-with-claude-code/references/quickstart.md @@ -14,43 +14,43 @@ Make sure you have: ## Step 1: Install Claude Code -### NPM Install +To install Claude Code, use one of the following methods: -If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/): + + + **Homebrew (macOS, Linux):** -```sh theme={null} -npm install -g @anthropic-ai/claude-code -``` - -### Native Install - - - Alternatively, try our new native install, now in beta. - + ```sh theme={null} + brew install --cask claude-code + ``` -**Homebrew (macOS, Linux):** + **macOS, Linux, WSL:** -```sh theme={null} -brew install --cask claude-code -``` + ```bash theme={null} + curl -fsSL https://claude.ai/install.sh | bash + ``` -**macOS, Linux, WSL:** + **Windows PowerShell:** -```bash theme={null} -curl -fsSL https://claude.ai/install.sh | bash -``` + ```powershell theme={null} + irm https://claude.ai/install.ps1 | iex + ``` -**Windows PowerShell:** + **Windows CMD:** -```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 + ``` + -**Windows CMD:** + + If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/): -```batch theme={null} -curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd -``` + ```sh theme={null} + npm install -g @anthropic-ai/claude-code + ``` + + ## Step 2: Log in to your account @@ -93,7 +93,7 @@ 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/docs/claude-code/iam#credential-management). + After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/iam#credential-management). ## Step 4: Ask your first question @@ -252,7 +252,7 @@ Here are the most important commands for daily use: | `/help` | Show available commands | `> /help` | | `exit` or Ctrl+C | Exit Claude Code | `> exit` | -See the [CLI reference](/en/docs/claude-code/cli-reference) for a complete list of commands. +See the [CLI reference](/en/cli-reference) for a complete list of commands. ## Pro tips for beginners @@ -304,17 +304,21 @@ See the [CLI reference](/en/docs/claude-code/cli-reference) for a complete list Now that you've learned the basics, explore more advanced features: - + Step-by-step guides for common tasks - + Master all commands and options - + Customize Claude Code for your workflow + + + Run tasks asynchronously in the cloud + ## Getting help @@ -322,3 +326,8 @@ Now that you've learned the basics, explore more advanced features: * **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 + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/sandboxing.md b/skills/working-with-claude-code/references/sandboxing.md new file mode 100644 index 0000000..a6fc2be --- /dev/null +++ b/skills/working-with-claude-code/references/sandboxing.md @@ -0,0 +1,224 @@ +# 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: + +* **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation +* **macOS**: Uses Seatbelt for sandbox enforcement + +These OS-level restrictions ensure that all child processes spawned by Claude Code's commands inherit the same security boundaries. + +## Getting started + +### Enable sandboxing + +You can enable sandboxing by running the `/sandbox` slash command: + +``` +> /sandbox +``` + +This opens a menu where you can choose between sandbox modes. + +### 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/iam#configuring-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. + +## 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: + +* **IAM policies**: Combine with [permission settings](/en/iam) 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**: Currently supports Linux and macOS; Windows support planned + +## See also + +* [Security](/en/security) - Comprehensive security features and best practices +* [IAM](/en/iam) - Permission configuration and access control +* [Settings](/en/settings) - Complete configuration reference +* [CLI reference](/en/cli-reference) - Command-line options including `-sb` + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/security.md b/skills/working-with-claude-code/references/security.md index c6baa38..d9a37fa 100644 --- a/skills/working-with-claude-code/references/security.md +++ b/skills/working-with-claude-code/references/security.md @@ -14,12 +14,13 @@ Claude Code uses strict read-only permissions by default. When additional action 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 [Identity and Access Management](/en/docs/claude-code/iam). +For detailed permission configuration, see [Identity and Access Management](/en/iam). ### 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 @@ -37,7 +38,7 @@ Prompt injection is a technique where an attacker attempts to override or manipu * **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/docs/claude-code/iam#tool-specific-permission-rules) +* **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/iam#tool-specific-permission-rules) ### Privacy safeguards @@ -58,7 +59,11 @@ For full details, please review our [Commercial Terms of Service](https://www.an * **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/docs/claude-code/iam#credential-management) +* **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/iam#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**: @@ -82,7 +87,20 @@ We encourage either writing your own MCP servers or using MCP servers from provi ## IDE security -See [here](/en/docs/claude-code/ide-integrations#security) for more information on the security of running Claude Code in an IDE. +See [here](/en/vs-code#security) for more information on the security of 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 @@ -90,15 +108,15 @@ See [here](/en/docs/claude-code/ide-integrations#security) for more information * Review all suggested changes before approval * Use project-specific permission settings for sensitive repositories -* Consider using [devcontainers](/en/docs/claude-code/devcontainer) for additional isolation +* Consider using [devcontainers](/en/devcontainer) for additional isolation * Regularly audit your permission settings with `/permissions` ### Team security -* Use [enterprise managed policies](/en/docs/claude-code/iam#enterprise-managed-policy-settings) to enforce organizational standards +* Use [enterprise managed policies](/en/iam#enterprise-managed-policy-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/docs/claude-code/monitoring-usage) +* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage) ### Reporting security issues @@ -111,7 +129,13 @@ If you discover a security vulnerability in Claude Code: ## Related resources -* [Identity and Access Management](/en/docs/claude-code/iam) - Configure permissions and access controls -* [Monitoring usage](/en/docs/claude-code/monitoring-usage) - Track and audit Claude Code activity -* [Development containers](/en/docs/claude-code/devcontainer) - Secure, isolated environments +* [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands +* [Identity and Access Management](/en/iam) - 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 + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/settings.md b/skills/working-with-claude-code/references/settings.md index 5ab3212..cb82919 100644 --- a/skills/working-with-claude-code/references/settings.md +++ b/skills/working-with-claude-code/references/settings.md @@ -19,12 +19,15 @@ Code through hierarchical settings: settings. System administrators can deploy policies to: * macOS: `/Library/Application Support/ClaudeCode/managed-settings.json` * Linux and WSL: `/etc/claude-code/managed-settings.json` - * Windows: `C:\ProgramData\ClaudeCode\managed-settings.json` + * Windows: `C:\Program Files\ClaudeCode\managed-settings.json` + * `C:\ProgramData\ClaudeCode\managed-settings.json` will be deprecated in a future version. * Enterprise deployments can also configure **managed MCP servers** that override - user-configured servers. See [Enterprise MCP configuration](/en/docs/claude-code/mcp#enterprise-mcp-configuration): + user-configured servers. See [Enterprise MCP configuration](/en/mcp#enterprise-mcp-configuration): * macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json` * Linux and WSL: `/etc/claude-code/managed-mcp.json` - * Windows: `C:\ProgramData\ClaudeCode\managed-mcp.json` + * Windows: `C:\Program Files\ClaudeCode\managed-mcp.json` + * `C:\ProgramData\ClaudeCode\managed-mcp.json` will be deprecated in a future version. +* **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`. ```JSON Example settings.json theme={null} { @@ -44,7 +47,12 @@ Code through hierarchical settings: "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" + ] } ``` @@ -52,47 +60,138 @@ Code through hierarchical 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` | How long to locally retain chat transcripts based on last activity date (default: 30 days) | `20` | -| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` | -| `includeCoAuthoredBy` | 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 before or after tool executions. See [hooks documentation](hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` | -| `disableAllHooks` | Disable all [hooks](hooks) | `true` | -| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` | -| `statusLine` | Configure a custom status line to display context. See [statusLine documentation](statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` | -| `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](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"]` | -| `useEnterpriseMcpConfigOnly` | When set in managed-settings.json, restricts MCP servers to only those defined in managed-mcp.json. See [Enterprise MCP configuration](/en/docs/claude-code/mcp#enterprise-mcp-configuration) | `true` | -| `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 [Enterprise MCP configuration](/en/docs/claude-code/mcp#enterprise-mcp-configuration) | `[{ "serverName": "github" }]` | -| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including enterprise servers. Denylist takes precedence over allowlist. See [Enterprise MCP configuration](/en/docs/claude-code/mcp#enterprise-mcp-configuration) | `[{ "serverName": "filesystem" }]` | -| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/docs/claude-code/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` | -| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/docs/claude-code/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` | +| 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 before or after tool executions. See [hooks documentation](/en/hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` | +| `disableAllHooks` | Disable all [hooks](/en/hooks) | `true` | +| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` | +| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` | +| `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 [Enterprise MCP configuration](/en/mcp#enterprise-mcp-configuration) | `[{ "serverName": "github" }]` | +| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including enterprise servers. Denylist takes precedence over allowlist. See [Enterprise MCP configuration](/en/mcp#enterprise-mcp-configuration) | `[{ "serverName": "filesystem" }]` | +| `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` | ### Permission settings -| Keys | Description | Example | -| :----------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- | -| `allow` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to allow tool use. **Note:** Bash rules use prefix matching, not regex | `[ "Bash(git diff:*)" ]` | -| `ask` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to ask for confirmation upon tool use. | `[ "Bash(git push:*)" ]` | -| `deny` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to deny tool use. Use this to also exclude sensitive files from Claude Code access. **Note:** Bash patterns are prefix matches and can be bypassed (see [Bash permission limitations](/en/docs/claude-code/iam#tool-specific-permission-rules)) | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` | -| `additionalDirectories` | Additional [working directories](iam#working-directories) that Claude has access to | `[ "../docs/" ]` | -| `defaultMode` | Default [permission mode](iam#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 policy settings](iam#enterprise-managed-policy-settings) | `"disable"` | +| Keys | Description | Example | +| :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------- | +| `allow` | Array of [permission rules](/en/iam#configuring-permissions) to allow tool use. **Note:** Bash rules use prefix matching, not regex | `[ "Bash(git diff:*)" ]` | +| `ask` | Array of [permission rules](/en/iam#configuring-permissions) to ask for confirmation upon tool use. | `[ "Bash(git push:*)" ]` | +| `deny` | Array of [permission rules](/en/iam#configuring-permissions) to deny tool use. Use this to also exclude sensitive files from Claude Code access. **Note:** Bash patterns are prefix matches and can be bypassed (see [Bash permission limitations](/en/iam#tool-specific-permission-rules)) | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` | +| `additionalDirectories` | Additional [working directories](/en/iam#working-directories) that Claude has access to | `[ "../docs/" ]` | +| `defaultMode` | Default [permission mode](/en/iam#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 policy settings](/en/iam#enterprise-managed-policy-settings) | `"disable"` | + +### 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 only). 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.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` | +| `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 only). **Reduces security.** Default: false | `true` | + +**Configuration example:** + +```json theme={null} +{ + "sandbox": { + "enabled": true, + "autoAllowBashIfSandboxed": true, + "excludedCommands": ["docker"], + "network": { + "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. + ### Settings precedence -Settings are applied in order of precedence (highest to lowest): +Settings apply in order of precedence. From highest to lowest: 1. **Enterprise managed policies** (`managed-settings.json`) * Deployed by IT/DevOps - * Cannot be overridden + * Can't be overridden 2. **Command line arguments** * Temporary overrides for a specific session @@ -108,24 +207,24 @@ Settings are applied in order of precedence (highest to lowest): This hierarchy ensures that enterprise security 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 +* **Memory files (`CLAUDE.md`)**: Contain instructions and context that Claude loads at startup * **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior * **Slash commands**: Custom commands that can be invoked during a session with `/command-name` * **MCP servers**: Extend Claude Code with additional tools and integrations * **Precedence**: Higher-level configurations (Enterprise) override lower-level ones (User/Project) * **Inheritance**: Settings are merged, with more specific settings adding to or overriding broader ones -### System prompt availability +### System prompt - - Unlike for claude.ai, we do not publish Claude Code's internal system prompt on this website. Use CLAUDE.md files or `--append-system-prompt` to add custom instructions to Claude Code's behavior. - +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 (e.g., API keys, secrets, environment files), use the `permissions.deny` setting in your `.claude/settings.json` file: +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} { @@ -150,7 +249,7 @@ Claude Code supports custom AI subagents that can be configured at both user and * **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/docs/claude-code/sub-agents). +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 @@ -246,7 +345,7 @@ Use the `/plugin` command to manage plugins interactively: * View plugin details (commands, agents, hooks provided) * Add/remove marketplaces -Learn more about the plugin system in the [plugins documentation](/en/docs/claude-code/plugins). +Learn more about the plugin system in the [plugins documentation](/en/plugins). ## Environment variables @@ -256,87 +355,158 @@ 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 you want to add to the request (in `Name: Value` format) | -| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/docs/claude-code/model-config#environment-variables) | -| `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/en/docs/claude-code/model-config#environment-variables) | -| `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/en/docs/claude-code/model-config#environment-variables) | -| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/docs/claude-code/model-config#environment-variables)) | -| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/docs/claude-code/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_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command | -| `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_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_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 | -| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (e.g. when using an LLM gateway) | -| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (e.g. when using an LLM gateway) | -| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/docs/claude-code/model-config) | -| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/docs/claude-code/amazon-bedrock) | -| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/docs/claude-code/google-vertex-ai) | -| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. This takes precedence over the `autoUpdates` configuration setting. | -| `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_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) | -| `HTTP_PROXY` | Specify HTTP proxy server for network connections | -| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections | -| `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` | Enable [extended thinking](/en/docs/build-with-claude/extended-thinking) and set the token budget for the thinking process. Extended thinking improves performance on complex reasoning and coding tasks but impacts [prompt caching efficiency](/en/docs/build-with-claude/prompt-caching#caching-with-thinking-blocks). Disabled by default. | -| `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 slash command metadata shown to [SlashCommand tool](/en/docs/claude-code/slash-commands#slashcommand-tool) (default: 15000) | -| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` intead 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_5_SONNET` | Override region for Claude Sonnet 3.5 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 | +| 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 you want to add to the request (in `Name: Value` format) | +| `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_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_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command | +| `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_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_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 | +| `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_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) | +| `HTTP_PROXY` | Specify HTTP proxy server for network connections | +| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections | +| `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` | Enable [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) and set the token budget for the thinking process. 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). Disabled by default. | +| `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 slash command metadata shown to [SlashCommand tool](/en/slash-commands#slashcommand-tool) (default: 15000) | +| `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 | -| :--------------- | :----------------------------------------------------------------------------------- | :------------------ | -| **Bash** | Executes shell commands in your environment | Yes | -| **Edit** | Makes targeted edits to specific files | Yes | -| **Glob** | Finds files based on pattern matching | No | -| **Grep** | Searches for patterns in file contents | No | -| **NotebookEdit** | Modifies Jupyter notebook cells | Yes | -| **NotebookRead** | Reads and displays Jupyter notebook contents | No | -| **Read** | Reads the contents of files | No | -| **SlashCommand** | Runs a [custom slash command](/en/docs/claude-code/slash-commands#slashcommand-tool) | Yes | -| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No | -| **TodoWrite** | Creates and manages structured task lists | No | -| **WebFetch** | Fetches content from a specified URL | Yes | -| **WebSearch** | Performs web searches with domain filtering | Yes | -| **Write** | Creates or overwrites files | Yes | - -Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/docs/claude-code/settings#available-settings). Also see [Tool-specific permission rules](/en/docs/claude-code/iam#tool-specific-permission-rules). +| Tool | Description | Permission Required | +| :------------------ | :------------------------------------------------------------------------------------------------ | :------------------ | +| **AskUserQuestion** | Asks the user multiple choice questions to gather information or clarify ambiguity | No | +| **Bash** | Executes shell commands in your environment (see [Bash tool behavior](#bash-tool-behavior) below) | Yes | +| **BashOutput** | Retrieves output from a background bash shell | 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 | +| **NotebookEdit** | Modifies Jupyter notebook cells | Yes | +| **Read** | Reads the contents of files | No | +| **Skill** | Executes a skill within the main conversation | Yes | +| **SlashCommand** | Runs a [custom slash command](/en/slash-commands#slashcommand-tool) | Yes | +| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No | +| **TodoWrite** | Creates and manages structured task lists | No | +| **WebFetch** | Fetches content from a specified URL | Yes | +| **WebSearch** | Performs web searches with domain filtering | Yes | +| **Write** | Creates or overwrites files | Yes | + +Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/iam#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#persisting-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/docs/claude-code/hooks-guide). +[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 @@ -344,6 +514,11 @@ files by blocking Write operations to certain paths. ## See also -* [Identity and Access Management](/en/docs/claude-code/iam#configuring-permissions) - Learn about Claude Code's permission system -* [IAM and access control](/en/docs/claude-code/iam#enterprise-managed-policy-settings) - Enterprise policy management -* [Troubleshooting](/en/docs/claude-code/troubleshooting#auto-updater-issues) - Solutions for common configuration issues +* [Identity and Access Management](/en/iam#configuring-permissions) - Learn about Claude Code's permission system +* [IAM and access control](/en/iam#enterprise-managed-policy-settings) - Enterprise policy management +* [Troubleshooting](/en/troubleshooting#auto-updater-issues) - Solutions for common configuration issues + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/setup.md b/skills/working-with-claude-code/references/setup.md index 2a3234a..f193e66 100644 --- a/skills/working-with-claude-code/references/setup.md +++ b/skills/working-with-claude-code/references/setup.md @@ -5,32 +5,58 @@ ## System requirements * **Operating Systems**: macOS 10.15+, Ubuntu 20.04+/Debian 10+, or Windows 10+ (with WSL 1, WSL 2, or Git for Windows) -* **Hardware**: 4GB+ RAM -* **Software**: [Node.js 18+](https://nodejs.org/en/download) +* **Hardware**: 4 GB+ RAM +* **Software**: [Node.js 18+](https://nodejs.org/en/download) (only required for npm installation) * **Network**: Internet connection required for authentication and AI processing * **Shell**: Works best in Bash, Zsh or Fish * **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries) ### Additional dependencies -* **ripgrep**: Usually included with Claude Code. If search functionality fails, see [search troubleshooting](/en/docs/claude-code/troubleshooting#search-and-discovery-issues). +* **ripgrep**: Usually included with Claude Code. If search fails, see [search troubleshooting](/en/troubleshooting#search-and-discovery-issues). ## Standard installation -To install Claude Code, run the following command: +To install Claude Code, use one of the following methods: -```sh theme={null} -npm install -g @anthropic-ai/claude-code -``` + + + **Homebrew (macOS, Linux):** - - Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. - If you encounter permission errors, see [configure Claude Code](/en/docs/claude-code/troubleshooting#linux-permission-issues) for recommended solutions. - + ```sh theme={null} theme={null} + brew install --cask claude-code + ``` + + **macOS, Linux, WSL:** + + ```bash theme={null} theme={null} + curl -fsSL https://claude.ai/install.sh | bash + ``` + + **Windows PowerShell:** + + ```powershell theme={null} theme={null} + irm https://claude.ai/install.ps1 | iex + ``` + + **Windows CMD:** + + ```batch theme={null} theme={null} + curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd + ``` + + + + If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/): + + ```sh theme={null} theme={null} + npm install -g @anthropic-ai/claude-code + ``` + + Some users may be automatically migrated to an improved installation method. - Run `claude doctor` after installation to check your installation type. After the installation process completes, navigate to your project and start Claude Code: @@ -42,12 +68,12 @@ claude Claude Code offers the following authentication options: -1. **Claude Console**: The default option. Connect through the Claude Console and complete the OAuth process. Requires active billing at [console.anthropic.com](https://console.anthropic.com). A "Claude Code" workspace will be automatically created for usage tracking and cost management. Note that you cannot create API keys for the Claude Code workspace - it is dedicated exclusively for Claude Code usage. +1. **Claude Console**: The default option. Connect through the Claude Console and complete the OAuth process. Requires active billing in the [Anthropic console](https://console.anthropic.com). 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. 2. **Claude App (with Pro or Max plan)**: Subscribe to Claude's [Pro or Max plan](https://claude.com/pricing) for a unified subscription that includes both Claude Code and the web interface. Get more value at the same price point while managing your account in one place. Log in with your Claude.ai account. During launch, choose the option that matches your subscription type. -3. **Enterprise platforms**: Configure Claude Code to use [Amazon Bedrock or Google Vertex AI](/en/docs/claude-code/third-party-integrations) for enterprise deployments with your existing cloud infrastructure. +3. **Enterprise platforms**: Configure Claude Code to use [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) for enterprise deployments with your existing cloud infrastructure. - Claude Code securely stores your credentials. See [Credential Management](/en/docs/claude-code/iam#credential-management) for details. + Claude Code securely stores your credentials. See [Credential Management](/en/iam#credential-management) for details. ## Windows setup @@ -68,31 +94,23 @@ Claude Code offers the following authentication options: Claude Code offers multiple installation methods to suit different environments. -If you encounter any issues during installation, consult the [troubleshooting guide](/en/docs/claude-code/troubleshooting#linux-permission-issues). +If you encounter any issues during installation, consult the [troubleshooting guide](/en/troubleshooting#linux-permission-issues). Run `claude doctor` after installation to check your installation type and version. -### Global npm installation - -Traditional method shown in the [install steps above](#standard-installation) +### Native installation options -### Native binary installation (Beta) +The native installation is the recommended method and offers several benefits: -If you have an existing installation of Claude Code, use `claude install` to start the native binary installation. +* One self-contained executable +* No Node.js dependency +* Improved auto-updater stability -For a fresh install, run one of the following commands: +If you have an existing installation of Claude Code, use `claude install` to migrate to the native binary installation. -**Homebrew (macOS, Linux):** - -```sh theme={null} -brew install --cask claude-code -``` - - - Claude Code installed via Homebrew will auto-update outside of the brew directory unless explicitly disabled with the `DISABLE_AUTOUPDATER` environment variable (see [Auto updates](#auto-updates) section). - +For advanced installation options with the native installer: **macOS, Linux, WSL:** @@ -108,7 +126,11 @@ curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58 ``` - **Alpine Linux and other musl/uClibc-based distributions**: The native build requires you to install `libgcc`, `libstdc++`, and `ripgrep`. Install (Alpine: `apk add libgcc libstdc++ ripgrep`) and set `USE_BUILTIN_RIPGREP=0`. + **Alpine Linux and other musl/uClibc-based distributions**: The native build requires `libgcc`, `libstdc++`, and `ripgrep`. For Alpine: `apk add libgcc libstdc++ ripgrep`. Set `USE_BUILTIN_RIPGREP=0`. + + + + Claude Code installed via Homebrew will auto-update outside of the brew directory unless explicitly disabled with the `DISABLE_AUTOUPDATER` environment variable (see [Auto updates](#auto-updates) section). **Windows PowerShell:** @@ -137,24 +159,35 @@ REM Install specific version number curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 1.0.58 && del install.cmd ``` -The native Claude Code installer is supported on macOS, Linux, and Windows. - - Make sure that you remove any outdated aliases or symlinks. - Once your installation is complete, run `claude doctor` to verify the installation. + Make sure that you remove any outdated aliases or symlinks before installing. -### Local installation +**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 + +For environments where NPM is preferred or required: + +```sh theme={null} +npm install -g @anthropic-ai/claude-code +``` -* After global install via npm, use `claude migrate-installer` to move to local -* Avoids autoupdater npm permission issues -* Some users may be automatically migrated to this method + + Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. + If you encounter permission errors, see [configure Claude Code](/en/troubleshooting#linux-permission-issues) for recommended solutions. + ## Running on AWS or GCP By default, Claude Code uses the Claude API. -For details on running Claude Code on AWS or GCP, see [third-party integrations](/en/docs/claude-code/third-party-integrations). +For details on running Claude Code on AWS or GCP, see [third-party integrations](/en/third-party-integrations). ## Update Claude Code @@ -169,7 +202,7 @@ Claude Code automatically keeps itself up to date to ensure you have the latest **Disable auto-updates:** -Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/docs/claude-code/settings): +Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/settings): ```bash theme={null} export DISABLE_AUTOUPDATER=1 @@ -180,3 +213,93 @@ export DISABLE_AUTOUPDATER=1 ```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 symlink: + +**macOS, Linux, WSL:** + +```bash theme={null} +rm -f ~/.local/bin/claude +rm -rf ~/.claude-code +``` + +**Windows PowerShell:** + +```powershell theme={null} +Remove-Item -Path "$env:LOCALAPPDATA\Programs\claude-code" -Recurse -Force +Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\WindowsApps\claude.exe" -Force +``` + +**Windows CMD:** + +```batch theme={null} +rmdir /s /q "%LOCALAPPDATA%\Programs\claude-code" +del "%LOCALAPPDATA%\Microsoft\WindowsApps\claude.exe" +``` + +### Homebrew installation + +```bash theme={null} +brew uninstall --cask claude-code +``` + +### 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" +``` + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/skills.md b/skills/working-with-claude-code/references/skills.md index 43ef0fb..5058f50 100644 --- a/skills/working-with-claude-code/references/skills.md +++ b/skills/working-with-claude-code/references/skills.md @@ -7,7 +7,7 @@ This guide shows you how to create, use, and manage Agent Skills in Claude Code. ## Prerequisites * Claude Code version 1.0 or later -* Basic familiarity with [Claude Code](/en/docs/claude-code/quickstart) +* Basic familiarity with [Claude Code](/en/quickstart) ## What are Agent Skills? @@ -22,7 +22,7 @@ Agent Skills package expertise into discoverable capabilities. Each Skill consis * Reduce repetitive prompting * Compose multiple Skills for complex tasks -Learn more in the [Agent Skills overview](/en/docs/agents-and-tools/agent-skills/overview). +Learn more in the [Agent Skills overview](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview). For a deep dive into the architecture and real-world applications of Agent Skills, read our engineering blog: [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills). @@ -64,7 +64,7 @@ Project Skills are checked into git and automatically available to team members. ### Plugin Skills -Skills can also come from [Claude Code plugins](/en/docs/claude-code/plugins). Plugins may bundle Skills that are automatically available when the plugin is installed. These Skills work the same way as personal and project Skills. +Skills can also come from [Claude Code plugins](/en/plugins). Plugins may bundle Skills that are automatically available when the plugin is installed. These Skills work the same way as personal and project Skills. ## Write SKILL.md @@ -72,7 +72,7 @@ Create a `SKILL.md` file with YAML frontmatter and Markdown content: ```yaml theme={null} --- -name: Your Skill Name +name: your-skill-name description: Brief description of what this Skill does and when to use it --- @@ -85,9 +85,14 @@ Provide clear, step-by-step guidance for Claude. Show concrete examples of using this Skill. ``` +**Field requirements**: + +* `name`: Must use lowercase letters, numbers, and hyphens only (max 64 characters) +* `description`: Brief description of what the Skill does and when to use it (max 1024 characters) + The `description` field is critical for Claude to discover when to use your Skill. It should include both what the Skill does and when Claude should use it. -See the [best practices guide](/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance. +See the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance including validation rules. ## Add supporting files @@ -123,7 +128,7 @@ Use the `allowed-tools` frontmatter field to limit which tools Claude can use wh ```yaml theme={null} --- -name: Safe File Reader +name: safe-file-reader description: Read files without making changes. Use when you need read-only file access. allowed-tools: Read, Grep, Glob --- @@ -141,10 +146,10 @@ This Skill provides read-only file access. When this Skill is active, Claude can only use the specified tools (Read, Grep, Glob) without needing to ask for permission. This is useful for: * Read-only Skills that shouldn't modify files -* Skills with limited scope (e.g., only data analysis, no file writing) +* Skills with limited scope: for example, only data analysis, no file writing * Security-sensitive workflows where you want to restrict capabilities -If `allowed-tools` is not specified, Claude will ask for permission to use tools as normal, following the standard permission model. +If `allowed-tools` isn't specified, Claude will ask for permission to use tools as normal, following the standard permission model. `allowed-tools` is only supported for Skills in Claude Code. @@ -256,7 +261,7 @@ claude --debug ## Share Skills with your team -**Recommended approach**: Distribute Skills through [plugins](/en/docs/claude-code/plugins). +**Recommended approach**: Distribute Skills through [plugins](/en/plugins). To share Skills via plugin: @@ -264,7 +269,7 @@ To share Skills via plugin: 2. Add the plugin to a marketplace 3. Team members install the plugin -For complete instructions, see [Add Skills to your plugin](/en/docs/claude-code/plugins#add-skills-to-your-plugin). +For complete instructions, see [Add Skills to your plugin](/en/plugins#add-skills-to-your-plugin). You can also share Skills directly through project repositories: @@ -481,7 +486,7 @@ commit-helper/ ```yaml theme={null} --- -name: Generating Commit Messages +name: generating-commit-messages description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes. --- @@ -510,7 +515,7 @@ code-reviewer/ ```yaml theme={null} --- -name: Code Reviewer +name: code-reviewer description: Review code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality. allowed-tools: Read, Grep, Glob --- @@ -549,7 +554,7 @@ pdf-processing/ ````yaml theme={null} --- -name: PDF Processing +name: pdf-processing description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages. --- @@ -584,15 +589,24 @@ Claude loads additional files only when needed. ## Next steps - + Write Skills that Claude can use effectively - + Learn how Skills work across Claude products - + + Use Skills programmatically with TypeScript and Python + + + Create your first Skill + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/slack.md b/skills/working-with-claude-code/references/slack.md new file mode 100644 index 0000000..492339c --- /dev/null +++ b/skills/working-with-claude-code/references/slack.md @@ -0,0 +1,211 @@ +# 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 + + + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/slash-commands.md b/skills/working-with-claude-code/references/slash-commands.md index 2e16cf4..f8c1e48 100644 --- a/skills/working-with-claude-code/references/slash-commands.md +++ b/skills/working-with-claude-code/references/slash-commands.md @@ -4,35 +4,52 @@ ## Built-in slash commands -| Command | Purpose | -| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------- | -| `/add-dir` | Add additional working directories | -| `/agents` | Manage custom AI subagents for specialized 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) | -| `/cost` | Show token usage statistics (see [cost tracking guide](/en/docs/claude-code/costs#using-the-cost-command) for subscription-specific details) | -| `/doctor` | Checks the health of your Claude Code installation | -| `/help` | Get usage help | -| `/init` | Initialize project with CLAUDE.md guide | -| `/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 | -| `/permissions` | View or update [permissions](/en/docs/claude-code/iam#configuring-permissions) | -| `/pr_comments` | View pull request comments | -| `/review` | Request code review | -| `/rewind` | Rewind the conversation and/or code | -| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity | -| `/terminal-setup` | Install Shift+Enter key binding for newlines (iTerm2 and VSCode only) | -| `/usage` | Show plan usage limits and rate limit status (subscription plans only) | -| `/vim` | Enter vim mode for alternating insert and command modes | +| 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. +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 @@ -55,7 +72,7 @@ Commands stored in your repository and shared with your team. When listed in `/h **Location**: `.claude/commands/` -In the following example, we create the `/optimize` command: +The following example creates the `/optimize` command: ```bash theme={null} # Create a project command @@ -69,7 +86,7 @@ Commands available across all your projects. When listed in `/help`, these comma **Location**: `~/.claude/commands/` -In the following example, we create the `/security-review` command: +The following example creates the `/security-review` command: ```bash theme={null} # Create a personal command @@ -81,12 +98,16 @@ echo "Review this code for security vulnerabilities:" > ~/.claude/commands/secur #### Namespacing -Organize commands in subdirectories. The subdirectories are used for organization and appear in the command description, but they do not affect the command name itself. The description will show whether the command comes from the project directory (`.claude/commands`) or the user-level directory (`~/.claude/commands`), along with the subdirectory name. +Use subdirectories to group related commands. Subdirectories appear in the command description but don't affect the command name. -Conflicts between user and project level commands are not supported. Otherwise, multiple commands with the same base file name can coexist. +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. -For example, a file at `.claude/commands/frontend/component.md` creates the command `/component` with description showing "(project:frontend)". -Meanwhile, a file at `~/.claude/commands/component.md` creates the command `/component` with description showing "(user)". +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 @@ -150,7 +171,7 @@ Based on the above changes, create a single git commit. #### File references -Include file contents in commands using the `@` prefix to [reference files](/en/docs/claude-code/common-workflows#reference-files-and-directories). +Include file contents in commands using the `@` prefix to [reference files](/en/common-workflows#reference-files-and-directories). For example: @@ -166,7 +187,7 @@ Compare @src/old-version.js with @src/new-version.js #### Thinking mode -Slash commands can trigger extended thinking by including [extended thinking keywords](/en/docs/claude-code/common-workflows#use-extended-thinking). +Slash commands can trigger extended thinking by including [extended thinking keywords](/en/common-workflows#use-extended-thinking). ### Frontmatter @@ -177,7 +198,7 @@ Command files support frontmatter, useful for specifying metadata about the comm | `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](/en/docs/about-claude/models/overview)) | Inherits from the conversation | +| `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: @@ -207,7 +228,7 @@ Focus on security, performance, and code style. ## Plugin commands -[Plugins](/en/docs/claude-code/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/docs/claude-code/plugin-marketplaces). +[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 @@ -294,9 +315,10 @@ MCP prompts can accept arguments defined by the server: #### Naming conventions -* Server and prompt names are normalized +Server and prompt names are normalized: + * Spaces and special characters become underscores -* Names are lowercased for consistency +* Names are lowercase for consistency ### Managing MCP connections @@ -310,39 +332,37 @@ Use the `/mcp` command to: ### MCP permissions and wildcards -When configuring [permissions for MCP tools](/en/docs/claude-code/iam#tool-specific-permission-rules), note that **wildcards are not supported**: +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) -* ✅ **Correct**: `mcp__github` (approves ALL tools from the github server) -* ✅ **Correct**: `mcp__github__get_issue` (approves specific tool) -* ❌ **Incorrect**: `mcp__github__*` (wildcards not supported) +To approve specific tools, list each one explicitly: -To approve all tools from an MCP server, use just the server name: `mcp__servername`. To approve specific tools only, list each tool individually. +* `mcp__github__get_issue` +* `mcp__github__list_issues` ## `SlashCommand` tool -The `SlashCommand` tool allows Claude to execute [custom slash commands](/en/docs/claude-code/slash-commands#custom-slash-commands) programmatically +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 trigger `SlashCommand` tool, your instructions (prompts, -CLAUDE.md, etc.) generally need to reference the command by name with its slash. - -Example: +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. +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. We use the `description` in the context. +* 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. @@ -356,14 +376,14 @@ To prevent Claude from executing any slash commands via the tool: # Add to deny rules: SlashCommand ``` -This will also remove SlashCommand tool (and the slash command descriptions) from context. +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 will also remove the command's metadata from context. +This also removes the command's metadata from context. ### `SlashCommand` permission rules @@ -378,13 +398,12 @@ 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, args, and description. +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 will see only a subset of the -available commands. In `/context`, a warning will show with "M of N commands". +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 @@ -392,11 +411,11 @@ available commands. In `/context`, a warning will show with "M of N commands". ### Use slash commands for -**Quick, frequently-used prompts**: +**Quick, frequently used prompts**: * Simple prompt snippets you use often * Quick reminders or templates -* Frequently-used instructions that fit in one file +* Frequently used instructions that fit in one file **Examples**: @@ -477,13 +496,18 @@ The Skill provides richer context, validation scripts, and organized reference m Both slash commands and Skills can coexist. Use the approach that fits your needs. -Learn more about [Agent Skills](/en/docs/claude-code/skills). +Learn more about [Agent Skills](/en/skills). ## See also -* [Plugins](/en/docs/claude-code/plugins) - Extend Claude Code with custom commands through plugins -* [Identity and Access Management](/en/docs/claude-code/iam) - Complete guide to permissions, including MCP tool permissions -* [Interactive mode](/en/docs/claude-code/interactive-mode) - Shortcuts, input modes, and interactive features -* [CLI reference](/en/docs/claude-code/cli-reference) - Command-line flags and options -* [Settings](/en/docs/claude-code/settings) - Configuration options -* [Memory management](/en/docs/claude-code/memory) - Managing Claude's memory across sessions +* [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 \ No newline at end of file diff --git a/skills/working-with-claude-code/references/statusline.md b/skills/working-with-claude-code/references/statusline.md index 024355e..1011f11 100644 --- a/skills/working-with-claude-code/references/statusline.md +++ b/skills/working-with-claude-code/references/statusline.md @@ -25,7 +25,7 @@ You can either: ## How it Works * The status line is updated when the conversation messages update -* Updates run at most every 300ms +* 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 @@ -58,6 +58,11 @@ Your status line command receives structured data via stdin in JSON format: "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 } } ``` @@ -181,6 +186,9 @@ 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) @@ -188,6 +196,25 @@ DIR=$(get_current_dir) echo "[$MODEL] 📁 ${DIR##*/}" ``` +### Context Window Usage + +Display the percentage of context window consumed: + +```bash theme={null} +#!/bin/bash +input=$(cat) + +INPUT_TOKENS=$(echo "$input" | jq -r '.context_window.total_input_tokens') +OUTPUT_TOKENS=$(echo "$input" | jq -r '.context_window.total_output_tokens') +CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size') +MODEL=$(echo "$input" | jq -r '.model.display_name') + +TOTAL_TOKENS=$((INPUT_TOKENS + OUTPUT_TOKENS)) +PERCENT_USED=$((TOTAL_TOKENS * 100 / CONTEXT_SIZE)) + +echo "[$MODEL] Context: ${PERCENT_USED}%" +``` + ## Tips * Keep your status line concise - it should fit on one line @@ -200,3 +227,8 @@ echo "[$MODEL] 📁 ${DIR##*/}" * If your status line doesn't appear, check that your script is executable (`chmod +x`) * Ensure your script outputs to stdout (not stderr) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/sub-agents.md b/skills/working-with-claude-code/references/sub-agents.md index de2c37e..4368a6e 100644 --- a/skills/working-with-claude-code/references/sub-agents.md +++ b/skills/working-with-claude-code/references/sub-agents.md @@ -27,7 +27,7 @@ When Claude Code encounters a task that matches a subagent's expertise, it can d - Once created, subagents can be used across different projects and shared with your team for consistent workflows. + Once created, you can use subagents across different projects and share them with your team for consistent workflows. @@ -53,15 +53,15 @@ To create your first subagent: - * **Recommended**: Generate with Claude first, then customize to make it yours - * Describe your subagent in detail and when it should be used - * Select the tools you want to grant access to (or leave blank to inherit all tools) - * The interface shows all available tools, making selection easy + * **Recommended**: generate with Claude first, then customize to make it yours + * Describe your subagent in detail, including when Claude should use it + * Select the tools you want to grant access to, or leave this blank to inherit all tools + * The interface shows all available tools * If you're generating with Claude, you can also edit the system prompt in your own editor by pressing `e` - Your subagent is now available! Claude will use it automatically when appropriate, or you can invoke it explicitly: + Your subagent is now available. Claude uses it automatically when appropriate, or you can invoke it explicitly: ``` > Use the code-reviewer subagent to check my recent changes @@ -84,9 +84,9 @@ When subagent names conflict, project-level subagents take precedence over user- ### Plugin agents -[Plugins](/en/docs/claude-code/plugins) can provide custom subagents that integrate seamlessly with Claude Code. Plugin agents work identically to user-defined agents and appear in the `/agents` interface. +[Plugins](/en/plugins) can provide custom subagents that integrate seamlessly with Claude Code. Plugin agents work identically to user-defined agents and appear in the `/agents` interface. -**Plugin agent locations**: Plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest). +**Plugin agent locations**: plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest). **Using plugin agents**: @@ -95,7 +95,7 @@ When subagent names conflict, project-level subagents take precedence over user- * Can be invoked automatically by Claude when appropriate * Can be managed (viewed, inspected) through `/agents` interface -See the [plugin components reference](/en/docs/claude-code/plugins-reference#agents) for details on creating plugin agents. +See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin agents. ### CLI-based configuration @@ -121,7 +121,7 @@ claude --agents '{ * Automation scripts that need custom subagents * Sharing subagent definitions in documentation or scripts -For detailed information about the JSON format and all available options, see the [CLI reference documentation](/en/docs/claude-code/cli-reference#agents-flag-format). +For detailed information about the JSON format and all available options, see the [CLI reference documentation](/en/cli-reference#agents-flag-format). ### File format @@ -133,6 +133,8 @@ name: your-sub-agent-name description: Description of when this subagent should be invoked tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted model: sonnet # Optional - specify model alias or 'inherit' +permissionMode: default # Optional - permission mode for the subagent +skills: skill1, skill2 # Optional - skills to auto-load --- Your subagent's system prompt goes here. This can be multiple paragraphs @@ -145,16 +147,18 @@ the subagent should follow. #### Configuration fields -| Field | Required | Description | -| :------------ | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `name` | Yes | Unique identifier using lowercase letters and hyphens | -| `description` | Yes | Natural language description of the subagent's purpose | -| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread | -| `model` | No | Model to use for this subagent. Can be a model alias (`sonnet`, `opus`, `haiku`) or `'inherit'` to use the main conversation's model. If omitted, defaults to the [configured subagent model](/en/docs/claude-code/model-config) | +| Field | Required | Description | +| :--------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | Yes | Unique identifier using lowercase letters and hyphens | +| `description` | Yes | Natural language description of the subagent's purpose | +| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread | +| `model` | No | Model to use for this subagent. Can be a model alias (`sonnet`, `opus`, `haiku`) or `'inherit'` to use the main conversation's model. If omitted, defaults to the [configured subagent model](/en/model-config) | +| `permissionMode` | No | Permission mode for the subagent. Valid values: `default`, `acceptEdits`, `bypassPermissions`, `plan`, `ignore`. Controls how the subagent handles permission requests | +| `skills` | No | Comma-separated list of skill names to auto-load when the subagent starts. Skills are loaded into the subagent's context automatically | ### Model selection -The `model` field allows you to control which [AI model](/en/docs/claude-code/model-config) the subagent uses: +The `model` field allows you to control 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 (useful for consistency) @@ -166,7 +170,7 @@ The `model` field allows you to control which [AI model](/en/docs/claude-code/mo ### Available tools -Subagents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/docs/claude-code/settings#tools-available-to-claude) for a complete list of available tools. +Subagents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/settings#tools-available-to-claude) for a complete list of available tools. **Recommended:** Use the `/agents` command to modify tool access - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the ones you need. @@ -196,7 +200,7 @@ This opens an interactive menu where you can: * Edit existing custom subagents, including their tool access * Delete custom subagents * See which subagents are active when duplicates exist -* **Easily manage tool permissions** with a complete list of available tools +* **Manage tool permissions** with a complete list of available tools ### Direct file management @@ -217,6 +221,10 @@ mkdir -p ~/.claude/agents # ... create subagent file ``` + + Subagents created by manually adding files will be loaded the next time you start a Claude Code session. To create and use a subagent immediately without restarting, use the `/agents` command instead. + + ## Using subagents effectively ### Automatic delegation @@ -241,6 +249,117 @@ Request a specific subagent by mentioning it in your command: > Ask the debugger subagent to investigate this error ``` +## Built-in subagents + +Claude Code includes built-in subagents that are available out of the box: + +### General-purpose subagent + +The general-purpose subagent is a capable agent for complex, multi-step tasks that require both exploration and action. Unlike the Explore subagent, it can modify files and execute a wider range of operations. + +**Key characteristics:** + +* **Model**: Uses Sonnet for more capable reasoning +* **Tools**: Has access to all tools +* **Mode**: Can read and write files, execute commands, make changes +* **Purpose**: Complex research tasks, multi-step operations, code modifications + +**When Claude uses it:** + +Claude delegates to the general-purpose subagent when: + +* The task requires both exploration and modification +* Complex reasoning is needed to interpret search results +* Multiple strategies may be needed if initial searches fail +* The task has multiple steps that depend on each other + +**Example scenario:** + +``` +User: Find all the places where we handle authentication and update them to use the new token format + +Claude: [Invokes general-purpose subagent] +[Agent searches for auth-related code across codebase] +[Agent reads and analyzes multiple files] +[Agent makes necessary edits] +[Returns detailed writeup of changes made] +``` + +### Plan subagent + +The Plan subagent is a specialized built-in agent designed for use during plan mode. When Claude is operating in plan mode (non-execution mode), it uses the Plan subagent to conduct research and gather information about your codebase before presenting a plan. + +**Key characteristics:** + +* **Model**: Uses Sonnet for more capable analysis +* **Tools**: Has access to Read, Glob, Grep, and Bash tools for codebase exploration +* **Purpose**: Searches files, analyzes code structure, and gathers context +* **Automatic invocation**: Claude automatically uses this agent when in plan mode and needs to research the codebase + +**How it works:** +When you're in plan mode and Claude needs to understand your codebase to create a plan, it delegates research tasks to the Plan subagent. This prevents infinite nesting of agents (subagents cannot spawn other subagents) while still allowing Claude to gather the necessary context. + +**Example scenario:** + +``` +User: [In plan mode] Help me refactor the authentication module + +Claude: Let me research your authentication implementation first... +[Internally invokes Plan subagent to explore auth-related files] +[Plan subagent searches codebase and returns findings] +Claude: Based on my research, here's my proposed plan... +``` + + + The Plan subagent is only used in plan mode. In normal execution mode, Claude uses the general-purpose agent or other custom subagents you've created. + + +### Explore subagent + +The Explore subagent is a fast, lightweight agent optimized for searching and analyzing codebases. It operates in strict read-only mode and is designed for rapid file discovery and code exploration. + +**Key characteristics:** + +* **Model**: Uses Haiku for fast, low-latency searches +* **Mode**: Strictly read-only - cannot create, modify, or delete files +* **Tools available**: + * Glob - File pattern matching + * Grep - Content searching with regular expressions + * Read - Reading file contents + * Bash - Read-only commands only (ls, git status, git log, git diff, find, cat, head, tail) + +**When Claude uses it:** + +Claude will delegate to the Explore subagent when it needs to search or understand a codebase but doesn't need to make changes. This is more efficient than the main agent running multiple search commands directly, as content found during the exploration process doesn't bloat the main conversation. + +**Thoroughness levels:** + +When invoking the Explore subagent, Claude specifies a thoroughness level: + +* **Quick** - Fast searches with minimal exploration. Good for targeted lookups. +* **Medium** - Moderate exploration. Balances speed and thoroughness. +* **Very thorough** - Comprehensive analysis across multiple locations and naming conventions. Used when the target might be in unexpected places. + +**Example scenarios:** + +``` +User: Where are errors from the client handled? + +Claude: [Invokes Explore subagent with "medium" thoroughness] +[Explore uses Grep to search for error handling patterns] +[Explore uses Read to examine promising files] +[Returns findings with absolute file paths] +Claude: Client errors are handled in src/services/process.ts:712... +``` + +``` +User: What's the codebase structure? + +Claude: [Invokes Explore subagent with "quick" thoroughness] +[Explore uses Glob and ls to map directory structure] +[Returns overview of key directories and their purposes] +``` + ## Example subagents ### Code reviewer @@ -261,7 +380,7 @@ When invoked: 3. Begin review immediately Review checklist: -- Code is simple and readable +- Code is clear and readable - Functions and variables are well-named - No duplicated code - Proper error handling @@ -310,7 +429,7 @@ For each issue, provide: - Testing approach - Prevention recommendations -Focus on fixing the underlying issue, not just symptoms. +Focus on fixing the underlying issue, not the symptoms. ``` ### Data scientist @@ -374,6 +493,65 @@ For complex workflows, you can chain multiple subagents: Claude Code intelligently selects subagents based on context. Make your `description` fields specific and action-oriented for best results. +### Resumable subagents + +Subagents can be resumed to continue previous conversations, which is particularly useful for long-running research or analysis tasks that need to be continued across multiple invocations. + +**How it works:** + +* Each subagent execution is assigned a unique `agentId` +* The agent's conversation is stored in a separate transcript file: `agent-{agentId}.jsonl` +* You can resume a previous agent by providing its `agentId` via the `resume` parameter +* When resumed, the agent continues with full context from its previous conversation + +**Example workflow:** + +Initial invocation: + +``` +> Use the code-analyzer agent to start reviewing the authentication module + +[Agent completes initial analysis and returns agentId: "abc123"] +``` + +Resume the agent: + +``` +> Resume agent abc123 and now analyze the authorization logic as well + +[Agent continues with full context from previous conversation] +``` + +**Use cases:** + +* **Long-running research**: Break down large codebase analysis into multiple sessions +* **Iterative refinement**: Continue refining a subagent's work without losing context +* **Multi-step workflows**: Have a subagent work on related tasks sequentially while maintaining context + +**Technical details:** + +* Agent transcripts are stored in your project directory +* Recording is disabled during resume to avoid duplicating messages +* Both synchronous and asynchronous agents can be resumed +* The `resume` parameter accepts the agent ID from a previous execution + +**Programmatic usage:** + +If you're using the Agent SDK or interacting with the AgentTool directly, you can pass the `resume` parameter: + +```typescript theme={null} +{ + "description": "Continue analysis", + "prompt": "Now examine the error handling patterns", + "subagent_type": "code-analyzer", + "resume": "abc123" // Agent ID from previous execution +} +``` + + + Keep track of agent IDs for tasks you may want to resume later. Claude Code displays the agent ID when a subagent completes its work. + + ## Performance considerations * **Context efficiency**: Agents help preserve main context, enabling longer overall sessions @@ -381,7 +559,12 @@ Claude Code intelligently selects subagents based on context. Make your `descrip ## Related documentation -* [Plugins](/en/docs/claude-code/plugins) - Extend Claude Code with custom agents through plugins -* [Slash commands](/en/docs/claude-code/slash-commands) - Learn about other built-in commands -* [Settings](/en/docs/claude-code/settings) - Configure Claude Code behavior -* [Hooks](/en/docs/claude-code/hooks) - Automate workflows with event handlers +* [Plugins](/en/plugins) - Extend Claude Code with custom agents through plugins +* [Slash commands](/en/slash-commands) - Learn about other built-in commands +* [Settings](/en/settings) - Configure Claude Code behavior +* [Hooks](/en/hooks) - Automate workflows with event handlers + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/terminal-config.md b/skills/working-with-claude-code/references/terminal-config.md index 1c7c193..8abe007 100644 --- a/skills/working-with-claude-code/references/terminal-config.md +++ b/skills/working-with-claude-code/references/terminal-config.md @@ -6,11 +6,11 @@ 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/docs/claude-code/statusline) to display contextual information like the current model, working directory, or git branch at the bottom of your terminal. +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 linebreaks into Claude Code: +You have several options for entering line breaks into Claude Code: * **Quick escape**: Type `\` followed by Enter to create a newline * **Keyboard shortcut**: Set up a keybinding to insert a newline @@ -48,7 +48,7 @@ Note that these notifications are specific to iTerm 2 and not available in the d #### Custom notification hooks -For advanced notification handling, you can create [notification hooks](/en/docs/claude-code/hooks#notification) to run your own logic. +For advanced notification handling, you can create [notification hooks](/en/hooks#notification) to run your own logic. ### Handling large inputs @@ -67,3 +67,8 @@ 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` * Editing: `x`, `dw`/`de`/`db`/`dd`/`D`, `cw`/`ce`/`cb`/`cc`/`C`, `.` (repeat) + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/third-party-integrations.md b/skills/working-with-claude-code/references/third-party-integrations.md index 170f25f..2f57ebb 100644 --- a/skills/working-with-claude-code/references/third-party-integrations.md +++ b/skills/working-with-claude-code/references/third-party-integrations.md @@ -13,6 +13,7 @@ This page provides an overview of available deployment options and helps you cho Anthropic Amazon Bedrock Google Vertex AI + Microsoft Foundry @@ -22,6 +23,7 @@ This page provides an overview of available deployment options and helps you cho 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/) @@ -29,13 +31,15 @@ This page provides an overview of available deployment options and helps you cho Enabled by default Enabled by default Enabled by default + Enabled by default Authentication API key - AWS credentials (IAM) - GCP credentials (OAuth/Service Account) + API key or AWS credentials + GCP credentials + API key or Microsoft Entra ID @@ -43,6 +47,7 @@ This page provides an overview of available deployment options and helps you cho Dashboard AWS Cost Explorer GCP Billing + Azure Cost Management @@ -50,30 +55,35 @@ This page provides an overview of available deployment options and helps you cho Teams, usage monitoring IAM policies, CloudTrail IAM roles, Cloud Audit Logs + RBAC policies, Azure Monitor ## Cloud providers - - - Use Claude models through AWS infrastructure with IAM-based authentication and AWS-native monitoring + + + Use Claude models through AWS infrastructure with API key or IAM-based authentication and AWS-native monitoring - + Access Claude models via Google Cloud Platform with enterprise-grade security and compliance + + + Access Claude through Azure with API key or Microsoft Entra ID authentication and Azure billing + ## Corporate infrastructure - + Configure Claude Code to work with your organization's proxy servers and SSL/TLS requirements - + Deploy centralized model access with usage tracking, budgeting, and audit logging @@ -117,6 +127,33 @@ export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock' export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # If gateway handles AWS auth ``` +### Using Foundry with corporate proxy + +Route Azure traffic through a corporate HTTP/HTTPS proxy: + +```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' +``` + +### Using Foundry with LLM Gateway + +Use a gateway service that provides Azure-compatible endpoints: + +```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 +``` + ### Using Vertex AI with corporate proxy Route Vertex AI traffic through a corporate HTTP/HTTPS proxy: @@ -181,7 +218,7 @@ Best for organizations that: When debugging your deployment: -* Use the `claude /status` [slash command](/en/docs/claude-code/slash-commands). This command provides observability into any applied authentication, proxy, and URL settings. +* Use the `claude /status` [slash command](/en/slash-commands). This command provides observability into any applied authentication, proxy, and URL settings. * Set environment variable `export ANTHROPIC_LOG=debug` to log requests. ## Best practices for organizations @@ -193,7 +230,7 @@ We strongly recommend investing in documentation so that Claude Code understands * **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](/en/docs/claude-code/memory). + [Learn more](/en/memory). ### 2. Simplify deployment @@ -205,18 +242,24 @@ Encourage new users to try Claude Code for codebase Q\&A, or on smaller bug fixe ### 4. 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/docs/claude-code/security). +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). ### 5. 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/docs/claude-code/mcp). +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! +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 -* [Set up Amazon Bedrock](/en/docs/claude-code/amazon-bedrock) for AWS-native deployment -* [Configure Google Vertex AI](/en/docs/claude-code/google-vertex-ai) for GCP deployment -* [Configure Enterprise Network](/en/docs/claude-code/network-config) for network requirements -* [Deploy LLM Gateway](/en/docs/claude-code/llm-gateway) for enterprise management -* [Settings](/en/docs/claude-code/settings) for configuration options and environment variables +* [Set up Amazon Bedrock](/en/amazon-bedrock) for AWS-native deployment +* [Configure Google Vertex AI](/en/google-vertex-ai) for GCP deployment +* [Set up Microsoft Foundry](/en/microsoft-foundry) for Azure deployment +* [Configure Enterprise Network](/en/network-config) for network requirements +* [Deploy LLM Gateway](/en/llm-gateway) for enterprise management +* [Settings](/en/settings) for configuration options and environment variables + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/troubleshooting.md b/skills/working-with-claude-code/references/troubleshooting.md index 9282123..08d0f5f 100644 --- a/skills/working-with-claude-code/references/troubleshooting.md +++ b/skills/working-with-claude-code/references/troubleshooting.md @@ -50,13 +50,13 @@ export PATH="$HOME/.nvm/versions/node/$(node -v)/bin:$PATH" ``` - Avoid disabling Windows PATH importing (`appendWindowsPath = false`) as this breaks the ability to easily call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development. + 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. ### 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 (eg. `/usr`, or `/usr/local`). +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 @@ -101,30 +101,6 @@ This command installs the appropriate build of Claude Code for your operating sy Make sure that you have the installation directory in your system PATH. -#### Alternative solution: Migrate to local installation - -Alternatively, if Claude Code will run, you can migrate to a local installation: - -```bash theme={null} -claude migrate-installer -``` - -This moves Claude Code to `~/.claude/local/` and sets up an alias in your shell configuration. No `sudo` is required for future updates. - -After migration, restart your shell, and then verify your installation: - -On macOS/Linux/WSL: - -```bash theme={null} -which claude # Should show an alias to ~/.claude/local/claude -``` - -On Windows: - -```powershell theme={null} -where claude # Should show path to claude executable -``` - Verify installation: ```bash theme={null} @@ -136,7 +112,7 @@ claude doctor # Check installation health ### 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/docs/claude-code/iam#configuring-permissions). +to run without approval using the `/permissions` command. See [Permissions docs](/en/iam#configuring-permissions). ### Authentication issues @@ -155,6 +131,48 @@ 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, allowed tools) | +| `.mcp.json` | Project MCP servers (checked into source control) | +| `managed-settings.json` | [Enterprise managed settings](/en/settings#settings-files) | +| `managed-mcp.json` | [Enterprise managed MCP servers](/en/mcp#enterprise-mcp-configuration) | + +On Windows, `~` refers to your user home directory, such as `C:\Users\YourName`. + +**Enterprise managed file locations:** + +* macOS: `/Library/Application Support/ClaudeCode/` +* Linux/WSL: `/etc/claude-code/` +* Windows: `C:\ProgramData\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, allowed tools, MCP server configurations, and session history. + + ## Performance and stability ### High CPU or memory usage @@ -193,7 +211,7 @@ apk add ripgrep pacman -S ripgrep ``` -Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/docs/claude-code/settings#environment-variables). +Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/settings#environment-variables). ### Slow or incomplete search results on WSL @@ -252,15 +270,21 @@ 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 [IDE integration guide](/en/docs/claude-code/ide-integrations#jetbrains-plugin-settings). +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, please [create an issue](https://github.com/anthropics/claude-code/issues) with the following information: whether you are native (git bash), or WSL1/WSL2, WSL networking mode (NAT or mirrored), IDE name/version, Claude Code extension/plugin version, and shell type (bash/zsh/etc) +If you're experiencing IDE integration problems on Windows, [create an issue](https://github.com/anthropics/claude-code/issues) with the following information: -### ESC key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals +* 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. -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. +### 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: @@ -270,7 +294,7 @@ To fix this issue: * 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. +This allows the `Esc` key to properly interrupt Claude Code operations. ## Markdown formatting issues @@ -300,9 +324,9 @@ function example() { **Solutions:** -1. **Ask Claude to add language tags**: Simply request "Please add appropriate language tags to all code blocks in this markdown file." +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 the [markdown formatting hook example](/en/docs/claude-code/hooks-guide#markdown-formatting-hook) for implementation details. +2. **Use post-processing hooks**: Set up automatic formatting hooks to detect and add missing language tags. See the [markdown formatting hook example](/en/hooks-guide#markdown-formatting-hook) for implementation details. 3. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed. @@ -316,14 +340,14 @@ If generated markdown has excessive blank lines or inconsistent spacing: 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/docs/claude-code/memory) 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/docs/claude-code/memory) +* **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 @@ -334,3 +358,8 @@ If you're experiencing issues not covered here: 2. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues 3. Run `/doctor` to check the health of your Claude Code installation 4. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/vs-code.md b/skills/working-with-claude-code/references/vs-code.md index 138d40b..3d55b96 100644 --- a/skills/working-with-claude-code/references/vs-code.md +++ b/skills/working-with-claude-code/references/vs-code.md @@ -1,8 +1,8 @@ # Visual Studio Code -> Use Claude Code with Visual Studio Code through our native extension or CLI integration +> Use Claude Code with Visual Studio Code through the native extension or CLI integration -Claude Code VS Code Extension Interface +Claude Code VS Code Extension Interface ## VS Code Extension (Beta) @@ -15,9 +15,10 @@ The VS Code extension provides: * **Native IDE experience**: Dedicated Claude Code sidebar panel accessed via the Spark icon * **Plan mode with editing**: Review and edit Claude's plans before accepting them * **Auto-accept edits mode**: Automatically apply Claude's changes as they're made +* **Extended thinking**: Toggle extended thinking on/off using the Extended Thinking button in the bottom-right corner of the prompt input * **File management**: @-mention files or attach files and images using the system file picker * **MCP server usage**: Use Model Context Protocol servers configured through the CLI -* **Conversation history**: Easy access to past conversations +* **Conversation history**: Access to past conversations * **Multiple sessions**: Run multiple Claude Code sessions simultaneously * **Keyboard shortcuts**: Support for most shortcuts from the CLI * **Slash commands**: Access most CLI slash commands directly in the extension @@ -30,15 +31,7 @@ The VS Code extension provides: Download and install the extension from the [Visual Studio Code Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code). -### Updating - -To update the VS Code extension: - -1. Open the VS Code command palette with `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux) -2. Search for "Claude Code: Update" -3. Select the command to update to the latest version - -### How It Works +### How it works Once installed, you can start using Claude Code through the VS Code interface: @@ -46,50 +39,57 @@ Once installed, you can start using Claude Code through the VS Code interface: 2. Prompt Claude Code in the same way you would in the terminal 3. Watch as Claude analyzes your code and suggests changes 4. Review and accept edits directly in the interface - * **Tip**: Drag the sidebar wider to see inline diffs, then click on them to expand for full details + * **Tip**: Drag the sidebar wider to see inline diffs, then click them to expand for full details -### Using Third-Party Providers (Vertex and Bedrock) +### Configuration -The VS Code extension supports using Claude Code with third-party providers like Amazon Bedrock and Google Vertex AI. When configured with these providers, the extension will not prompt for login. To use third-party providers, configure environment variables in the VS Code extension settings: +The VS Code extension reads the same `settings.json` files as the CLI. See the [settings documentation](/en/settings) for details. -1. Open VS Code settings -2. Search for "Claude Code: Environment Variables" -3. Add the required environment variables +#### Third-party providers and gateways -#### Environment Variables +To use the VS Code extension with third-party providers (Amazon Bedrock, Google Vertex AI, Microsoft Foundry) or gateways that handle authentication: -| Variable | Description | Required | Example | -| :---------------------------- | :------------------------------------- | :--------------------- | :----------------------------------------------- | -| `CLAUDE_CODE_USE_BEDROCK` | Enable Amazon Bedrock integration | Required for Bedrock | `"1"` or `"true"` | -| `CLAUDE_CODE_USE_VERTEX` | Enable Google Vertex AI integration | Required for Vertex AI | `"1"` or `"true"` | -| `ANTHROPIC_API_KEY` | API key for third-party access | Required | `"your-api-key"` | -| `AWS_REGION` | AWS region for Bedrock | | `"us-east-2"` | -| `AWS_PROFILE` | AWS profile for Bedrock authentication | | `"your-profile"` | -| `CLOUD_ML_REGION` | Region for Vertex AI | | `"global"` or `"us-east5"` | -| `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID for Vertex AI | | `"your-project-id"` | -| `ANTHROPIC_MODEL` | Override primary model | Override model ID | `"us.anthropic.claude-3-7-sonnet-20250219-v1:0"` | -| `ANTHROPIC_SMALL_FAST_MODEL` | Override small/fast model | Optional | `"us.anthropic.claude-3-5-haiku-20241022-v1:0"` | +1. Add the appropriate environment variables for your provider or gateway to your Claude Code `settings.json`: + ```json theme={null} + { + "env": { + "CLAUDE_CODE_USE_BEDROCK": "1", + "AWS_REGION": "us-east-2", + "AWS_PROFILE": "your-profile" + } + } + ``` + +2. Disable the VS Code extension login prompt via [`vscode://settings/claudeCode.disableLoginPrompt`](vscode://settings/claudeCode.disableLoginPrompt) or in VS Code's settings: + ```json theme={null} + { + "claudeCode.disableLoginPrompt": true + } + ``` For detailed setup instructions and additional configuration options, see: -* [Claude Code on Amazon Bedrock](/en/docs/claude-code/amazon-bedrock) -* [Claude Code on Google Vertex AI](/en/docs/claude-code/google-vertex-ai) +* [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) -### Not Yet Implemented +### Not yet implemented -The following features are not yet available in the VS Code extension: +The following features aren't yet available in the VS Code extension: -* **Full MCP server configuration**: You need to [configure MCP servers through the CLI](/en/docs/claude-code/mcp) first, then the extension will use them -* **Subagents configuration**: Configure [subagents through the CLI](/en/docs/claude-code/sub-agents) to use them in VS Code +* **MCP server and Plugin configuration UI**: Type `/mcp` to open the terminal-based MCP server configuration, or `/plugin` for Plugin configuration. Once configured, MCP servers and Plugins work in the extension. You can also [configure MCP servers through the CLI](/en/mcp) first, then the extension will use them. +* **Subagents configuration**: Configure [subagents through the CLI](/en/sub-agents) to use them in VS Code * **Checkpoints**: Save and restore conversation state at specific points +* **Conversation rewinding**: The `/rewind` command is coming soon * **Advanced shortcuts**: - * `#` shortcut to add to memory - * `!` shortcut to run bash commands directly + * `#` shortcut to add to memory (not supported) + * `!` shortcut to run bash commands directly (not supported) * **Tab completion**: File path completion with tab key +* **Model selection UI for older models**: To use older model versions like `claude-sonnet-4-20250514`, open VS Code settings for Claude Code (the `/General Config` command) and insert the model string directly into the 'Selected Model' field -We are working on adding these features in future updates. +These features are planned for future updates. -## Security Considerations +## Security considerations When Claude Code runs in VS Code 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. @@ -99,23 +99,32 @@ When running in VS Code, consider: * Using manual approval mode for edits * Taking extra care to ensure Claude is only used with trusted prompts -## Legacy CLI Integration +## Legacy CLI integration -The first VS Code integration that we released allows Claude Code running in the terminal to interact with your IDE. It provides selection context sharing (current selection/tab is automatically shared with Claude Code), diff viewing in the IDE instead of terminal, file reference shortcuts (`Cmd+Option+K` on Mac or `Alt+Ctrl+K` on Windows/Linux to insert file references like @File#L1-99), and automatic diagnostic sharing (lint and syntax errors). +The original VS Code integration allows Claude Code running in the terminal to interact with your IDE. It provides selection context sharing (current selection/tab is automatically shared with Claude Code), diff viewing in the IDE instead of terminal, file reference shortcuts (`Cmd+Option+K` on Mac or `Alt+Ctrl+K` on Windows/Linux to insert file references like @File#L1-99), and automatic diagnostic sharing (lint and syntax errors). -The legacy integration auto-installs when you run `claude` from VS Code's integrated terminal. Simply run `claude` from the terminal and all features activate. For external terminals, use the `/ide` command to connect Claude Code to your VS Code instance. To configure, run `claude`, enter `/config`, and set the diff tool to `auto` for automatic IDE detection. +The legacy integration auto-installs when you run `claude` from VS Code's integrated terminal. Run `claude` from the terminal and all features activate. For external terminals, use the `/ide` command to connect Claude Code to your VS Code instance. To configure, run `claude`, enter `/config`, and set the diff tool to `auto` for automatic IDE detection. Both the extension and CLI integration work with Visual Studio Code, Cursor, Windsurf, and VSCodium. ## Troubleshooting -### Extension Not Installing +### Extension not installing * Ensure you have a compatible version of VS Code (1.85.0 or later) * Check that VS Code has permission to install extensions -* Try installing directly from the marketplace website +* Try installing directly from the Marketplace website + +### Claude Code never responds -### Legacy Integration Not Working +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 +4. **File a bug report**: If the problem continues, [file an issue on GitHub](https://github.com/anthropics/claude-code/issues) with details about the error + +### Legacy integration not working * Ensure you're running Claude Code from VS Code's integrated terminal * Ensure the CLI for your IDE variant is installed: @@ -125,6 +134,11 @@ Both the extension and CLI integration work with Visual Studio Code, Cursor, Win * VSCodium: `codium` command should be available * If the command isn't installed: 1. Open command palette with `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux) - 2. Search for "Shell Command: Install 'code' command in PATH" (or equivalent for your IDE) + 2. Search for `Shell Command: Install 'code' command in PATH` (or equivalent for your IDE) + +For additional help, see the [troubleshooting guide](/en/troubleshooting). + + +--- -For additional help, see our [troubleshooting guide](/en/docs/claude-code/troubleshooting). +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file From a3cc3db819482a73de4b6587bffd95cea69884eb Mon Sep 17 00:00:00 2001 From: Chris Vaillancourt Date: Fri, 12 Dec 2025 17:04:35 -0800 Subject: [PATCH 5/7] docs: add upstream improvement context and fix documentation --- docs/upstream-improvements-context.md | 991 ++++++++++++++++++++ docs/working-with-claude-code-update-fix.md | 186 ++++ 2 files changed, 1177 insertions(+) create mode 100644 docs/upstream-improvements-context.md create mode 100644 docs/working-with-claude-code-update-fix.md diff --git a/docs/upstream-improvements-context.md b/docs/upstream-improvements-context.md new file mode 100644 index 0000000..3a1aa96 --- /dev/null +++ b/docs/upstream-improvements-context.md @@ -0,0 +1,991 @@ +# Upstream Improvements: Context Document + +**Purpose**: Comprehensive documentation of issues discovered and solutions developed for contributing upstream to `superpowers-developing-for-claude-code` and `episodic-memory` plugins. + +**Date**: December 8-9, 2025 +**Sessions**: +- Session 1: 1ee8e950-09c9-4792-bb88-699c14da6408 (Dec 8, 6:27 PM) +- Session 2: 0c4ed174-0e5c-47d5-a7a1-2148a48b4ee0 (Dec 8, 6:49 PM - current) + +--- + +## Table of Contents + +1. [Issue #1: update_docs.js Script Failure](#issue-1-update_docsjs-script-failure) +2. [Issue #2: episodic-memory Setup and Usage](#issue-2-episodic-memory-setup-and-usage) +3. [Key Learnings](#key-learnings) +4. [Recommendations for Upstream](#recommendations-for-upstream) + +--- + +## Issue #1: update_docs.js Script Failure + +### Problem Statement + +The `update_docs.js` script in the `working-with-claude-code` skill fails with HTTP 401 error when attempting to fetch Claude Code documentation. + +**Error Output**: +``` +❌ Error: HTTP 401: Unauthorized +🚀 Claude Code Documentation Updater +📥 Fetching llms.txt... +``` + +**Script Location**: +``` +~/.claude/plugins/cache/superpowers-marketplace/superpowers-developing-for-claude-code/0.3.1/skills/working-with-claude-code/scripts/update_docs.js +``` + +### Root Cause Analysis + +#### Initial Investigation (Dec 8, 6:27 PM - Session 1) + +1. **Examined the failing script**: + - Located at: `skills/working-with-claude-code/scripts/update_docs.js` + - Script attempts to fetch: `https://docs.claude.com/llms.txt` + - Pattern matching: `/https:\/\/docs\.claude\.com\/en\/docs\/claude-code\/[^\s)]+\.md/g` + +2. **Tested the endpoint directly**: + ```bash + # Using WebFetch tool + WebFetch(url='https://docs.claude.com/llms.txt') + # Result: Request failed with status code 401 + ``` + +3. **Searched for documentation location**: + ``` + WebSearch: "docs.claude.com Claude Code documentation 2025" + ``` + + **Discovery**: Documentation moved from `docs.claude.com` to `code.claude.com` + +4. **Verified new location**: + ```bash + WebFetch(url='https://code.claude.com/docs/en/overview') + # Result: Success! Documentation found at new domain + ``` + +5. **Tested for llms.txt at new domain**: + ```bash + WebFetch(url='https://code.claude.com/llms.txt') + # Result: 302 redirect to https://www.claude.com/product/claude-code + # Conclusion: No llms.txt available at new domain + ``` + +#### Root Cause Summary + +1. **Domain migration**: Claude Code documentation moved from `docs.claude.com` → `code.claude.com` +2. **Authentication requirement**: `llms.txt` endpoint now requires authentication (returns 401) +3. **No replacement endpoint**: New domain doesn't provide a public `llms.txt` equivalent +4. **Documentation structure**: New docs at `code.claude.com/docs/en/[page-name]` + +### Solution Development + +#### Approach 1: Dynamic Discovery (Attempted) + +**Tried**: Finding a documentation index or sitemap +- Checked for `llms.txt` at new domain → 302 redirect +- Looked for sitemap.xml → Not found +- Checked for doc map → No public endpoint + +**Result**: No dynamic discovery method available + +#### Approach 2: Hardcoded List (Implemented) + +**Rationale**: +- Documentation structure is stable +- Pages are well-known and documented +- Better than broken script + +**Implementation Steps**: + +1. **Extracted documentation structure** from `code.claude.com/docs/en/overview` + - Found 43 documentation pages organized by category + - Verified each page is accessible + +2. **Created hardcoded list**: + ```javascript + const DOC_PAGES = [ + // Getting Started (4 pages) + 'overview.md', + 'quickstart.md', + 'common-workflows.md', + 'claude-code-on-the-web.md', + + // Build with Claude Code (7 pages) + 'sub-agents.md', + 'plugins.md', + 'skills.md', + 'output-styles.md', + 'hooks-guide.md', + 'headless.md', + 'github-actions.md', + + // CI/CD Integration (1 page) + 'gitlab-ci-cd.md', + + // Advanced Integration (1 page) + 'mcp.md', + + // Troubleshooting (1 page) + 'troubleshooting.md', + + // Deployment (7 pages) + 'third-party-integrations.md', + 'amazon-bedrock.md', + 'google-vertex-ai.md', + 'network-config.md', + 'llm-gateway.md', + 'devcontainer.md', + 'sandboxing.md', + + // Administration (8 pages) + 'setup.md', + 'iam.md', + 'security.md', + 'data-usage.md', + 'monitoring-usage.md', + 'costs.md', + 'analytics.md', + 'plugin-marketplaces.md', + + // Configuration (6 pages) + 'settings.md', + 'vs-code.md', + 'jetbrains.md', + 'terminal-config.md', + 'model-config.md', + 'memory.md', + + // Reference (7 pages) + 'cli-reference.md', + 'interactive-mode.md', + 'slash-commands.md', + 'checkpointing.md', + 'hooks.md', + 'plugins-reference.md', + 'statusline.md', + + // Resources (1 page) + 'legal-and-compliance.md' + ]; + ``` + +3. **Updated constants**: + ```javascript + // OLD: + const LLMS_TXT_URL = 'https://docs.claude.com/llms.txt'; + const CLAUDE_CODE_PATTERN = /https:\/\/docs\.claude\.com\/en\/docs\/claude-code\/[^\s)]+\.md/g; + + // NEW: + const DOCS_BASE_URL = 'https://code.claude.com/docs/en'; + ``` + +4. **Replaced getClaudeCodeUrls function**: + ```javascript + // OLD: async function that fetched and parsed llms.txt + async function getClaudeCodeUrls() { + console.log('📥 Fetching llms.txt...'); + const content = await fetchUrl(LLMS_TXT_URL); + const urls = new Set(); + const matches = content.matchAll(CLAUDE_CODE_PATTERN); + for (const match of matches) { + urls.add(match[0]); + } + return Array.from(urls).sort(); + } + + // NEW: Simple map over hardcoded list + async function getClaudeCodeUrls() { + return DOC_PAGES.map(page => `${DOCS_BASE_URL}/${page}`); + } + ``` + +5. **Cleaned up console output** (removed emojis for cleaner logs): + ```javascript + // OLD: + console.log('🚀 Claude Code Documentation Updater\n'); + console.log(`✅ Found ${urls.length} Claude Code documentation pages\n`); + console.log('📥 Downloading documentation...'); + console.log(`\n✅ Documentation update complete!`); + console.log(`\n📁 Documentation saved to: ${REFERENCES_DIR}`); + + // NEW: + console.log('Claude Code Documentation Updater\n'); + console.log(`Found ${urls.length} Claude Code documentation pages\n`); + console.log('Downloading documentation...'); + console.log(`\nDocumentation update complete!`); + console.log(`\nDocumentation saved to: ${REFERENCES_DIR}`); + ``` + +### Testing and Verification + +#### First Test (Session 1) + +```bash +cd ~/.claude/plugins/cache/superpowers-marketplace/superpowers-developing-for-claude-code/0.3.1/skills/working-with-claude-code +node scripts/update_docs.js +``` + +**Output**: +``` +Claude Code Documentation Updater + +Found 44 Claude Code documentation pages + +Downloading documentation... + Fetching overview.md... + Fetching quickstart.md... + [... 41 more files ...] + +Documentation update complete! + 43 files downloaded successfully + 1 files failed to download + +Documentation saved to: [...]/references +``` + +**Failure**: `migration-guide.md` returned 404 (doesn't exist on server) + +#### Fix Applied + +Removed `migration-guide.md` from `DOC_PAGES` list (line 43 originally). + +#### Second Test + +```bash +node scripts/update_docs.js +``` + +**Result**: All 43 files downloaded successfully ✓ + +**Verified files**: +```bash +ls ~/.claude/plugins/cache/.../references/ | wc -l +# Output: 43 +``` + +### Additional Changes Required + +#### Updated SKILL.md Documentation + +**File**: `skills/working-with-claude-code/SKILL.md` + +**Changes Made**: + +1. **Line 10**: Updated domain reference + ```markdown + + This skill provides complete, authoritative documentation for Claude Code directly from docs.claude.com. + + + This skill provides complete, authoritative documentation for Claude Code directly from code.claude.com. + ``` + +2. **Lines 79-85**: Updated file list (added `sandboxing.md`, removed `migration-guide.md`) + ```markdown + + ├── devcontainer.md # Dev container support + ├── sandboxing.md # Sandboxing security features + ├── github-actions.md # GitHub Actions integration + ├── gitlab-ci-cd.md # GitLab CI/CD integration + ├── third-party-integrations.md # Other integrations + ├── legal-and-compliance.md # Legal information + └── troubleshooting.md # Troubleshooting guide + ``` + +3. **Lines 124-139**: Updated script description + ```markdown + + The script: + 1. Fetches llms.txt from docs.claude.com + 2. Extracts all Claude Code documentation URLs + 3. Downloads each page to `references/` + 4. Reports success/failures + + + The script: + 1. Uses a curated list of 43 Claude Code documentation pages + 2. Fetches each page from code.claude.com/docs/en/ + 3. Downloads each page to `references/` + 4. Reports success/failures + ``` + +### Critical Issue: Reproducibility + +**The Problem We Experienced**: + +This exact issue was encountered and solved **twice** in two separate sessions: +- Session 1: Dec 8, 6:27 PM (1ee8e950-09c9-4792-bb88-699c14da6408) +- Session 2: Dec 8, 6:49 PM (0c4ed174-0e5c-47d5-a7a1-2148a48b4ee0) + +**Both sessions**: +1. Encountered the same 401 error +2. Debugged the same root cause +3. Implemented the identical solution +4. Wasted ~30 minutes of duplicate work + +**Why This Happened**: +- No access to previous session context +- Fix lives in plugin cache (non-persistent location) +- No episodic memory set up yet +- No upstream contribution of the fix + +**This demonstrates**: +1. The fix needs to go upstream (affects all users) +2. The importance of episodic-memory for continuity +3. Plugin cache changes are ephemeral + +### Files Modified + +**1. update_docs.js** +- Location: `skills/working-with-claude-code/scripts/update_docs.js` +- Lines changed: 6-7, 16-112 (essentially complete rewrite) +- Status: Tested and working + +**2. SKILL.md** +- Location: `skills/working-with-claude-code/SKILL.md` +- Lines changed: 10, 79-85, 124-139 +- Status: Documentation updated + +### Complete Working Solution + +The complete fixed `update_docs.js` is in the current session context (system reminder shows the full file). Key characteristics: + +- **43 documentation pages** (migration-guide.md removed) +- **New domain**: code.claude.com/docs/en/ +- **No external dependencies**: Hardcoded list eliminates authentication issues +- **Backwards compatible**: Same output format and directory structure +- **Tested**: Successfully downloads all 43 files + +--- + +## Issue #2: episodic-memory Setup and Usage + +### Problem Statement + +User attempted to install episodic-memory globally via npm/pnpm but received 404 error. Additionally, after installing as a Claude Code plugin, the functionality wasn't immediately available and required manual configuration. + +### Initial Problem: npm Package 404 + +#### What Was Tried + +```bash +sfw pnpm add -g episodic-memory +# Error: ERR_PNPM_FETCH_404 GET https://registry.npmjs.org/episodic-memory: Not Found - 404 +``` + +#### Investigation Steps + +1. **Checked npm registry**: + - Searched npmjs.com for "episodic-memory" + - Package does not exist on npm + +2. **Examined GitHub repository**: + - URL: https://github.com/obra/episodic-memory + - Found `package.json` with package name "episodic-memory" + - Repository exists but package is NOT published to npm + +3. **Checked plugin installation**: + - Plugin was installed via: `/plugin install episodic-memory@superpowers-marketplace` + - Plugin location: `~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/` + +#### Root Cause + +**episodic-memory is NOT an npm package**. It's exclusively distributed as a Claude Code plugin through the superpowers-marketplace. + +**Evidence**: +```json +// package.json exists but package is not published +{ + "name": "episodic-memory", + "version": "1.0.13", + "description": "Semantic search for Claude Code conversations", + // ... but NO npm publish workflow +} +``` + +### Setup Process Discovered + +#### Correct Installation Method + +```bash +# Inside Claude Code +/plugin install episodic-memory@superpowers-marketplace +``` + +**What This Does**: +1. Downloads plugin to `~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/` +2. Installs CLI tools to `cli/` subdirectory +3. Exposes MCP tools: `episodic-memory__search` and `episodic-memory__read` +4. Sets up session-end hook (supposed to auto-index) + +#### Initial Sync Required + +**Problem**: After installation, attempting to search returned no results. + +**Debugging Steps**: + +1. **Tested MCP search tool**: + ```javascript + mcp__plugin_episodic-memory_episodic-memory__search({ + query: "update docs script documentation code.claude.com", + after: "2025-12-04", + limit: 10 + }) + // Result: No results found + ``` + +2. **Verified conversations exist**: + ```bash + ls ~/.claude/projects/-Users-chris-dev-github-chrisvaillancourt-claude-code-skills/*.jsonl + # Found multiple .jsonl files with recent timestamps + ``` + +3. **Checked for archive directory**: + ```bash + find ~/.claude -name "*episodic*" -type d + # Found: ~/.claude/plugins/cache/superpowers-marketplace/episodic-memory + # But no archive directory yet + ``` + +4. **Located CLI tools**: + ```bash + ls ~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/ + # Found: episodic-memory, episodic-memory-search, index-conversations, etc. + ``` + +5. **Ran manual sync**: + ```bash + ~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory sync + ``` + +**Sync Output**: +``` +Syncing conversations... +Source: /Users/chris/.claude/projects +Destination: /Users/chris/.config/superpowers/conversation-archive + +Loading embedding model (first run may take time)... +Embedding model loaded +Generating summaries for 10 conversation(s)... + (250 more need summaries - will process on next sync) + Summarizing 21aab2fc-7a77-4d5e-bcbb-e647d1e5e543.jsonl (9 exchanges)... + Summarizing 5f154d95-0b3a-4e11-a45c-3c2d64c44286.jsonl (2 exchanges)... + Summarizing 8713580b-4160-4b76-af4b-de02adccfe09.jsonl (1 exchanges)... + Summarizing b1f9d608-4efa-4317-be82-0f0010de68bf.jsonl (4 exchanges)... + +✅ Sync complete! + Copied: 715 + Skipped: 0 + Indexed: 714 + Summarized: 4 + 68.97s user 2.27s system 134% cpu 52.937 total +``` + +**Key Discovery**: Manual sync was required on first use. Archive created at: +``` +~/.config/superpowers/conversation-archive +``` + +### CLI Tools Usage + +#### Available Commands + +Located in: `~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/` + +**Files**: +- `episodic-memory` - Main CLI entry point +- `episodic-memory.js` - Main implementation +- `episodic-memory-search` - Search wrapper +- `index-conversations` - Indexing tool +- `index-conversations.js` - Indexing implementation +- `mcp-server` - MCP server wrapper +- `mcp-server-wrapper.js` - MCP implementation +- `search-conversations` - Search implementation + +#### Working Commands + +**1. Sync Conversations**: +```bash +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory sync +``` +- Copies from: `~/.claude/projects` +- Copies to: `~/.config/superpowers/conversation-archive` +- Creates embeddings for semantic search +- Generates summaries (processes 10 per run, incrementally) + +**2. Search Conversations**: +```bash +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory search "query string" --limit 10 +``` + +**Example Search**: +```bash +episodic-memory search "update docs script code.claude.com documentation" --limit 3 +``` + +**Output**: +``` +Loading embedding model (first run may take time)... +Embedding model loaded +Found 3 relevant conversations: + +1. [-Users-chris-dev-github-chrisvaillancourt-claude-code-skills, 2025-12-09] - 21% match + "Update the Claude Code documentation in the working-with-claude-code skill" + Lines 8-11 in /Users/chris/.config/superpowers/conversation-archive/-Users-chris-dev-github-chrisvaillancourt-claude-code-skills/1ee8e950-09c9-4792-bb88-699c14da6408.jsonl (288.7KB, 119 lines) +``` + +**3. Show Conversation**: +```bash +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory show /path/to/conversation.jsonl --start 1 --end 30 +``` + +Displays formatted conversation with: +- Metadata (session ID, git branch, working directory) +- Timestamped messages +- Tool uses and results +- Markdown formatting + +**4. Statistics**: +```bash +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory stats +``` +(Note: Command exists but wasn't tested in our sessions) + +### MCP Tools (Once Synced) + +After manual sync, MCP tools became functional: + +**1. Search Tool**: +```javascript +mcp__plugin_episodic-memory_episodic-memory__search({ + query: "update docs script", + after: "2025-12-04", + limit: 10, + mode: "both" // "vector", "text", or "both" +}) +``` + +**2. Read Tool**: +```javascript +mcp__plugin_episodic-memory_episodic-memory__read({ + path: "/path/to/conversation.jsonl", + startLine: 1, + endLine: 50 +}) +``` + +### Known Issues from GitHub + +**Repository**: https://github.com/obra/episodic-memory + +**Critical Open Issues** (as of Dec 8, 2025): + +1. **Issue #31**: MCP server fails to connect - missing build artifacts and incorrect plugin configuration +2. **Issue #30**: MCP tries to run bash script with `node` instead of proper interpreter +3. **Issue #27**: Episodic memory appears empty - sync needs to run automatically or prompt user on first use + - **Our experience confirms this**: Manual sync was required +4. **Issue #26**: `--background` flag fails silently (SessionStart hook broken) +5. **Issue #24**: MCP fails on exit (bug) +6. **Issue #23**: Critical: npm install resource exhaustion - 11 concurrent processes in infinite loop +7. **Issue #22**: Bug Report: Agent conversation files not being summarized +8. **Issue #21**: Failed to load hooks (bug) +9. **Issue #19**: Relies on better-sqlite3 which causes endless npm install when plugin runs for the first time +10. **Issue #16**: Agent conversations are incorrectly indexed (bug) +11. **Issue #14**: Had to manually install dependencies (bug) +12. **Issue #13**: episodic-memory fails with Exit code 127, mcp server won't start (bug) + +### What Works (Verified in Our Session) + +✅ **Installation**: `/plugin install episodic-memory@superpowers-marketplace` +✅ **Manual sync**: CLI `episodic-memory sync` command works +✅ **Archive creation**: Creates `~/.config/superpowers/conversation-archive` +✅ **Indexing**: Successfully indexed 714 conversations +✅ **Embeddings**: Generated embeddings for semantic search +✅ **Search accuracy**: Found relevant conversations (21% match for our query) +✅ **CLI search**: Direct CLI search works perfectly +✅ **Show command**: Displays conversations with formatting +✅ **MCP tools**: Work after manual sync +✅ **Incremental summaries**: Processes 10 summaries per sync (250 remaining is ok) + +### What Doesn't Work / Issues Encountered + +❌ **Auto-sync on first use**: Must run manual sync initially (Issue #27) +❌ **npm package**: Not published to npm (404 error) +❌ **CLI in PATH**: Commands not automatically available (need full path) +⚠️ **Session-end hook**: May not be working automatically (Issue #26) +⚠️ **MCP server issues**: Multiple reported problems (Issues #31, #30, #24) +⚠️ **Dependency installation**: better-sqlite3 causes issues (Issue #19, #23) + +### Successful Workflow Established + +**Initial Setup** (one-time): +```bash +# 1. Install plugin +/plugin install episodic-memory@superpowers-marketplace + +# 2. Run initial sync +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory sync + +# 3. Verify archive created +ls ~/.config/superpowers/conversation-archive +``` + +**Daily Usage**: +```bash +# Search for past conversations +episodic-memory search "topic keywords" --limit 5 + +# View a specific conversation +episodic-memory show /path/to/conversation.jsonl + +# Sync new conversations (if auto-sync not working) +episodic-memory sync +``` + +**Integration with Claude Code**: +- Use MCP search tool during sessions +- Reference past solutions to avoid duplicate work +- Build institutional knowledge across sessions + +### Architecture Discovered + +**Data Flow**: +``` +1. Conversations saved: ~/.claude/projects/[project]/[uuid].jsonl +2. Sync copies to: ~/.config/superpowers/conversation-archive/[project]/[uuid].jsonl +3. Index generates: Embeddings + summaries in SQLite database +4. Search queries: Vector similarity + text matching +5. Results ranked: Semantic similarity percentage +``` + +**Storage Locations**: +- **Source**: `~/.claude/projects/` (active sessions) +- **Archive**: `~/.config/superpowers/conversation-archive/` (persistent copy) +- **Index**: SQLite database (location not explicitly found, likely in archive dir) +- **Plugin**: `~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/` + +**Key Technologies**: +- **Embeddings**: @xenova/transformers (semantic search) +- **Database**: better-sqlite3 + sqlite-vec (vector storage) +- **MCP**: @modelcontextprotocol/sdk (tool exposure) +- **Summaries**: Generated via Claude agent + +--- + +## Key Learnings + +### 1. Plugin Cache is Ephemeral + +**Problem**: Changes to plugin files are lost when: +- Plugin updates to new version (0.3.1 → 0.3.2) +- Cache is cleared +- Plugin is reinstalled + +**Impact**: +- Our update_docs.js fix will be lost on next plugin update +- Any local customizations are non-persistent +- Upstream contribution is essential for permanence + +**Solution**: Contribute fixes upstream to source repository + +### 2. Importance of Episodic Memory + +**Without episodic memory**: +- Repeated work across sessions (we solved update_docs.js twice) +- Lost context and solutions +- Wasted ~30 minutes of duplicate debugging + +**With episodic memory**: +- Search past sessions: `episodic-memory search "topic"` +- Find previous solutions instantly +- Build institutional knowledge +- Avoid duplicate work + +**Setup is crucial**: Manual sync required on first use + +### 3. Documentation Infrastructure Matters + +**The update_docs.js failure affects**: +- Every user of the plugin +- Ability to get latest documentation +- Trust in the tooling + +**High-priority fix** because: +- Blocks core functionality (documentation updates) +- Reproducible for all users +- Simple fix with proven solution + +### 4. npm vs Plugin Distribution + +**Not all tools are npm packages**: +- episodic-memory: Plugin only (no npm) +- Must use plugin distribution channel +- CLI tools in plugin directory, not system PATH + +**Check before assuming**: Just because there's a package.json doesn't mean it's published to npm + +### 5. Manual Initialization Often Required + +**episodic-memory lesson**: +- Plugin installation ≠ ready to use +- Manual sync required on first use +- Session-end hooks may not be working +- Documentation should include setup steps + +**Better approach**: +- Detect first use and prompt for sync +- Auto-run initial sync +- Provide clear setup instructions + +--- + +## Recommendations for Upstream + +### For superpowers-developing-for-claude-code + +#### Priority 1: Fix update_docs.js (Critical) + +**Why Critical**: +- Script is broken for all users +- Blocks documentation updates +- Simple fix with proven solution + +**Proposed Changes**: + +1. **update_docs.js**: + - Change domain: `docs.claude.com` → `code.claude.com` + - Replace dynamic llms.txt fetching with hardcoded list + - Remove `migration-guide.md` (404 on server) + - Clean up console output (optional) + +2. **SKILL.md**: + - Update domain references + - Update script description + - Add `sandboxing.md`, remove `migration-guide.md` + +**Files to Modify**: +- `skills/working-with-claude-code/scripts/update_docs.js` +- `skills/working-with-claude-code/SKILL.md` + +**Testing**: +- Verified working solution +- Successfully downloads all 43 documentation pages +- No breaking changes + +**Maintenance Consideration**: +- Hardcoded list will need updates when new docs are added +- Consider adding comment: "Update this list when new docs are published" +- Could add script to verify all URLs still exist + +#### Priority 2: Document the Migration (Medium) + +**Add to CHANGELOG.md or README.md**: +- Note about documentation domain migration +- Explanation of why llms.txt approach was replaced +- Instructions for updating the list when new docs are published + +### For episodic-memory + +#### Priority 1: Fix First-Use Experience (Critical) + +**Current Problem**: Issue #27 - Episodic memory appears empty on first use + +**Our Experience Confirms**: +- MCP search returns no results immediately after installation +- Manual sync required +- No indication to user that sync is needed + +**Proposed Solutions**: + +1. **Auto-sync on first use**: + - Detect if archive directory is empty + - Automatically run sync on first MCP tool invocation + - Show progress to user + +2. **Prompt user for sync**: + - MCP tool returns helpful message: "No conversations indexed yet. Run: episodic-memory sync" + - Include sync command in installation instructions + +3. **Add setup verification**: + - Add command: `episodic-memory status` + - Shows: Archive exists? Conversations indexed? Last sync time? + +#### Priority 2: Make CLI Tools Available (Medium) + +**Current Problem**: CLI tools not in system PATH + +**Impact**: Users must use full paths: +```bash +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory +``` + +**Proposed Solutions**: + +1. **Add bin links** in plugin manifest +2. **Document the full paths** in README +3. **Create shell aliases** (document in setup guide): + ```bash + alias episodic-memory='~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory' + ``` + +#### Priority 3: Clarify npm Distribution (Low) + +**Current Confusion**: Users try `npm install -g episodic-memory` and get 404 + +**Proposed Solutions**: + +1. **Update README** to clearly state: + - "Not available on npm" + - "Install via: /plugin install episodic-memory@superpowers-marketplace" + +2. **Consider publishing to npm** if there's value: + - Would allow global installation + - Could simplify CLI access + - May help with dependency issues + +3. **Or add .npmignore** to prevent confusion: + - Clearly mark as plugin-only distribution + +#### Priority 4: Address Dependency Issues (High) + +**Related Issues**: #23, #19, #14, #13 + +**Problems**: +- better-sqlite3 causes installation loops +- Exit code 127 failures +- Manual dependency installation needed + +**Our Experience**: These didn't affect us (plugin already built), but GitHub issues show significant user impact + +**Recommended**: +- Review dependency chain +- Consider pre-built binaries +- Improve error messages for dependency failures + +--- + +## Testing Checklist for Upstream PRs + +### update_docs.js Fix + +- [ ] Clone repo: `git clone https://github.com/obra/superpowers-developing-for-claude-code` +- [ ] Apply changes to `skills/working-with-claude-code/scripts/update_docs.js` +- [ ] Apply changes to `skills/working-with-claude-code/SKILL.md` +- [ ] Test script runs successfully +- [ ] Verify all 43 files download +- [ ] Check no 404 errors +- [ ] Confirm references directory populated +- [ ] Test that documentation is readable +- [ ] Verify no breaking changes to API/output + +### episodic-memory Improvements + +- [ ] Document first-use sync requirement +- [ ] Test auto-sync on empty archive (if implemented) +- [ ] Verify MCP tools work after sync +- [ ] Test CLI commands with full paths +- [ ] Confirm search returns relevant results +- [ ] Check show command formatting +- [ ] Verify archive location is documented +- [ ] Test incremental sync (subsequent runs) + +--- + +## Appendix: Complete File Contents + +### A. Fixed update_docs.js + +See system reminder in current session for complete file. Key sections: + +- Lines 16-17: Domain constants +- Lines 20-83: DOC_PAGES array (43 pages) +- Lines 110-112: Simplified getClaudeCodeUrls function +- Lines 135-139: Updated console output + +### B. Updated SKILL.md Sections + +**Domain reference** (line 10): +```markdown +This skill provides complete, authoritative documentation for Claude Code directly from code.claude.com. +``` + +**Script description** (lines 135-139): +```markdown +The script: +1. Uses a curated list of 43 Claude Code documentation pages +2. Fetches each page from code.claude.com/docs/en/ +3. Downloads each page to `references/` +4. Reports success/failures +``` + +### C. episodic-memory Setup Commands + +**Installation**: +```bash +/plugin install episodic-memory@superpowers-marketplace +``` + +**Initial sync**: +```bash +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory sync +``` + +**Search usage**: +```bash +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory search "query" --limit 5 +``` + +**Show conversation**: +```bash +~/.claude/plugins/cache/superpowers-marketplace/episodic-memory/1.0.13/cli/episodic-memory show /path/to/file.jsonl +``` + +--- + +## Contact Information for Upstream + +**superpowers-developing-for-claude-code**: +- Repository: https://github.com/obra/superpowers-developing-for-claude-code +- Maintainer: Jesse Vincent (jesse@fsck.com) +- Current Version: 0.3.1 + +**episodic-memory**: +- Repository: https://github.com/obra/episodic-memory +- Maintainer: Jesse Vincent (jesse@fsck.com) +- Current Version: 1.0.13 +- Open Issues: 12 (as of Dec 8, 2025) + +--- + +## Session References + +**Session 1** (First encounter with update_docs.js issue): +- ID: 1ee8e950-09c9-4792-bb88-699c14da6408 +- Date: Dec 8, 2025, 6:27 PM +- Location: ~/.config/superpowers/conversation-archive/-Users-chris-dev-github-chrisvaillancourt-claude-code-skills/1ee8e950-09c9-4792-bb88-699c14da6408.jsonl + +**Session 2** (Current session): +- ID: 0c4ed174-0e5c-47d5-a7a1-2148a48b4ee0 +- Date: Dec 8, 2025, 6:49 PM - present +- Context: Repeated the same fix, discovered episodic-memory, documented everything + +--- + +## Next Steps + +1. **Review this document** for accuracy and completeness +2. **Fork repositories**: + - Fork obra/superpowers-developing-for-claude-code + - Fork obra/episodic-memory (if contributing) +3. **Create feature branches** +4. **Apply fixes** with proper testing +5. **Open PRs** with references to this document +6. **Engage with maintainer** for feedback + +--- + +**Document Status**: Complete and ready for upstream contribution process +**Last Updated**: December 9, 2025 +**Authors**: Session work with Claude Code (Sonnet 4.5) diff --git a/docs/working-with-claude-code-update-fix.md b/docs/working-with-claude-code-update-fix.md new file mode 100644 index 0000000..6ee90f3 --- /dev/null +++ b/docs/working-with-claude-code-update-fix.md @@ -0,0 +1,186 @@ +# Fix for working-with-claude-code Plugin Update Script + +## Problem + +The `update_docs.js` script in the `working-with-claude-code` skill fails with: +``` +❌ Error: HTTP 401: Unauthorized +📥 Fetching llms.txt... +``` + +## Root Cause + +1. Claude Code documentation moved from `docs.claude.com` to `code.claude.com` +2. The `llms.txt` endpoint at `docs.claude.com/llms.txt` now requires authentication (returns 401) +3. There is no equivalent public endpoint at the new domain + +## Solution + +The script needs to be updated to: +1. Use the new domain `code.claude.com` instead of `docs.claude.com` +2. Replace dynamic llms.txt fetching with a hardcoded list of documentation pages +3. Remove `migration-guide.md` which doesn't exist (404) + +## Implementation + +### Script Location +``` +~/.claude/plugins/cache/superpowers-marketplace/superpowers-developing-for-claude-code/0.3.1/skills/working-with-claude-code/scripts/update_docs.js +``` + +### Changes Required + +1. **Update constants** (lines 16-17): +```javascript +const DOCS_BASE_URL = 'https://code.claude.com/docs/en'; +const REFERENCES_DIR = path.join(__dirname, '..', 'references'); +``` + +2. **Replace with hardcoded list** (lines 20-86): +```javascript +const DOC_PAGES = [ + // Getting Started + 'overview.md', + 'quickstart.md', + 'common-workflows.md', + 'claude-code-on-the-web.md', + + // Build with Claude Code + 'sub-agents.md', + 'plugins.md', + 'skills.md', + 'output-styles.md', + 'hooks-guide.md', + 'headless.md', + 'github-actions.md', + + // CI/CD Integration + 'gitlab-ci-cd.md', + + // Advanced Integration + 'mcp.md', + + // Troubleshooting + 'troubleshooting.md', + + // Deployment + 'third-party-integrations.md', + 'amazon-bedrock.md', + 'google-vertex-ai.md', + 'network-config.md', + 'llm-gateway.md', + 'devcontainer.md', + 'sandboxing.md', + + // Administration + 'setup.md', + 'iam.md', + 'security.md', + 'data-usage.md', + 'monitoring-usage.md', + 'costs.md', + 'analytics.md', + 'plugin-marketplaces.md', + + // Configuration + 'settings.md', + 'vs-code.md', + 'jetbrains.md', + 'terminal-config.md', + 'model-config.md', + 'memory.md', + + // Reference + 'cli-reference.md', + 'interactive-mode.md', + 'slash-commands.md', + 'checkpointing.md', + 'hooks.md', + 'plugins-reference.md', + 'statusline.md', + + // Resources + 'legal-and-compliance.md' +]; +``` + +3. **Update getClaudeCodeUrls function** (line 110-112): +```javascript +async function getClaudeCodeUrls() { + return DOC_PAGES.map(page => `${DOCS_BASE_URL}/${page}`); +} +``` + +4. **Update console messages** (remove emojis for cleaner output): +```javascript +console.log('Claude Code Documentation Updater\n'); +console.log(`Found ${urls.length} Claude Code documentation pages\n`); +console.log('Downloading documentation...'); +console.log(`\nDocumentation update complete!`); +``` + +## Verification + +After applying the fix, run: +```bash +cd ~/.claude/plugins/cache/superpowers-marketplace/superpowers-developing-for-claude-code/0.3.1/skills/working-with-claude-code +node scripts/update_docs.js +``` + +Expected output: +``` +Claude Code Documentation Updater + +Found 43 Claude Code documentation pages + +Downloading documentation... + Fetching overview.md... + [... 42 more files ...] + +Documentation update complete! + 43 files downloaded successfully + +Documentation saved to: [path]/references +``` + +## Persistence Strategy + +⚠️ **WARNING**: This fix will be **lost** when: +- The plugin updates to a new version +- The plugin cache is cleared +- You reinstall the plugin + +### Recommended Approach + +**Option 1: Contribute upstream** (Best) +- Open an issue/PR at: https://github.com/obra/superpowers-developing-for-claude-code +- Benefits: Permanent fix, helps everyone + +**Option 2: Document in episodic-memory** +- This conversation is now indexed and searchable +- Search: `episodic-memory search "update docs script 401"` +- Will find this fix in future sessions + +**Option 3: Keep this documentation** +- Commit this file to your repo +- Reference it when the fix needs to be reapplied +- Consider adding to your BEADS workflow + +## History + +- **First occurrence**: Dec 8, 2025, 6:27 PM (Session: 1ee8e950-09c9-4792-bb88-699c14da6408) +- **Second occurrence**: Dec 8, 2025, 6:49 PM (Session: 0c4ed174-0e5c-47d5-a7a1-2148a48b4ee0) +- Both sessions: Identical problem, identical solution + +## Related Issues + +- Claude Code documentation moved from docs.claude.com → code.claude.com (Nov 2025) +- llms.txt endpoint now requires authentication +- See: https://code.claude.com/docs/en/overview for current documentation + +## Next Steps + +1. ✅ Document the fix (this file) +2. ⬜ Open issue at https://github.com/obra/superpowers-developing-for-claude-code +3. ⬜ Contribute PR with the fix +4. ⬜ Consider creating a post-install hook if needed frequently From c86c38d8811cdc54b4c9f9d22e710080f5e765bb Mon Sep 17 00:00:00 2001 From: Chris Vaillancourt Date: Fri, 12 Dec 2025 17:20:47 -0800 Subject: [PATCH 6/7] docs: remove redundant fix documentation The working-with-claude-code-update-fix.md file is completely redundant with upstream-improvements-context.md, which contains all the same information plus additional episodic-memory setup documentation. --- docs/working-with-claude-code-update-fix.md | 186 -------------------- 1 file changed, 186 deletions(-) delete mode 100644 docs/working-with-claude-code-update-fix.md diff --git a/docs/working-with-claude-code-update-fix.md b/docs/working-with-claude-code-update-fix.md deleted file mode 100644 index 6ee90f3..0000000 --- a/docs/working-with-claude-code-update-fix.md +++ /dev/null @@ -1,186 +0,0 @@ -# Fix for working-with-claude-code Plugin Update Script - -## Problem - -The `update_docs.js` script in the `working-with-claude-code` skill fails with: -``` -❌ Error: HTTP 401: Unauthorized -📥 Fetching llms.txt... -``` - -## Root Cause - -1. Claude Code documentation moved from `docs.claude.com` to `code.claude.com` -2. The `llms.txt` endpoint at `docs.claude.com/llms.txt` now requires authentication (returns 401) -3. There is no equivalent public endpoint at the new domain - -## Solution - -The script needs to be updated to: -1. Use the new domain `code.claude.com` instead of `docs.claude.com` -2. Replace dynamic llms.txt fetching with a hardcoded list of documentation pages -3. Remove `migration-guide.md` which doesn't exist (404) - -## Implementation - -### Script Location -``` -~/.claude/plugins/cache/superpowers-marketplace/superpowers-developing-for-claude-code/0.3.1/skills/working-with-claude-code/scripts/update_docs.js -``` - -### Changes Required - -1. **Update constants** (lines 16-17): -```javascript -const DOCS_BASE_URL = 'https://code.claude.com/docs/en'; -const REFERENCES_DIR = path.join(__dirname, '..', 'references'); -``` - -2. **Replace with hardcoded list** (lines 20-86): -```javascript -const DOC_PAGES = [ - // Getting Started - 'overview.md', - 'quickstart.md', - 'common-workflows.md', - 'claude-code-on-the-web.md', - - // Build with Claude Code - 'sub-agents.md', - 'plugins.md', - 'skills.md', - 'output-styles.md', - 'hooks-guide.md', - 'headless.md', - 'github-actions.md', - - // CI/CD Integration - 'gitlab-ci-cd.md', - - // Advanced Integration - 'mcp.md', - - // Troubleshooting - 'troubleshooting.md', - - // Deployment - 'third-party-integrations.md', - 'amazon-bedrock.md', - 'google-vertex-ai.md', - 'network-config.md', - 'llm-gateway.md', - 'devcontainer.md', - 'sandboxing.md', - - // Administration - 'setup.md', - 'iam.md', - 'security.md', - 'data-usage.md', - 'monitoring-usage.md', - 'costs.md', - 'analytics.md', - 'plugin-marketplaces.md', - - // Configuration - 'settings.md', - 'vs-code.md', - 'jetbrains.md', - 'terminal-config.md', - 'model-config.md', - 'memory.md', - - // Reference - 'cli-reference.md', - 'interactive-mode.md', - 'slash-commands.md', - 'checkpointing.md', - 'hooks.md', - 'plugins-reference.md', - 'statusline.md', - - // Resources - 'legal-and-compliance.md' -]; -``` - -3. **Update getClaudeCodeUrls function** (line 110-112): -```javascript -async function getClaudeCodeUrls() { - return DOC_PAGES.map(page => `${DOCS_BASE_URL}/${page}`); -} -``` - -4. **Update console messages** (remove emojis for cleaner output): -```javascript -console.log('Claude Code Documentation Updater\n'); -console.log(`Found ${urls.length} Claude Code documentation pages\n`); -console.log('Downloading documentation...'); -console.log(`\nDocumentation update complete!`); -``` - -## Verification - -After applying the fix, run: -```bash -cd ~/.claude/plugins/cache/superpowers-marketplace/superpowers-developing-for-claude-code/0.3.1/skills/working-with-claude-code -node scripts/update_docs.js -``` - -Expected output: -``` -Claude Code Documentation Updater - -Found 43 Claude Code documentation pages - -Downloading documentation... - Fetching overview.md... - [... 42 more files ...] - -Documentation update complete! - 43 files downloaded successfully - -Documentation saved to: [path]/references -``` - -## Persistence Strategy - -⚠️ **WARNING**: This fix will be **lost** when: -- The plugin updates to a new version -- The plugin cache is cleared -- You reinstall the plugin - -### Recommended Approach - -**Option 1: Contribute upstream** (Best) -- Open an issue/PR at: https://github.com/obra/superpowers-developing-for-claude-code -- Benefits: Permanent fix, helps everyone - -**Option 2: Document in episodic-memory** -- This conversation is now indexed and searchable -- Search: `episodic-memory search "update docs script 401"` -- Will find this fix in future sessions - -**Option 3: Keep this documentation** -- Commit this file to your repo -- Reference it when the fix needs to be reapplied -- Consider adding to your BEADS workflow - -## History - -- **First occurrence**: Dec 8, 2025, 6:27 PM (Session: 1ee8e950-09c9-4792-bb88-699c14da6408) -- **Second occurrence**: Dec 8, 2025, 6:49 PM (Session: 0c4ed174-0e5c-47d5-a7a1-2148a48b4ee0) -- Both sessions: Identical problem, identical solution - -## Related Issues - -- Claude Code documentation moved from docs.claude.com → code.claude.com (Nov 2025) -- llms.txt endpoint now requires authentication -- See: https://code.claude.com/docs/en/overview for current documentation - -## Next Steps - -1. ✅ Document the fix (this file) -2. ⬜ Open issue at https://github.com/obra/superpowers-developing-for-claude-code -3. ⬜ Contribute PR with the fix -4. ⬜ Consider creating a post-install hook if needed frequently From ed8e571fb6c34aa3c916a5ecc8f3e72c7ace09d2 Mon Sep 17 00:00:00 2001 From: Chris Vaillancourt Date: Mon, 19 Jan 2026 16:06:07 -0800 Subject: [PATCH 7/7] docs(references): refresh documentation and add new pages - Update 33 reference files with latest content from code.claude.com - Add chrome.md for Chrome extension documentation - Add discover-plugins.md for plugin discovery documentation - Update SKILL.md with new file references and quick reference entries --- skills/working-with-claude-code/SKILL.md | 3 + .../references/amazon-bedrock.md | 2 - .../references/chrome.md | 220 +++++ .../references/claude-code-on-the-web.md | 83 +- .../references/claude_code_docs_map.md | 772 +++++++++++------- .../references/cli-reference.md | 132 +-- .../references/common-workflows.md | 201 +++-- .../references/costs.md | 2 +- .../references/data-usage.md | 35 +- .../references/desktop.md | 54 +- .../references/discover-plugins.md | 378 +++++++++ .../references/gitlab-ci-cd.md | 10 +- .../references/headless.md | 238 +++--- .../references/hooks.md | 168 +++- .../references/iam.md | 121 ++- .../references/interactive-mode.md | 140 +++- .../references/mcp.md | 177 +++- .../references/memory.md | 36 +- .../references/monitoring-usage.md | 41 +- .../references/overview.md | 50 +- .../references/plugin-marketplaces.md | 534 +++++++----- .../references/plugins-reference.md | 426 +++++++++- .../references/plugins.md | 519 ++++++------ .../references/quickstart.md | 62 +- .../references/sandboxing.md | 2 +- .../references/security.md | 2 +- .../references/settings.md | 693 +++++++++++++--- .../references/setup.md | 255 +++--- .../references/skills.md | 725 ++++++++-------- .../references/slash-commands.md | 200 +++-- .../references/statusline.md | 52 +- .../references/sub-agents.md | 722 +++++++++------- .../references/terminal-config.md | 21 +- .../references/third-party-integrations.md | 294 ++++--- .../references/troubleshooting.md | 72 +- .../references/vs-code.md | 273 +++++-- 36 files changed, 5121 insertions(+), 2594 deletions(-) create mode 100644 skills/working-with-claude-code/references/chrome.md create mode 100644 skills/working-with-claude-code/references/discover-plugins.md diff --git a/skills/working-with-claude-code/SKILL.md b/skills/working-with-claude-code/SKILL.md index 878367b..ae28241 100644 --- a/skills/working-with-claude-code/SKILL.md +++ b/skills/working-with-claude-code/SKILL.md @@ -36,6 +36,7 @@ Use this skill when: | Configuration options | `settings.md` | | Web-based Claude Code | `claude-code-on-the-web.md` | | Desktop app | `desktop.md` | +| Chrome extension | `chrome.md` | | Sandboxing/security | `sandboxing.md` | | Slack integration | `slack.md` | @@ -51,9 +52,11 @@ references/ ├── common-workflows.md # Common usage patterns ├── claude-code-on-the-web.md # Web-based Claude Code ├── desktop.md # Desktop application +├── chrome.md # Chrome extension ├── plugins.md # Plugin development ├── plugins-reference.md # Plugin API reference ├── plugin-marketplaces.md # Plugin marketplaces +├── discover-plugins.md # Plugin discovery ├── skills.md # Skill creation ├── mcp.md # MCP server integration ├── hooks.md # Hooks overview diff --git a/skills/working-with-claude-code/references/amazon-bedrock.md b/skills/working-with-claude-code/references/amazon-bedrock.md index 1aeaf90..5b27790 100644 --- a/skills/working-with-claude-code/references/amazon-bedrock.md +++ b/skills/working-with-claude-code/references/amazon-bedrock.md @@ -110,8 +110,6 @@ export AWS_REGION=us-east-1 # or your preferred region export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2 ``` -**For VS Code Extension users**: Configure environment variables in the VS Code extension settings instead of exporting them in your shell. See [Using Third-Party Providers in VS Code](/en/vs-code#using-third-party-providers-vertex-and-bedrock) for detailed instructions. All environment variables shown in this guide should work when configured through the VS Code extension settings. - 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. diff --git a/skills/working-with-claude-code/references/chrome.md b/skills/working-with-claude-code/references/chrome.md new file mode 100644 index 0000000..db5bbd6 --- /dev/null +++ b/skills/working-with-claude-code/references/chrome.md @@ -0,0 +1,220 @@ +# 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` slash 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 + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/claude-code-on-the-web.md b/skills/working-with-claude-code/references/claude-code-on-the-web.md index e737412..2fd13a4 100644 --- a/skills/working-with-claude-code/references/claude-code-on-the-web.md +++ b/skills/working-with-claude-code/references/claude-code-on-the-web.md @@ -16,12 +16,9 @@ Claude Code on the web lets developers kick off Claude Code from the Claude app. * **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. This is perfect for: +Claude Code is also available on the Claude iOS app for kicking off tasks on the go and monitoring work in progress. -* **On the go**: Kick off tasks while commuting or away from laptop -* **Monitoring**: Watch the trajectory and steer the agent's work - -Developers can also move Claude Code sessions from the Claude app to their terminal to continue tasks locally. +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? @@ -54,14 +51,75 @@ When you start a task on Claude Code on the web: ## 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 -After starting a task on the web: +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 -1. Click the "Open in CLI" button -2. Paste and run the command in your terminal in a checkout of the repo -3. Any existing local changes will be stashed, and the remote session will be loaded -4. Continue working locally +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 @@ -127,6 +185,8 @@ When you start a session in Claude Code on the web, here's what happens under th **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: @@ -256,6 +316,7 @@ When using "Limited" network access, the following domains are allowed by defaul * ghcr.io * mcr.microsoft.com * \*.data.mcr.microsoft.com +* public.ecr.aws #### Cloud Platforms @@ -276,6 +337,8 @@ When using "Limited" network access, the following domains are allowed by defaul * dot.net * visualstudio.com * dev.azure.com +* \*.amazonaws.com +* \*.api.aws * oracle.com * [www.oracle.com](http://www.oracle.com) * java.com diff --git a/skills/working-with-claude-code/references/claude_code_docs_map.md b/skills/working-with-claude-code/references/claude_code_docs_map.md index 9a4e349..e45b27c 100644 --- a/skills/working-with-claude-code/references/claude_code_docs_map.md +++ b/skills/working-with-claude-code/references/claude_code_docs_map.md @@ -5,7 +5,7 @@ This is a comprehensive map of all Claude Code documentation pages with their headings, designed for easy navigation by LLMs. > **Note:** This file is auto-generated by GitHub Actions. Do not edit manually. -> Last updated: 2025-11-06 00:10:13 UTC +> Last updated: 2026-01-14 04:18:45 UTC ## Document Structure @@ -55,13 +55,18 @@ This map uses a hierarchical structure: * How to use Plan Mode * Example: Planning a complex refactor * Configure Plan Mode as default +* Let Claude interview you * Work with tests * Create pull requests * Handle documentation * Work with images * Reference files and directories -* Use extended thinking +* Use extended thinking (thinking mode) + * Per-request thinking with `ultrathink` + * How extended thinking token budgets work * Resume previous conversations + * Name your sessions + * Use the session picker * Run parallel Claude Code sessions with Git worktrees * Use Claude as a unix-style utility * Add Claude to your verification process @@ -75,6 +80,12 @@ This map uses a hierarchical structure: * Example questions * Next steps +### [changelog](https://code.claude.com/docs/en/changelog.md) + +* (No headings found) + +## Outside of the terminal + ### [claude-code-on-the-web](https://code.claude.com/docs/en/claude-code-on-the-web.md) * What is Claude Code on the web? @@ -82,11 +93,15 @@ This map uses a hierarchical structure: * Getting started * How it works * Moving tasks between web and terminal + * From terminal to web + * Tips for background tasks * From web to terminal + * Requirements for teleporting * Cloud environment * Default image * Checking available tools * Language-specific setups + * Databases * Environment configuration * Dependency management * Local vs remote execution @@ -120,155 +135,88 @@ This map uses a hierarchical structure: * Best practices * Related resources -## Build with Claude Code - -### [sub-agents](https://code.claude.com/docs/en/sub-agents.md) - -* What are subagents? -* Key benefits -* Quick start -* Subagent configuration - * File locations - * Plugin agents - * CLI-based configuration - * File format - * Configuration fields - * Model selection - * Available tools -* Managing subagents - * Using the /agents command (Recommended) - * Direct file management -* Using subagents effectively - * Automatic delegation - * Explicit invocation -* Built-in subagents - * Plan subagent -* Example subagents - * Code reviewer - * Debugger - * Data scientist -* Best practices -* Advanced usage - * Chaining subagents - * Dynamic subagent selection - * Resumable subagents -* Performance considerations -* Related documentation - -### [plugins](https://code.claude.com/docs/en/plugins.md) +### [desktop](https://code.claude.com/docs/en/desktop.md) -* Quickstart - * Prerequisites - * Create your first plugin -* Hello Command - * Plugin structure overview - * Install and manage plugins - * Prerequisites - * Add marketplaces - * Install plugins - * Via interactive menu (recommended for discovery) - * Via direct commands (for quick installation) - * Verify installation - * Set up team plugin workflows - * Develop more complex plugins - * Add Skills to your plugin - * Organize complex plugins - * Test your plugins locally - * Debug plugin issues - * Share your plugins - * Next steps - * For plugin users - * For plugin developers - * For team leads and administrators - * See also +* Claude Code on desktop (Preview) +* Installation +* Features +* Using Git worktrees + * Copying files ignored with `.gitignore` + * Launch Claude Code on the web +* Bundled Claude Code version +* Environment configuration + * Custom environment variables +* Enterprise configuration +* Related resources -### [skills](https://code.claude.com/docs/en/skills.md) +### [chrome](https://code.claude.com/docs/en/chrome.md) +* What the integration enables * Prerequisites -* What are Agent Skills? -* Create a Skill - * Personal Skills - * Project Skills - * Plugin Skills -* Write SKILL.md -* Add supporting files -* Restrict tool access with allowed-tools -* View available Skills -* Test a Skill -* Debug a Skill - * Make description specific - * Verify file path - * Check YAML syntax - * View errors -* Share Skills with your team - * Step 1: Add Skill to your project - * Step 2: Commit to git - * Step 3: Team members get Skills automatically -* Update a Skill -* Remove a Skill +* How the integration works +* Set up the integration +* Try it out +* Example workflows + * Test a local web application + * Debug with console logs + * Automate form filling + * Draft content in Google Docs + * Extract data from web pages + * Run multi-site workflows + * Record a demo GIF * Best practices - * Keep Skills focused - * Write clear descriptions - * Test with your team - * Document Skill versions * Troubleshooting - * Claude doesn't use my Skill - * Skill has errors - * Multiple Skills conflict -* Examples - * Simple Skill (single file) - * Skill with tool permissions - * Multi-file Skill -* Next steps - -### [output-styles](https://code.claude.com/docs/en/output-styles.md) - -* Built-in output styles -* How output styles work -* Change your output style -* Create a custom output style -* Comparisons to related features - * Output Styles vs. CLAUDE.md vs. --append-system-prompt - * Output Styles vs. [Agents](/en/sub-agents) - * Output Styles vs. [Custom Slash Commands](/en/slash-commands) + * Extension not detected + * Browser not responding + * First-time setup +* Enable by default +* See also -### [hooks-guide](https://code.claude.com/docs/en/hooks-guide.md) +### [vs-code](https://code.claude.com/docs/en/vs-code.md) -* Hook Events Overview -* Quickstart - * Prerequisites - * Step 1: Open hooks configuration - * Step 2: Add a matcher - * Step 3: Add the hook - * Step 4: Save your configuration - * Step 5: Verify your hook - * Step 6: Test your hook -* More Examples - * Code Formatting Hook - * Markdown Formatting Hook - * Custom Notification Hook - * File Protection Hook -* Learn more +* Prerequisites +* Install the extension +* Get started +* Customize your workflow + * Change the layout + * Switch to terminal mode +* VS Code commands and shortcuts +* Configure settings +* Use third-party providers +* VS Code extension vs. Claude Code CLI + * Run CLI in VS Code + * Switch between extension and CLI +* Security considerations +* Fix common issues + * Extension won't install + * Spark icon not visible + * Claude Code never responds + * Standalone CLI not connecting to IDE +* Uninstall the extension +* Next steps -### [headless](https://code.claude.com/docs/en/headless.md) +### [jetbrains](https://code.claude.com/docs/en/jetbrains.md) -* Overview -* Basic usage -* Configuration Options -* Multi-turn conversations -* Output Formats - * Text Output (Default) - * JSON Output - * Streaming JSON Output -* Input Formats - * Text Input (Default) - * Streaming JSON Input -* Agent Integration Examples - * SRE Incident Response Bot - * Automated Security Review - * Multi-turn Legal Assistant -* Best Practices -* Related Resources +* Supported IDEs +* Features +* Installation + * Marketplace Installation +* Usage + * From Your IDE + * From External Terminals +* Configuration + * Claude Code Settings + * Plugin Settings + * General Settings + * ESC Key Configuration +* Special Configurations + * Remote Development + * WSL Configuration +* Troubleshooting + * Plugin Not Working + * IDE Not Detected + * Command Not Found +* Security Considerations ### [github-actions](https://code.claude.com/docs/en/github-actions.md) @@ -303,7 +251,7 @@ This map uses a hierarchical structure: * Authentication errors * Advanced configuration * Action parameters - * Using claude\_args + * Pass CLI arguments * Alternative integration methods * Customizing Claude's behavior @@ -338,6 +286,197 @@ This map uses a hierarchical structure: * Common parameters and variables * Customizing Claude's behavior +### [slack](https://code.claude.com/docs/en/slack.md) + +* Use cases +* Prerequisites +* Setting up Claude Code in Slack +* How it works + * Automatic detection + * Context gathering + * Session flow +* User interface elements + * App Home + * Message actions + * Repository selection +* Access and permissions + * User-level access + * Workspace admin permissions +* What's accessible where +* Best practices + * Writing effective requests + * When to use Slack vs. web +* Troubleshooting + * Sessions not starting + * Repository not showing + * Wrong repository selected + * Authentication errors + * Session expiration +* Current limitations +* Related resources + +## Build with Claude Code + +### [sub-agents](https://code.claude.com/docs/en/sub-agents.md) + +* Built-in subagents +* Quickstart: create your first subagent +* Configure subagents + * Use the /agents command + * Choose the subagent scope + * Write subagent files + * Supported frontmatter fields + * Choose a model + * Control subagent capabilities + * Available tools + * Permission modes + * Conditional rules with hooks + * Disable specific subagents + * Define hooks for subagents + * Hooks in subagent frontmatter + * Project-level hooks for subagent events +* Work with subagents + * Understand automatic delegation + * Run subagents in foreground or background + * Common patterns + * Isolate high-volume operations + * Run parallel research + * Chain subagents + * Choose between subagents and main conversation + * Manage subagent context + * Resume subagents + * Auto-compaction +* Example subagents + * Code reviewer + * Debugger + * Data scientist + * Database query validator +* Next steps + +### [plugins](https://code.claude.com/docs/en/plugins.md) + +* When to use plugins vs standalone configuration +* Quickstart + * Prerequisites + * Create your first plugin +* Hello Command +* Hello Command + * Plugin structure overview + * Develop more complex plugins + * Add Skills to your plugin + * Add LSP servers to your plugin + * Organize complex plugins + * Test your plugins locally + * Debug plugin issues + * Share your plugins + * Convert existing configurations to plugins + * Migration steps + * What changes when migrating + * Next steps + * For plugin users + * For plugin developers + +### [discover-plugins](https://code.claude.com/docs/en/discover-plugins.md) + +* How marketplaces work +* Official Anthropic marketplace + * Code intelligence + * External integrations + * Development workflows + * Output styles +* Try it: add the demo marketplace +* Add marketplaces + * Add from GitHub + * Add from other Git hosts + * Add from local paths + * Add from remote URLs +* Install plugins +* Manage installed plugins +* Manage marketplaces + * Use the interactive interface + * Use CLI commands + * Configure auto-updates +* Configure team marketplaces +* Troubleshooting + * /plugin command not recognized + * Common issues +* Next steps + +### [skills](https://code.claude.com/docs/en/skills.md) + +* Create your first Skill +* How Skills work + * Where Skills live + * When to use Skills versus other options +* Configure Skills + * Write SKILL.md + * Available metadata fields + * Update or delete a Skill + * Add supporting files with progressive disclosure + * Example: multi-file Skill structure + * Restrict tool access with allowed-tools + * Run Skills in a forked context + * Define hooks for Skills + * Control Skill visibility + * When to use each setting + * Example: model-only Skill + * Skills and subagents + * Give a subagent access to Skills + * Run a Skill in a subagent context + * Distribute Skills +* Examples + * Simple Skill (single file) + * Use multiple files +* Troubleshooting + * View and test Skills + * Skill not triggering + * Skill doesn't load + * Skill has errors + * Multiple Skills conflict + * Plugin Skills not appearing +* Next steps + +### [output-styles](https://code.claude.com/docs/en/output-styles.md) + +* Built-in output styles +* How output styles work +* Change your output style +* Create a custom output style + * Frontmatter +* Comparisons to related features + * Output Styles vs. CLAUDE.md vs. --append-system-prompt + * Output Styles vs. [Agents](/en/sub-agents) + * Output Styles vs. [Custom Slash Commands](/en/slash-commands) + +### [hooks-guide](https://code.claude.com/docs/en/hooks-guide.md) + +* Hook Events Overview +* Quickstart + * Prerequisites + * Step 1: Open hooks configuration + * Step 2: Add a matcher + * Step 3: Add the hook + * Step 4: Save your configuration + * Step 5: Verify your hook + * Step 6: Test your hook +* More Examples + * Code Formatting Hook + * Markdown Formatting Hook + * Custom Notification Hook + * File Protection Hook +* Learn more + +### [headless](https://code.claude.com/docs/en/headless.md) + +* Basic usage +* Examples + * Get structured output + * Auto-approve tools + * Create a commit + * Customize the system prompt + * Continue conversations +* Next steps + ### [mcp](https://code.claude.com/docs/en/mcp.md) * What you can do with MCP @@ -347,6 +486,7 @@ This map uses a hierarchical structure: * Option 2: Add a remote SSE server * Option 3: Add a local stdio server * Managing your servers + * Dynamic tool updates * Plugin-provided MCP servers * MCP installation scopes * Local scope @@ -368,24 +508,16 @@ This map uses a hierarchical structure: * Reference MCP resources * Use MCP prompts as slash commands * Execute MCP prompts -* Enterprise MCP configuration - * Setting up enterprise MCP configuration - * Restricting MCP servers with allowlists and denylists - -### [migration-guide](https://code.claude.com/docs/en/migration-guide.md) - -* Overview -* What's Changed -* Migration Steps - * For TypeScript/JavaScript Projects - * For Python Projects -* Breaking changes - * Python: ClaudeCodeOptions renamed to ClaudeAgentOptions - * System prompt no longer default - * Settings Sources No Longer Loaded by Default -* Why the Rename? -* Getting Help -* Next Steps +* Managed MCP configuration + * Option 1: Exclusive control with managed-mcp.json + * Option 2: Policy-based control with allowlists and denylists + * Restriction options + * Example configuration + * How command-based restrictions work + * How URL-based restrictions work + * Allowlist behavior (`allowedMcpServers`) + * Denylist behavior (`deniedMcpServers`) + * Important notes ### [troubleshooting](https://code.claude.com/docs/en/troubleshooting.md) @@ -393,9 +525,13 @@ This map uses a hierarchical structure: * Windows installation issues: errors in WSL * Linux and Mac installation issues: permission or command not found errors * Recommended solution: Native Claude Code installation + * Windows: "Claude Code on Windows requires git-bash" + * Windows: "installMethod is native, but claude command not found" * Permissions and authentication * Repeated permission prompts * Authentication issues +* Configuration file locations + * Resetting configuration * Performance and stability * High CPU or memory usage * Command hangs or freezes @@ -405,7 +541,7 @@ This map uses a hierarchical structure: * JetBrains IDE not detected on WSL2 * WSL2 networking modes * Reporting Windows IDE integration issues (both native and WSL) - * ESC key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals + * Escape key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals * Markdown formatting issues * Missing language tags in code blocks * Inconsistent spacing and formatting @@ -416,26 +552,17 @@ This map uses a hierarchical structure: ### [third-party-integrations](https://code.claude.com/docs/en/third-party-integrations.md) -* Provider comparison -* Cloud providers -* Corporate infrastructure -* Configuration overview - * Using Bedrock with corporate proxy - * Using Bedrock with LLM Gateway - * Using Vertex AI with corporate proxy - * Using Vertex AI with LLM Gateway - * Authentication configuration -* Choosing the right deployment configuration - * Direct provider access - * Corporate proxy - * LLM Gateway -* Debugging +* Compare deployment options +* Configure proxies and gateways + * Amazon Bedrock + * Microsoft Foundry + * Google Vertex AI * Best practices for organizations - * 1. Invest in documentation and memory - * 2. Simplify deployment - * 3. Start with guided usage - * 4. Configure security policies - * 5. Leverage MCP for integrations + * Invest in documentation and memory + * Simplify deployment + * Start with guided usage + * Configure security policies + * Leverage MCP for integrations * Next steps ### [amazon-bedrock](https://code.claude.com/docs/en/amazon-bedrock.md) @@ -469,6 +596,17 @@ This map uses a hierarchical structure: * Troubleshooting * Additional resources +### [microsoft-foundry](https://code.claude.com/docs/en/microsoft-foundry.md) + +* Prerequisites +* Setup + * 1. Provision Microsoft Foundry resource + * 2. Configure Azure credentials + * 3. Configure Claude Code +* Azure RBAC configuration +* Troubleshooting +* Additional resources + ### [network-config](https://code.claude.com/docs/en/network-config.md) * Proxy configuration @@ -481,6 +619,9 @@ This map uses a hierarchical structure: ### [llm-gateway](https://code.claude.com/docs/en/llm-gateway.md) +* Gateway requirements +* Configuration + * Model selection * LiteLLM configuration * Prerequisites * Basic LiteLLM setup @@ -492,7 +633,6 @@ This map uses a hierarchical structure: * Claude API through LiteLLM * Amazon Bedrock through LiteLLM * Google Vertex AI through LiteLLM - * Model selection * Additional resources ### [devcontainer](https://code.claude.com/docs/en/devcontainer.md) @@ -518,6 +658,7 @@ This map uses a hierarchical structure: * OS-level enforcement * Getting started * Enable sandboxing + * Sandbox modes * Configure sandboxing * Security benefits * Protection against prompt injection @@ -538,20 +679,31 @@ This map uses a hierarchical structure: * System requirements * Additional dependencies -* Standard installation +* Installation + * Authentication + * For individuals + * For teams and organizations + * Install a specific version + * Binary integrity and code signing +* NPM installation (deprecated) * Windows setup -* Alternative installation methods - * Native installation options - * NPM installation -* Running on AWS or GCP * Update Claude Code * Auto updates + * Configure release channel + * Disable auto-updates * Update manually +* Uninstall Claude Code + * Native installation + * Homebrew installation + * WinGet installation + * NPM installation + * Clean up configuration files (optional) ### [iam](https://code.claude.com/docs/en/iam.md) * Authentication methods - * Claude API authentication + * Claude for Teams or Enterprise (recommended) + * Claude Console authentication * Cloud provider authentication * Access control and permissions * Permission system @@ -560,7 +712,7 @@ This map uses a hierarchical structure: * Working directories * Tool-specific permission rules * Additional permission control with hooks - * Enterprise managed policy settings + * Managed settings * Settings precedence * Credential management @@ -592,53 +744,54 @@ This map uses a hierarchical structure: * Feedback using the `/bug` command * Session quality surveys * Data retention -* Data flow and dependencies - * Cloud execution +* Data access +* Local Claude Code: Data flow and dependencies + * Cloud execution: Data flow and dependencies * Telemetry services * Default behaviors by API provider ### [monitoring-usage](https://code.claude.com/docs/en/monitoring-usage.md) -* Quick Start -* Administrator Configuration -* Configuration Details - * Common Configuration Variables - * Metrics Cardinality Control - * Dynamic Headers - * Settings Configuration - * Script Requirements - * Important Limitations - * Multi-Team Organization Support - * Example Configurations -* Available Metrics and Events - * Standard Attributes +* Quick start +* Administrator configuration +* Configuration details + * Common configuration variables + * Metrics cardinality control + * Dynamic headers + * Settings configuration + * Script requirements + * Refresh behavior + * Multi-team organization support + * Example configurations +* Available metrics and events + * Standard attributes * Metrics - * Metric Details - * Session Counter - * Lines of Code Counter - * Pull Request Counter - * Commit Counter - * Cost Counter - * Token Counter - * Code Edit Tool Decision Counter - * Active Time Counter + * Metric details + * Session counter + * Lines of code counter + * Pull request counter + * Commit counter + * Cost counter + * Token counter + * Code edit tool decision counter + * Active time counter * Events - * User Prompt Event - * Tool Result Event - * API Request Event - * API Error Event - * Tool Decision Event -* Interpreting Metrics and Events Data - * Usage Monitoring - * Cost Monitoring - * Alerting and Segmentation - * Event Analysis -* Backend Considerations - * For Metrics: - * For Events/Logs: -* Service Information -* ROI Measurement Resources -* Security/Privacy Considerations + * User prompt event + * Tool result event + * API request event + * API error event + * Tool decision event +* Interpreting metrics and events data + * Usage monitoring + * Cost monitoring + * Alerting and segmentation + * Event analysis +* Backend considerations + * For metrics + * For events/logs +* Service information +* ROI measurement resources +* Security/privacy considerations * Monitoring Claude Code on Amazon Bedrock ### [costs](https://code.claude.com/docs/en/costs.md) @@ -673,114 +826,76 @@ This map uses a hierarchical structure: ### [plugin-marketplaces](https://code.claude.com/docs/en/plugin-marketplaces.md) * Overview - * Prerequisites -* Add and use marketplaces - * Add GitHub marketplaces - * Add Git repositories - * Add local marketplaces for development - * Install plugins from marketplaces - * Verify marketplace installation -* Configure team marketplaces -* Create your own marketplace - * Prerequisites for marketplace creation - * Create the marketplace file - * Marketplace schema - * Required fields - * Optional metadata - * Plugin entries - * Optional plugin fields - * Plugin sources - * Relative paths - * GitHub repositories - * Git repositories - * Advanced plugin entries +* Walkthrough: create a local marketplace +* Create the marketplace file +* Marketplace schema + * Required fields + * Owner fields + * Optional metadata +* Plugin entries + * Required fields + * Optional plugin fields +* Plugin sources + * Relative paths + * GitHub repositories + * Git repositories + * Advanced plugin entries * Host and distribute marketplaces * Host on GitHub (recommended) * Host on other git services - * Use local marketplaces for development -* Manage marketplace operations - * List known marketplaces - * Update marketplace metadata - * Remove a marketplace -* Troubleshooting marketplaces - * Common marketplace issues - * Marketplace not loading - * Plugin installation failures - * Validation and testing -* Next steps - * For marketplace users - * For marketplace creators - * For organizations + * Private repositories + * Test locally before distribution + * Require marketplaces for your team + * Managed marketplace restrictions + * Common configurations + * How restrictions work +* Validation and testing +* Troubleshooting + * Marketplace not loading + * Marketplace validation errors + * Plugin installation failures + * Private repository authentication fails + * Plugins with relative paths fail in URL-based marketplaces + * Files not found after installation * See also ## Configuration ### [settings](https://code.claude.com/docs/en/settings.md) +* Configuration scopes + * Available scopes + * When to use each scope + * How scopes interact + * What uses scopes * Settings files * Available settings * Permission settings * Sandbox settings + * Attribution settings + * File suggestion settings + * Hook configuration * Settings precedence * Key points about the configuration system - * System prompt availability + * System prompt * Excluding sensitive files * Subagent configuration * Plugin configuration * Plugin settings * `enabledPlugins` * `extraKnownMarketplaces` + * `strictKnownMarketplaces` * Managing plugins * Environment variables * Tools available to Claude + * Bash tool behavior * Extending tools with hooks * See also -### [vs-code](https://code.claude.com/docs/en/vs-code.md) - -* VS Code Extension (Beta) - * Features - * Requirements - * Installation - * How It Works - * Using Third-Party Providers (Vertex and Bedrock) - * Environment Variables - * Not Yet Implemented -* Security Considerations -* Legacy CLI Integration -* Troubleshooting - * Extension Not Installing - * Legacy Integration Not Working - -### [jetbrains](https://code.claude.com/docs/en/jetbrains.md) - -* Supported IDEs -* Features -* Installation - * Marketplace Installation -* Usage - * From Your IDE - * From External Terminals -* Configuration - * Claude Code Settings - * Plugin Settings - * General Settings - * ESC Key Configuration -* Special Configurations - * Remote Development - * WSL Configuration -* Troubleshooting - * Plugin Not Working - * IDE Not Detected - * Command Not Found -* Security Considerations - ### [terminal-config](https://code.claude.com/docs/en/terminal-config.md) * Themes and appearance * Line breaks - * Set up Shift+Enter (VS Code or iTerm2): - * Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app): * Notification setup * iTerm 2 system notifications * Custom notification hooks @@ -805,9 +920,15 @@ This map uses a hierarchical structure: * Determine memory type * CLAUDE.md imports * How Claude looks up memories -* Quickly add memories with the `#` shortcut * Directly edit memories with `/memory` * Set up project memory +* Modular rules with `.claude/rules/` + * Basic structure + * Path-specific rules + * Glob patterns + * Subdirectories + * Symlinks + * User-level rules * Organization-level memory management * Memory best practices @@ -822,6 +943,7 @@ This map uses a hierarchical structure: * Python Example * Node.js Example * Helper Function Approach + * Context Window Usage * Tips * Troubleshooting @@ -839,12 +961,15 @@ This map uses a hierarchical structure: * Keyboard shortcuts * General controls + * Text editing + * Theme and display * Multiline input * Quick commands * Vim editor mode * Mode switching * Navigation (NORMAL mode) * Editing (NORMAL mode) + * Text objects (NORMAL mode) * Command history * Reverse search with Ctrl+R * Background bash commands @@ -870,6 +995,7 @@ This map uses a hierarchical structure: * File references * Thinking mode * Frontmatter + * Define hooks for commands * Plugin commands * How plugin commands work * Plugin command structure @@ -882,11 +1008,12 @@ This map uses a hierarchical structure: * Naming conventions * Managing MCP connections * MCP permissions and wildcards -* `SlashCommand` tool - * `SlashCommand` tool supported commands - * Disable `SlashCommand` tool - * Disable specific commands only - * `SlashCommand` permission rules +* `Skill` tool + * What the `Skill` tool can invoke + * Encourage Claude to use specific commands + * Disable the `Skill` tool + * Disable specific commands or Skills + * `Skill` permission rules * Character budget limit * Skills vs slash commands * Use slash commands for @@ -914,6 +1041,7 @@ This map uses a hierarchical structure: * Structure * Project-Specific Hook Scripts * Plugin hooks + * Hooks in Skills, Agents, and Slash Commands * Prompt-Based Hooks * How prompt-based hooks work * Configuration @@ -937,7 +1065,10 @@ This map uses a hierarchical structure: * SessionEnd * Hook Input * PreToolUse Input - * PermissionRequest + * Bash tool + * Write tool + * Edit tool + * Read tool * PostToolUse Input * Notification Input * UserPromptSubmit Input @@ -982,6 +1113,8 @@ This map uses a hierarchical structure: * Skills * Hooks * MCP servers + * LSP servers +* Plugin installation scopes * Plugin manifest schema * Complete schema * Required fields @@ -989,14 +1122,29 @@ This map uses a hierarchical structure: * Component path fields * Path behavior rules * Environment variables +* Plugin caching and file resolution + * How plugin caching works + * Path traversal limitations + * Working with external dependencies * Plugin directory structure * Standard plugin layout * File locations reference +* CLI commands reference + * plugin install + * plugin uninstall + * plugin enable + * plugin disable + * plugin update * Debugging and development tools * Debugging commands * Common issues + * Example error messages + * Hook troubleshooting + * MCP server troubleshooting + * Directory structure mistakes * Distribution and versioning reference * Version management +* See also ## Resources diff --git a/skills/working-with-claude-code/references/cli-reference.md b/skills/working-with-claude-code/references/cli-reference.md index cca72c2..1ba1abe 100644 --- a/skills/working-with-claude-code/references/cli-reference.md +++ b/skills/working-with-claude-code/references/cli-reference.md @@ -4,58 +4,67 @@ ## 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 | `claude -c` | -| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` | -| `claude -r "" "query"` | Resume session by ID | `claude -r "abc123" "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). | +| 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"}}'` | -| `--allowedTools` | A list of tools that should be allowed without prompting the user for permission, in addition to [settings.json files](/en/settings) | `"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"` | -| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` | -| `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` | -| `--dangerously-skip-permissions` | Skip 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"` | -| `--disallowedTools` | A list of tools that should be disallowed without prompting the user for permission, in addition to [settings.json files](/en/settings) | `"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` | -| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` | -| `--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"` | -| `--max-turns` | Limit the number of agentic turns in non-interactive mode | `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` | -| `--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/iam#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"` | -| `--resume`, `-r` | Resume a specific session by ID, or by choosing in interactive mode | `claude --resume abc123 "query"` | -| `--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"` | -| `--tools` | Specify the list of available tools from the built-in set (use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"`) | `claude -p --tools "Bash,Edit,Read" "query"` | -| `--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` | +| 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` | +| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` | +| `--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"` | +| `--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/iam#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 @@ -94,13 +103,14 @@ For more details on creating and using subagents, see the [subagents documentati ### System prompt flags -Claude Code provides three flags for customizing the system prompt, each serving a different purpose: +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 | +| 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:** @@ -119,20 +129,18 @@ Claude Code provides three flags for customizing the system prompt, each serving claude --append-system-prompt "Always use TypeScript and include JSDoc comments" ``` - - `--system-prompt` and `--system-prompt-file` are mutually exclusive. You cannot use both flags simultaneously. - +* **`--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" + ``` - - For most use cases, `--append-system-prompt` is recommended as it preserves 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. - +`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be used together with either replacement flag. -For detailed information about print mode (`-p`) including output formats, -streaming, verbose logging, and programmatic usage, see the -[SDK documentation](https://docs.claude.com/en/docs/agent-sdk). +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 * [Slash commands](/en/slash-commands) - Interactive session commands * [Quickstart guide](/en/quickstart) - Getting started with Claude Code diff --git a/skills/working-with-claude-code/references/common-workflows.md b/skills/working-with-claude-code/references/common-workflows.md index 2f3867e..86322d4 100644 --- a/skills/working-with-claude-code/references/common-workflows.md +++ b/skills/working-with-claude-code/references/common-workflows.md @@ -221,7 +221,7 @@ Suppose you want to use specialized AI subagents to handle specific tasks more e ## 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. +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 @@ -283,6 +283,38 @@ Claude analyzes the current implementation and create a comprehensive plan. Refi See [settings documentation](/en/settings#available-settings) for more configuration options. +## Let Claude interview you + +For large features, start with a minimal spec and let Claude interview you to fill in the details: + +``` +> Interview me about this feature before you start: user notification system +``` + +``` +> Help me think through the requirements for authentication by asking questions +``` + +``` +> Ask me clarifying questions to build out this spec: payment processing +``` + +Claude uses the [`AskUserQuestion`](/en/settings#tools-available-to-claude) tool to ask you multiple-choice questions for gathering requirements, clarifying ambiguity, and understanding your preferences before writing any code. This collaborative approach produces better specs than trying to anticipate every requirement upfront. + + + When you select "Type something" to provide a custom answer, press **Ctrl+G** to open your default text editor for longer responses. + + +This behavior is most active in Plan Mode. To encourage it in other modes, add guidance to your `CLAUDE.md` file: + +```markdown theme={null} +Always ask clarifying questions when there are multiple valid approaches to a task. +``` + + + If you're building applications with the Agent SDK and want to surface clarifying questions to your users programmatically, see [Handle approvals and user input](https://platform.claude.com/docs/en/agent-sdk/user-input#handle-clarifying-questions). + + *** ## Work with tests @@ -454,6 +486,7 @@ Suppose you need to work with images in your codebase, and you want Claude's hel * 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 *** @@ -499,110 +532,134 @@ Use @ to quickly include files or directories without waiting for Claude to read *** -## Use extended thinking +## 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`. -Suppose you're working on complex architectural decisions, challenging bugs, or planning multi-step implementations that require deep reasoning. +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. - [Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is disabled by default in Claude Code. You can enable it on-demand by using `Tab` to toggle Thinking on, or by using prompts like "think" or "think hard". You can also enable it permanently by setting the [`MAX_THINKING_TOKENS` environment variable](/en/settings#environment-variables) in your settings. + Phrases like "think", "think hard", "ultrathink", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens. - - - ``` - > I need to implement a new authentication system using OAuth2 for our API. Think deeply about the best approach for implementing this in our codebase. - ``` +### Configure thinking mode - Claude gathers relevant information from your codebase and - uses extended thinking, which is visible in the interface. - +Thinking is enabled by default, but you can adjust or disable it. - - ``` - > think about potential security vulnerabilities in this approach - ``` +| 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` | - ``` - > think hard about edge cases we should handle - ``` -
-
+To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text. - - Tips to get the most value out of extended thinking: +### How extended thinking token budgets work - [Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is most valuable for complex tasks such as: +Extended thinking uses a **token budget** that controls how much internal reasoning Claude can perform before responding. - * Planning complex architectural changes - * Debugging intricate issues - * Creating implementation plans for new features - * Understanding complex codebases - * Evaluating tradeoffs between different approaches +A larger thinking token budget provides: - Use `Tab` to toggle Thinking on and off during a session. +* 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 - The way you prompt for thinking results in varying levels of thinking depth: +Token budgets for thinking mode: - * "think" triggers basic extended thinking - * intensifying phrases such as "keep hard", "think more", "think a lot", or "think longer" triggers deeper thinking +* 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 - For more extended thinking prompting tips, see [Extended thinking tips](https://docs.claude.com/en/docs/build-with-claude/prompt-engineering/extended-thinking-tips). - +**Limit the thinking budget:** - - Claude displays its thinking process as italic gray text above the - response. - +* 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 -Suppose you've been working on a task with Claude Code and need to continue where you left off in a later session. +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 + +From inside an active session, use `/resume` to switch to a different conversation. -Claude Code provides two options for resuming previous conversations: +Sessions are stored per project directory. The `/resume` picker shows sessions from the same git repository, including worktrees. -* `--continue` to automatically continue the most recent conversation -* `--resume` to display a conversation picker +### Name your sessions + +Give sessions descriptive names to find them later. This is a best practice when working on multiple tasks or features. - - ```bash theme={null} - claude --continue + + Use `/rename` during a session to give it a memorable name: + + ``` + > /rename auth-refactor ``` - This immediately resumes your most recent conversation without any prompts. + 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 --continue --print "Continue with my task" + claude --resume auth-refactor ``` - Use `--print` with `--continue` to resume the most recent conversation in non-interactive mode, perfect for scripts or automation. - + Or from inside an active session: - - ```bash theme={null} - claude --resume ``` + > /resume auth-refactor + ``` + + - This displays an interactive conversation selector with a clean list view showing: +### Use the session picker - * Session summary (or initial prompt) - * Metadata: time elapsed, message count, and git branch +The `/resume` command (or `claude --resume` without arguments) opens an interactive session picker with these features: - Use arrow keys to navigate and press Enter to select a conversation. Press Esc to exit. - - +**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: - * Conversation history is stored locally on your machine - * Use `--continue` for quick access to your most recent conversation - * Use `--resume` when you need to select a specific past conversation - * When resuming, you'll see the entire conversation history before continuing + * **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: @@ -611,22 +668,6 @@ Claude Code provides two options for resuming previous conversations: 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 - - Examples: - - ```bash theme={null} - # Continue most recent conversation - claude --continue - - # Continue most recent conversation with a specific prompt - claude --continue --print "Show me our progress" - - # Show conversation picker - claude --resume - - # Continue most recent conversation in non-interactive mode - claude --continue --print "Run the tests again" - ``` *** diff --git a/skills/working-with-claude-code/references/costs.md b/skills/working-with-claude-code/references/costs.md index ed2dd03..de78a6a 100644 --- a/skills/working-with-claude-code/references/costs.md +++ b/skills/working-with-claude-code/references/costs.md @@ -62,7 +62,7 @@ The TPM per user decreases as team size grows because we expect fewer users to u * **Compact conversations:** - * Claude uses auto-compact by default when context exceeds 95% capacity + * Claude uses auto-compact by default when context reaches approximately 95% capacity. To trigger compaction earlier, set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](/en/settings#environment-variables) to a lower percentage (for example, `50`) * Toggle auto-compact: Run `/config` and navigate to "Auto-compact enabled" * Use `/compact` manually when context gets large * Add custom instructions: `/compact Focus on code samples and API usage` diff --git a/skills/working-with-claude-code/references/data-usage.md b/skills/working-with-claude-code/references/data-usage.md index 89f4e64..cdc7723 100644 --- a/skills/working-with-claude-code/references/data-usage.md +++ b/skills/working-with-claude-code/references/data-usage.md @@ -7,15 +7,7 @@ ### Data training policy **Consumer users (Free, Pro, and Max plans)**: -Starting August 28, 2025, we're giving 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). - -* If you're a current user, you can select your preference now and your selection will immediately go into effect. - This setting will only apply to new or resumed chats and coding sessions on Claude. Previous chats with no additional activity will not be used for model training. -* You have until October 8, 2025 to make your selection. - If you're a new user, you can pick your setting for model training during the signup process. - You can change your selection at any time in your Privacy Settings. +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)). @@ -51,27 +43,28 @@ Learn more about data retention practices in our [Privacy Center](https://privac 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 flow and dependencies +## 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. -Claude Code data flow diagram +## 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 - - - The above data flow diagram and description applies to Claude Code CLI running locally on your machine. For cloud-based sessions using Claude Code on the web, see the section below. - +### 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 storage**: Your repository is cloned to an isolated VM and automatically deleted after session completion -* **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 -* **Data retention**: Code and session data are subject to the retention and usage policies for your account type -* **Session data**: Prompts, code changes, and outputs follow the same data policies as local Claude Code usage +* **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). diff --git a/skills/working-with-claude-code/references/desktop.md b/skills/working-with-claude-code/references/desktop.md index 18aa492..81fdccd 100644 --- a/skills/working-with-claude-code/references/desktop.md +++ b/skills/working-with-claude-code/references/desktop.md @@ -8,22 +8,34 @@ The Claude desktop app provides a native interface for running multiple Claude Code sessions on your local machine and seamless integration with Claude Code on the web. -## Features +## Installation -Claude Code on desktop provides: +Download the Claude desktop app for your platform: -* **Parallel local sessions with `git` worktrees**: Run multiple Claude Code sessions simultaneously in the same repository, each with its own isolated `git` worktree -* **Include files listed in your `.gitignore` in your worktrees**: Automatically copy files in your `.gitignore`, like `.env`, to new worktrees using `.worktreeinclude` -* **Launch Claude Code on the web**: Kick off secure cloud sessions directly from the desktop app + + + Universal build for Intel and Apple Silicon + -## Installation + + For x64 processors + + -Download and install the Claude Desktop app from [claude.ai/download](https://claude.ai/download) +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 Windows arm64 architectures. + Local sessions are not available on Windows ARM64. +## Features + +Claude Code on desktop provides: + +* **Parallel local sessions with `git` worktrees**: Run multiple Claude Code sessions simultaneously in the same repository, each with its own isolated `git` worktree +* **Include files listed in your `.gitignore` in your worktrees**: Automatically copy files in your `.gitignore`, like `.env`, to new worktrees using `.worktreeinclude` +* **Launch Claude Code on the web**: Kick off secure cloud sessions directly from the desktop app + ## Using Git worktrees Claude Code on desktop enables running multiple Claude Code sessions in the same repository using Git worktrees. Each session gets its own isolated worktree, allowing Claude to work on different tasks without conflicts. The default location for worktrees is `~/.claude-worktrees` but this can be configured in your settings on the Claude desktop app. @@ -53,7 +65,7 @@ The file uses `.gitignore`-style patterns. When a worktree is created, files mat ### Launch Claude Code on the web -From the desktop app, you can kick off Claude Code sessions that run on Anthropic's secure cloud infrastructure. This is useful for: +From the desktop app, you can kick off Claude Code sessions that run on Anthropic's secure cloud infrastructure. To start a web session from desktop, select a remote environment when creating a new session. @@ -67,7 +79,29 @@ Claude Code on desktop includes a bundled, stable version of Claude Code to ensu The bundled Claude Code version in Desktop may differ from the latest CLI version. Desktop prioritizes stability while the CLI may have newer features.
-### Enterprise configuration +## Environment configuration + +For local environments, Claude Code on desktop automatically extracts your `$PATH` environment variable from your shell configuration. This allows local sessions to access development tools like `yarn`, `npm`, `node`, and other commands available in your terminal without additional setup. + +### Custom environment variables + +Select "Local" environment, then to the right, select the settings button. This will open a dialog where you can update local environment variables. This is useful for setting project-specific variables or API keys that your development workflows require. Environment variable values are masked in the UI for security reasons. + + + 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 + + # Multiline values - wrap in quotes + CERT="-----BEGIN CERT----- + MIIE... + -----END CERT-----" + ``` + + +## 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). diff --git a/skills/working-with-claude-code/references/discover-plugins.md b/skills/working-with-claude-code/references/discover-plugins.md new file mode 100644 index 0000000..b87c75d --- /dev/null +++ b/skills/working-with-claude-code/references/discover-plugins.md @@ -0,0 +1,378 @@ +# 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 custom commands, 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 help Claude understand your codebase more deeply. With these plugins installed, Claude can jump to definitions, find references, and see type errors immediately after edits. These plugins use the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP), 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` | +| 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. + + +### 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. + +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. See [Plugin Skills not appearing](/en/skills#plugin-skills-not-appearing-after-installation) for details. + +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). + +## Next steps + +* **Build your own plugins**: See [Plugins](/en/plugins) to create custom commands, 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 + + +--- + +> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt \ No newline at end of file diff --git a/skills/working-with-claude-code/references/gitlab-ci-cd.md b/skills/working-with-claude-code/references/gitlab-ci-cd.md index 4b87bf2..f5d2d22 100644 --- a/skills/working-with-claude-code/references/gitlab-ci-cd.md +++ b/skills/working-with-claude-code/references/gitlab-ci-cd.md @@ -77,7 +77,7 @@ claude: before_script: - apk update - apk add --no-cache git curl bash - - npm install -g @anthropic-ai/claude-code + - 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 @@ -255,7 +255,7 @@ claude: before_script: - apk update - apk add --no-cache git curl bash - - npm install -g @anthropic-ai/claude-code + - curl -fsSL https://claude.ai/install.sh | bash script: - /bin/gitlab-mcp-server || true - > @@ -289,7 +289,7 @@ claude-bedrock: before_script: - apk add --no-cache bash curl jq git python3 py3-pip - pip install --no-cache-dir awscli - - npm install -g @anthropic-ai/claude-code + - 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 @@ -339,8 +339,8 @@ claude-vertex: rules: - if: '$CI_PIPELINE_SOURCE == "web"' before_script: - - apt-get update && apt-get install -y git nodejs npm && apt-get clean - - npm install -g @anthropic-ai/claude-code + - 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 < Run Claude Code programmatically without interactive UI +> Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript. -## Overview +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 headless mode allows you to run Claude Code programmatically from command line scripts and automation tools without any interactive UI. + + The CLI was previously called "headless mode." The `-p` flag and all CLI options work the same way. + -## Basic usage - -The primary command-line interface to Claude Code is the `claude` command. Use the `--print` (or `-p`) flag to run in non-interactive mode and print the final result: +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 "Stage my changes and write a set of commits for them" \ - --allowedTools "Bash,Read" \ - --permission-mode acceptEdits +claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash" ``` -## Configuration Options - -Headless mode leverages all the CLI options available in Claude Code. Here are the key ones for automation and scripting: +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). -| Flag | Description | Example | -| :------------------------- | :----------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ | -| `--print`, `-p` | Run in non-interactive mode | `claude -p "query"` | -| `--output-format` | Specify output format (`text`, `json`, `stream-json`) | `claude -p --output-format json` | -| `--resume`, `-r` | Resume a conversation by session ID | `claude --resume abc123` | -| `--continue`, `-c` | Continue the most recent conversation | `claude --continue` | -| `--verbose` | Enable verbose logging | `claude --verbose` | -| `--append-system-prompt` | Append to system prompt (only with `--print`) | `claude --append-system-prompt "Custom instruction"` | -| `--allowedTools` | Space-separated list of allowed tools, or

string of comma-separated list of allowed tools | `claude --allowedTools mcp__slack mcp__filesystem`

`claude --allowedTools "Bash(npm install),mcp__filesystem"` | -| `--disallowedTools` | Space-separated list of denied tools, or

string of comma-separated list of denied tools | `claude --disallowedTools mcp__splunk mcp__github`

`claude --disallowedTools "Bash(git commit),mcp__github"` | -| `--mcp-config` | Load MCP servers from a JSON file | `claude --mcp-config servers.json` | -| `--permission-prompt-tool` | MCP tool for handling permission prompts (only with `--print`) | `claude --permission-prompt-tool mcp__auth__prompt` | +## Basic usage -For a complete list of CLI options and features, see the [CLI reference](/en/cli-reference) documentation. +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: -## Multi-turn conversations +* `--continue` for [continuing conversations](#continue-conversations) +* `--allowedTools` for [auto-approving tools](#auto-approve-tools) +* `--output-format` for [structured output](#get-structured-output) -For multi-turn conversations, you can resume conversations or continue from the most recent session: +This example asks Claude a question about your codebase and prints the response: ```bash theme={null} -# Continue the most recent conversation -claude --continue "Now refactor this for better performance" - -# Resume a specific conversation by session ID -claude --resume 550e8400-e29b-41d4-a716-446655440000 "Update the tests" - -# Resume in non-interactive mode -claude --resume 550e8400-e29b-41d4-a716-446655440000 "Fix all linting issues" --no-interactive +claude -p "What does the auth module do?" ``` -## Output Formats +## Examples -### Text Output (Default) +These examples highlight common CLI patterns. -```bash theme={null} -claude -p "Explain file src/components/Header.tsx" -# Output: This is a React component showing... -``` +### Get structured output -### JSON Output +Use `--output-format` to control how responses are returned: -Returns structured data including metadata: +* `text` (default): plain text output +* `json`: structured JSON with result, session ID, and metadata +* `stream-json`: newline-delimited JSON for real-time streaming -```bash theme={null} -claude -p "How does the data layer work?" --output-format json -``` +This example returns a project summary as JSON with session metadata, with the text result in the `result` field: -Response format: - -```json theme={null} -{ - "type": "result", - "subtype": "success", - "total_cost_usd": 0.003, - "is_error": false, - "duration_ms": 1234, - "duration_api_ms": 800, - "num_turns": 6, - "result": "The response text here...", - "session_id": "abc123" -} +```bash theme={null} +claude -p "Summarize this project" --output-format json ``` -### Streaming JSON Output +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. -Streams each message as it is received: +This example extracts function names and returns them as an array of strings: ```bash theme={null} -claude -p "Build an application" --output-format stream-json +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"]}' ``` -Each conversation begins with an initial `init` system message, followed by a list of user and assistant messages, followed by a final `result` system message with stats. Each message is emitted as a separate JSON object. + + 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' + ``` + -## Input Formats +### Auto-approve tools -### Text Input (Default) +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} -# Direct argument -claude -p "Explain this code" - -# From stdin -echo "Explain this code" | claude -p +claude -p "Run the test suite and fix any failures" \ + --allowedTools "Bash,Read,Edit" ``` -### Streaming JSON Input - -A stream of messages provided via `stdin` where each message represents a user turn. This allows multiple turns of a conversation without re-launching the `claude` binary and allows providing guidance to the model while it is processing a request. +### Create a commit -Each message is a JSON 'User message' object, following the same format as the output message schema. Messages are formatted using the [`jsonl`](https://jsonlines.org/) format where each line of input is a complete JSON object. Streaming JSON input requires `-p` and `--output-format stream-json`. +This example reviews staged changes and creates a commit with an appropriate message: ```bash theme={null} -echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Explain this code"}]}}' | claude -p --output-format=stream-json --input-format=stream-json --verbose +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:*)" ``` -## Agent Integration Examples +The `--allowedTools` flag uses [permission rule syntax](/en/settings#permission-rule-syntax). The `:*` suffix enables prefix matching, so `Bash(git diff:*)` allows any command starting with `git diff`. -### SRE Incident Response Bot + + [Slash commands](/en/slash-commands) like `/commit` are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead. + -```bash theme={null} -#!/bin/bash - -# Automated incident response agent -investigate_incident() { - local incident_description="$1" - local severity="${2:-medium}" - - claude -p "Incident: $incident_description (Severity: $severity)" \ - --append-system-prompt "You are an SRE expert. Diagnose the issue, assess impact, and provide immediate action items." \ - --output-format json \ - --allowedTools "Bash,Read,WebSearch,mcp__datadog" \ - --mcp-config monitoring-tools.json -} - -# Usage -investigate_incident "Payment API returning 500 errors" "high" -``` +### Customize the system prompt -### Automated Security Review +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} -# Security audit agent for pull requests -audit_pr() { - local pr_number="$1" - - gh pr diff "$pr_number" | claude -p \ - --append-system-prompt "You are a security engineer. Review this PR for vulnerabilities, insecure patterns, and compliance issues." \ - --output-format json \ - --allowedTools "Read,Grep,WebSearch" -} - -# Usage and save to file -audit_pr 123 > security-report.json +gh pr diff "$1" | claude -p \ + --append-system-prompt "You are a security engineer. Review for vulnerabilities." \ + --output-format json ``` -### Multi-turn Legal Assistant +See [system prompt flags](/en/cli-reference#system-prompt-flags) for more options including `--system-prompt` to fully replace the default prompt. -```bash theme={null} -# Legal document review with session persistence -session_id=$(claude -p "Start legal review session" --output-format json | jq -r '.session_id') - -# Review contract in multiple steps -claude -p --resume "$session_id" "Review contract.pdf for liability clauses" -claude -p --resume "$session_id" "Check compliance with GDPR requirements" -claude -p --resume "$session_id" "Generate executive summary of risks" -``` +### Continue conversations -## Best Practices +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: -* **Use JSON output format** for programmatic parsing of responses: - - ```bash theme={null} - # Parse JSON response with jq - result=$(claude -p "Generate code" --output-format json) - code=$(echo "$result" | jq -r '.result') - cost=$(echo "$result" | jq -r '.cost_usd') - ``` +```bash theme={null} +# First request +claude -p "Review this codebase for performance issues" -* **Handle errors gracefully** - check exit codes and stderr: +# Continue the most recent conversation +claude -p "Now focus on the database queries" --continue +claude -p "Generate a summary of all issues found" --continue +``` - ```bash theme={null} - if ! claude -p "$prompt" 2>error.log; then - echo "Error occurred:" >&2 - cat error.log >&2 - exit 1 - fi - ``` +If you're running multiple conversations, capture the session ID to resume a specific one: -* **Use session management** for maintaining context in multi-turn conversations +```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" +``` -* **Consider timeouts** for long-running operations: +## Next steps - ```bash theme={null} - timeout 300 claude -p "$complex_prompt" || echo "Timed out after 5 minutes" - ``` + + + Build your first agent with Python or TypeScript + -* **Respect rate limits** when making multiple requests by adding delays between calls + + Explore all CLI flags and options + -## Related Resources + + Use the Agent SDK in GitHub workflows + -* [CLI usage and controls](/en/cli-reference) - Complete CLI documentation -* [Common workflows](/en/common-workflows) - Step-by-step guides for common use cases + + Use the Agent SDK in GitLab pipelines + + --- diff --git a/skills/working-with-claude-code/references/hooks.md b/skills/working-with-claude-code/references/hooks.md index fa3a484..3b07586 100644 --- a/skills/working-with-claude-code/references/hooks.md +++ b/skills/working-with-claude-code/references/hooks.md @@ -13,7 +13,11 @@ Claude Code hooks are configured in your [settings files](/en/settings): * `~/.claude/settings.json` - User settings * `.claude/settings.json` - Project settings * `.claude/settings.local.json` - Local project settings (not committed) -* Enterprise managed policy settings +* Managed policy settings + + + Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](/en/settings#hook-configuration). + ### Structure @@ -142,6 +146,48 @@ ensuring they work regardless of Claude's current directory: See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks. +### Hooks in Skills, Agents, and Slash Commands + +In addition to settings files and plugins, hooks can be defined directly in [Skills](/en/skills), [subagents](/en/sub-agents), and [slash commands](/en/slash-commands) using frontmatter. These hooks are scoped to the component's lifecycle and only run when that component is active. + +**Supported events**: `PreToolUse`, `PostToolUse`, and `Stop` + +**Example in a Skill**: + +```yaml theme={null} +--- +name: secure-operations +description: Perform operations with security checks +hooks: + PreToolUse: + - matcher: "Bash" + hooks: + - type: command + command: "./scripts/security-check.sh" +--- +``` + +**Example in an agent**: + +```yaml theme={null} +--- +name: code-reviewer +description: Review code changes +hooks: + PostToolUse: + - matcher: "Edit|Write" + hooks: + - type: command + command: "./scripts/run-linter.sh" +--- +``` + +Component-scoped hooks follow the same configuration format as settings-based hooks but are automatically cleaned up when the component finishes executing. + +**Additional option for skills and slash commands:** + +* `once`: Set to `true` to run the hook only once per session. After the first successful execution, the hook is removed. Note: This option is currently only supported for skills and slash commands, not for agents. + ## 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 are currently only supported for `Stop` and `SubagentStop` hooks, where they enable intelligent, context-aware decisions. @@ -187,21 +233,15 @@ The LLM must respond with JSON containing: ```json theme={null} { - "decision": "approve" | "block", - "reason": "Explanation for the decision", - "continue": false, // Optional: stops Claude entirely - "stopReason": "Message shown to user", // Optional: custom stop message - "systemMessage": "Warning or context" // Optional: shown to user + "ok": true | false, + "reason": "Explanation for the decision" } ``` **Response fields:** -* `decision`: `"approve"` allows the action, `"block"` prevents it -* `reason`: Explanation shown to Claude when decision is `"block"` -* `continue`: (Optional) If `false`, stops Claude's execution entirely -* `stopReason`: (Optional) Message shown when `continue` is false -* `systemMessage`: (Optional) Additional message shown to the user +* `ok`: `true` allows the action, `false` prevents it +* `reason`: Required when `ok` is `false`. Explanation shown to Claude ### Supported hook events @@ -223,7 +263,7 @@ Prompt-based hooks work with any hook event, but are most useful for: "hooks": [ { "type": "prompt", - "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"decision\": \"approve\" or \"block\", \"reason\": \"your explanation\"}", + "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 } ] @@ -243,7 +283,7 @@ Prompt-based hooks work with any hook event, but are most useful for: "hooks": [ { "type": "prompt", - "prompt": "Evaluate if this subagent should stop. Input: $ARGUMENTS\n\nCheck if:\n- The subagent completed its assigned task\n- Any errors occurred that need fixing\n- Additional context gathering is needed\n\nReturn: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}" + "prompt": "Evaluate if this subagent should stop. Input: $ARGUMENTS\n\nCheck if:\n- The subagent completed its assigned task\n- Any errors occurred that need fixing\n- Additional context gathering is needed\n\nReturn: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"explanation\"} to continue." } ] } @@ -452,7 +492,7 @@ event-specific data: session_id: string transcript_path: string // Path to conversation JSON cwd: string // The current working directory when the hook is invoked - permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions" + permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", "dontAsk", or "bypassPermissions" // Event-specific fields hook_event_name: string @@ -462,7 +502,37 @@ event-specific data: ### PreToolUse Input -The exact schema for `tool_input` depends on the tool. +The exact schema for `tool_input` depends on the tool. Here are examples for commonly hooked tools. + +#### Bash tool + +The Bash tool is the most commonly hooked tool for command validation: + +```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": "PreToolUse", + "tool_name": "Bash", + "tool_input": { + "command": "psql -c 'SELECT * FROM users'", + "description": "Query the users table", + "timeout": 120000 + }, + "tool_use_id": "toolu_01ABC123..." +} +``` + +| Field | Type | Description | +| :------------------ | :------ | :-------------------------------------------- | +| `command` | string | The shell command to execute | +| `description` | string | Optional description of what the command does | +| `timeout` | number | Optional timeout in milliseconds | +| `run_in_background` | boolean | Whether to run the command in background | + +#### Write tool ```json theme={null} { @@ -480,6 +550,60 @@ The exact schema for `tool_input` depends on the tool. } ``` +| Field | Type | Description | +| :---------- | :----- | :--------------------------------- | +| `file_path` | string | Absolute path to the file to write | +| `content` | string | Content to write to the file | + +#### Edit 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": "PreToolUse", + "tool_name": "Edit", + "tool_input": { + "file_path": "/path/to/file.txt", + "old_string": "original text", + "new_string": "replacement text" + }, + "tool_use_id": "toolu_01ABC123..." +} +``` + +| Field | Type | Description | +| :------------ | :------ | :-------------------------------------------------- | +| `file_path` | string | Absolute path to the file to edit | +| `old_string` | string | Text to find and replace | +| `new_string` | string | Replacement text | +| `replace_all` | boolean | Whether to replace all occurrences (default: false) | + +#### Read 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": "PreToolUse", + "tool_name": "Read", + "tool_input": { + "file_path": "/path/to/file.txt" + }, + "tool_use_id": "toolu_01ABC123..." +} +``` + +| Field | Type | Description | +| :---------- | :----- | :----------------------------------------- | +| `file_path` | string | Absolute path to the file to read | +| `offset` | number | Optional line number to start reading from | +| `limit` | number | Optional number of lines to read | + ### PostToolUse Input The exact schema for `tool_input` and `tool_response` depends on the tool. @@ -681,18 +805,24 @@ to Claude. Additionally, hooks can modify tool inputs before execution using `updatedInput`: -* `updatedInput` allows you to modify the tool's input parameters before the tool executes. -* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls. +* `updatedInput` modifies the tool's input parameters before the tool executes +* Combine with `"permissionDecision": "allow"` to modify the input and auto-approve the tool call +* Combine with `"permissionDecision": "ask"` to modify the input and show it to the user for confirmation + +Hooks can also provide context to Claude using `additionalContext`: + +* `"hookSpecificOutput.additionalContext"` adds a string to Claude's context before the tool executes. ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PreToolUse", - "permissionDecision": "allow" + "permissionDecision": "allow", "permissionDecisionReason": "My reason here", "updatedInput": { "field_to_modify": "new value" - } + }, + "additionalContext": "Current environment: production. Proceed with caution." } } ``` diff --git a/skills/working-with-claude-code/references/iam.md b/skills/working-with-claude-code/references/iam.md index 9b35515..9aea66a 100644 --- a/skills/working-with-claude-code/references/iam.md +++ b/skills/working-with-claude-code/references/iam.md @@ -4,21 +4,37 @@ ## 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: +Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of these ways: -* Claude API via the Claude Console -* Amazon Bedrock -* Microsoft Foundry -* Google Vertex AI +* [Claude for Teams or Enterprise](/en/setup#for-teams-and-organizations) (recommended) +* [Claude Console with team billing](/en/setup#for-teams-and-organizations) +* [Amazon Bedrock](/en/amazon-bedrock) +* [Google Vertex AI](/en/google-vertex-ai) +* [Microsoft Foundry](/en/microsoft-foundry) -### Claude API authentication +### Claude for Teams or Enterprise (recommended) -**To set up Claude Code access for your team via Claude API:** +[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. + +**To set up Claude Code access:** + +1. Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or contact sales for [Claude for Enterprise](https://anthropic.com/contact-sales) +2. Invite team members from the admin dashboard +3. 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. + +**To set up Claude Code access for your team via Claude Console:** 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) + * [Set up SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso) 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 @@ -44,36 +60,44 @@ We support fine-grained permissions so that you're able to specify exactly what 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 | +| 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 | ### 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. +* **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. + * **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. +A rule that is just the tool name matches any use of that tool. For example, adding `Bash` to the allow list allows Claude Code to use the Bash tool without requiring user approval. Note that `Bash(*)` does **not** match all Bash commands. Use `Bash` without parentheses to match all uses. + + + For a quick reference on permission rule syntax including wildcards, see [Permission rule syntax](/en/settings#permission-rule-syntax) in the settings documentation. + #### 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) | +| 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`](/en/settings#permission-settings) rules | +| `bypassPermissions` | Skips all permission prompts (requires safe environment - see warning below) | #### Working directories @@ -91,9 +115,13 @@ Some tools support more fine-grained permission controls: **Bash** +Bash permission rules support both prefix matching with `:*` and wildcard matching with `*`: + * `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/` +* `Bash(npm *)` Matches any command starting with `npm ` (e.g., `npm install`, `npm run build`) +* `Bash(* install)` Matches any command ending with ` install` (e.g., `npm install`, `yarn install`) +* `Bash(git * main)` Matches commands like `git checkout main`, `git merge main` 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` @@ -102,8 +130,8 @@ Some tools support more fine-grained permission controls: 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 + 1. The `:*` wildcard only works at the end of a pattern for prefix matching + 2. The `*` wildcard can appear at any position and matches any sequence of characters 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 @@ -113,14 +141,16 @@ Some tools support more fine-grained permission controls: For more reliable URL filtering, consider: - * Using the WebFetch tool with `WebFetch(domain:github.com)` permission + * **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 - * Using hooks for custom permission validation + + 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 & 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. +`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 and Glob. Read & Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types: @@ -147,39 +177,40 @@ Read & Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore **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 - - Unlike other permission types, MCP permissions do NOT support wildcards (`*`). +**Task (Subagents)** - To approve all tools from an MCP server: +Use `Task(AgentName)` rules to control which [subagents](/en/sub-agents) Claude can use: - * ✅ Use: `mcp__github` (approves ALL GitHub tools) - * ❌ Don't use: `mcp__github__*` (wildcards are not supported) +* `Task(Explore)` Matches the Explore subagent +* `Task(Plan)` Matches the Plan subagent +* `Task(Verify)` Matches the Verify subagent - To approve specific tools only, list each one: +Add these rules to the `deny` array in your [settings](/en/settings#permission-settings) or use the `--disallowedTools` CLI flag to disable specific agents. For example, to disable the Explore agent: - * ✅ Use: `mcp__github__get_issue` - * ✅ Use: `mcp__github__list_issues` - +```json theme={null} +{ + "permissions": { + "deny": ["Task(Explore)"] + } +} +``` ### 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 policy settings - -For enterprise deployments of Claude Code, we support enterprise managed policy settings that take precedence over user and project settings. This allows system administrators to enforce security policies that users cannot override. - -System administrators can deploy policies to the [managed settings file locations](/en/settings#settings-files). +### Managed settings -These policy files follow the same format as regular [settings files](/en/settings#settings-files) but cannot be overridden by user or project settings. This ensures consistent security policies across your organization. +For organizations that need centralized control over Claude Code configuration, administrators can deploy `managed-settings.json` files 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. Enterprise policies +1. Managed settings (`managed-settings.json`) 2. Command line arguments 3. Local project settings (`.claude/settings.local.json`) 4. Shared project settings (`.claude/settings.json`) diff --git a/skills/working-with-claude-code/references/interactive-mode.md b/skills/working-with-claude-code/references/interactive-mode.md index e3e5aa6..cda62f5 100644 --- a/skills/working-with-claude-code/references/interactive-mode.md +++ b/skills/working-with-claude-code/references/interactive-mode.md @@ -5,47 +5,78 @@ ## Keyboard shortcuts - Keyboard shortcuts may vary by platform and terminal. Press `?` to see available shortcuts for your environment. For example, Option key combinations on macOS may require configuring your terminal to use Option as a meta/escape key. + 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+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` (macOS/Linux) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file | -| `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 | -| `Tab` | Toggle [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) | Switch between Thinking on and Thinking off | -| `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 | +| 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 | -| Terminal setup | `Shift+Enter` | After `/terminal-setup` | -| Control sequence | `Ctrl+J` | Line feed character for multiline | -| Paste mode | Paste directly | For code blocks, logs | +| 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 | - Configure your preferred line break behavior in terminal settings. Run `/terminal-setup` to install Shift+Enter binding for iTerm2 and VS Code terminals. + 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 | Memory shortcut - add to CLAUDE.md | Prompts for file selection | -| `/` at start | Slash command | See [slash commands](/en/slash-commands) | -| `!` at start | Bash mode | Run commands directly and add execution output to the session | -| `@` | File path mention | Trigger file path autocomplete | +| Shortcut | Description | Notes | +| :----------- | :---------------- | :------------------------------------------------------------ | +| `/` at start | Slash command | See [slash commands](/en/slash-commands) | +| `!` at start | Bash mode | Run commands directly and add execution output to the session | +| `@` | File path mention | Trigger file path autocomplete | ## Vim editor mode @@ -65,17 +96,23 @@ Enable vim-style editing with `/vim` command or configure permanently via `/conf ### 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 | +| 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 | ### Editing (NORMAL mode) @@ -88,8 +125,29 @@ Enable vim-style editing with `/vim` command or configure permanently via `/conf | `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: @@ -130,10 +188,12 @@ To run commands in the background, you can either: **Key features:** -* Output is buffered and Claude can retrieve it using the BashOutput tool +* 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) diff --git a/skills/working-with-claude-code/references/mcp.md b/skills/working-with-claude-code/references/mcp.md index 0860ccb..229e2eb 100644 --- a/skills/working-with-claude-code/references/mcp.md +++ b/skills/working-with-claude-code/references/mcp.md @@ -37,8 +37,12 @@ export const MCPServersTable = ({platform = "all"}) => { mcpConnector: worksWith.includes('claude-api'), claudeDesktop: worksWith.includes('claude-desktop') }; - const remoteUrl = server.remotes?.[0]?.url || meta.url; - const remoteType = server.remotes?.[0]?.type; + 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) { @@ -277,21 +281,22 @@ Stdio servers run as local processes on your machine. They're ideal for tools th ```bash theme={null} # Basic syntax -claude mcp add --transport stdio [args...] +claude mcp add [options] -- [args...] # Real example: Add Airtable server -claude mcp add --transport stdio airtable --env AIRTABLE_API_KEY=YOUR_KEY \ +claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \ -- npx -y airtable-mcp-server ``` - **Understanding the "--" parameter:** - The `--` (double dash) separates Claude's own CLI flags from the command and arguments that get passed to the MCP server. Everything before `--` are options for Claude (like `--env`, `--scope`), and everything after `--` is the actual command to run the 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 myserver --env KEY=value -- python server.py --port 8080` → runs `python server.py --port 8080` with `KEY=value` in environment + * `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. @@ -314,6 +319,10 @@ claude mcp remove github /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: @@ -466,7 +475,7 @@ Select your scope based on: * **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) - * **Enterprise managed**: `managed-mcp.json` in system directories (see [Enterprise MCP configuration](#enterprise-mcp-configuration)) + * **Managed**: `managed-mcp.json` in system directories (see [Managed MCP configuration](#managed-mcp-configuration))
### Scope hierarchy and precedence @@ -792,6 +801,62 @@ MCP servers can expose resources that you can reference using @ mentions, simila * 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 slash commands MCP servers can expose prompts that become available as slash commands in Claude Code. @@ -831,17 +896,32 @@ MCP servers can expose prompts that become available as slash commands in Claude * Server and prompt names are normalized (spaces become underscores) -## Enterprise MCP configuration +## Managed MCP configuration + +For organizations that need centralized control over MCP servers, Claude Code supports two configuration options: -For organizations that need centralized control over MCP servers, Claude Code supports enterprise-managed MCP configurations. This allows IT administrators to: +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**: Optionally restrict users from adding their own MCP servers +* **Prevent unauthorized MCP servers**: Restrict users from adding unapproved MCP servers * **Disable MCP entirely**: Remove MCP functionality completely if needed -### Setting up enterprise MCP configuration +### 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 can deploy an enterprise MCP configuration file alongside the managed settings file. See [settings files](/en/settings#settings-files) for the `managed-mcp.json` file locations on each platform. +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: @@ -868,18 +948,23 @@ The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file: } ``` -### Restricting MCP servers with allowlists and denylists +### 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). -In addition to providing enterprise-managed servers, administrators can control which MCP servers users are allowed to configure using `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 two ways: +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 **either** `serverName` **or** `serverCommand`, not both. +**Important**: Each entry must have exactly one of `serverName`, `serverCommand`, or `serverUrl`. #### Example configuration @@ -892,14 +977,21 @@ Each entry in the allowlist or denylist can restrict servers in two ways: // Allow by exact command (for stdio servers) { "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] }, - { "serverCommand": ["python", "/usr/local/bin/approved-server.py"] } + { "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"] } + { "serverCommand": ["npx", "-y", "unapproved-package"] }, + + // Block by URL pattern (for remote servers) + { "serverUrl": "https://*.untrusted.com/*" } ] } ``` @@ -919,9 +1011,44 @@ Each entry in the allowlist or denylist can restrict servers in two ways: **Non-stdio server behavior**: -* Remote servers (HTTP, SSE, WebSocket) always match by name only +* 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} { @@ -979,7 +1106,7 @@ Each entry in the allowlist or denylist can restrict servers in two ways: * `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 or command +* List of entries: Users can only configure servers that match by name, command, or URL pattern #### Denylist behavior (`deniedMcpServers`) @@ -989,12 +1116,12 @@ Each entry in the allowlist or denylist can restrict servers in two ways: #### Important notes -* These restrictions apply to all scopes: user, project, local, and even enterprise servers from `managed-mcp.json` -* **Denylist takes absolute precedence**: If a server matches a denylist entry (by name or command), it will be blocked even if it's on the allowlist -* Name-based and command-based restrictions work together: a server passes if it matches **either** a name entry **or** a command entry (unless blocked by denylist) +* **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) - **Enterprise configuration precedence**: The enterprise MCP configuration has the highest precedence and cannot be overridden by user, local, or project configurations. + **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. diff --git a/skills/working-with-claude-code/references/memory.md b/skills/working-with-claude-code/references/memory.md index 738c464..afcba9d 100644 --- a/skills/working-with-claude-code/references/memory.md +++ b/skills/working-with-claude-code/references/memory.md @@ -54,16 +54,6 @@ Claude Code reads memories recursively: starting in the cwd, Claude Code recurse 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. -## Quickly add memories with the `#` shortcut - -The fastest way to add a memory is to start your input with the `#` character: - -``` -# Always use descriptive variable names -``` - -You'll be prompted to select which memory file to store this in. - ## Directly edit memories with `/memory` Use the `/memory` slash command during a session to open any memory file in your system editor for more extensive additions or organization. @@ -113,7 +103,8 @@ Rules can be scoped to specific files using YAML frontmatter with the `paths` fi ```markdown theme={null} --- -paths: src/api/**/*.ts +paths: + - "src/api/**/*.ts" --- # API Development Rules @@ -136,24 +127,31 @@ The `paths` field supports standard glob patterns: | `*.md` | Markdown files in the project root | | `src/components/*.tsx` | React components in a specific directory | -You can use braces to match multiple patterns efficiently: +You can specify multiple patterns: ```markdown theme={null} --- -paths: src/**/*.{ts,tsx} +paths: + - "src/**/*.ts" + - "lib/**/*.ts" + - "tests/**/*.test.ts" --- - -# TypeScript/React Rules ``` -This expands to match both `src/**/*.ts` and `src/**/*.tsx`. You can also combine multiple patterns with commas: +Brace expansion is supported for matching multiple extensions or directories: ```markdown theme={null} --- -paths: {src,lib}/**/*.ts, tests/**/*.test.ts +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: @@ -208,11 +206,11 @@ User-level rules are loaded before project rules, giving project rules higher pr ## Organization-level memory management -Enterprise organizations can deploy centrally managed CLAUDE.md files that apply to all users. +Organizations can deploy centrally managed CLAUDE.md files that apply to all users. To set up organization-level memory management: -1. Create the enterprise memory file at the **Enterprise policy** location shown in the [memory types table above](#determine-memory-type). +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. diff --git a/skills/working-with-claude-code/references/monitoring-usage.md b/skills/working-with-claude-code/references/monitoring-usage.md index 6f142a8..dee022b 100644 --- a/skills/working-with-claude-code/references/monitoring-usage.md +++ b/skills/working-with-claude-code/references/monitoring-usage.md @@ -66,23 +66,24 @@ Example managed settings configuration: ### 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 | +| 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 @@ -120,11 +121,9 @@ The script must output valid JSON with string key-value pairs representing HTTP echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}" ``` -#### Important limitations +#### Refresh behavior -**Headers are fetched only at startup, not during runtime.** This is due to OpenTelemetry exporter architecture limitations. - -For scenarios requiring frequent token refresh, use an OpenTelemetry Collector as a proxy that can refresh its own headers. +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 diff --git a/skills/working-with-claude-code/references/overview.md b/skills/working-with-claude-code/references/overview.md index 872252c..9e41b11 100644 --- a/skills/working-with-claude-code/references/overview.md +++ b/skills/working-with-claude-code/references/overview.md @@ -6,35 +6,55 @@ Prerequisites: -* A [Claude.ai](https://claude.ai) (recommended) or [Claude Console](https://console.anthropic.com/) account +* 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. + - ```bash theme={null} + ```sh theme={null} brew install --cask claude-code ``` - - - ```powershell theme={null} - irm https://claude.ai/install.ps1 | iex - ``` + + Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes. + - - ```bash theme={null} - npm install -g @anthropic-ai/claude-code + + ```powershell theme={null} + winget install Anthropic.ClaudeCode ``` - Requires [Node.js 18+](https://nodejs.org/en/download/) + + WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes. + @@ -48,7 +68,7 @@ claude You'll be prompted to log in on first use. That's it! [Continue with Quickstart (5 minutes) →](/en/quickstart) - Claude Code automatically keeps itself up to date. See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues. + 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 @@ -88,6 +108,10 @@ You'll be prompted to log in on first use. That's it! [Continue with Quickstart ## Additional resources + + Learn more about Claude Code on claude.com + + Create custom AI agents with the Claude Agent SDK diff --git a/skills/working-with-claude-code/references/plugin-marketplaces.md b/skills/working-with-claude-code/references/plugin-marketplaces.md index fe97f17..9c6a601 100644 --- a/skills/working-with-claude-code/references/plugin-marketplaces.md +++ b/skills/working-with-claude-code/references/plugin-marketplaces.md @@ -1,129 +1,119 @@ -# Plugin marketplaces +# Create and distribute a plugin marketplace -> Create and manage plugin marketplaces to distribute Claude Code extensions across teams and communities. +> Build and host plugin marketplaces to distribute Claude Code extensions across teams and communities. -Plugin marketplaces are catalogs of available plugins that make it easy to discover, install, and manage Claude Code extensions. This guide shows you how to use existing marketplaces and create your own for team distribution. +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. -## Overview - -A marketplace is a JSON file that lists available plugins and describes where to find them. Marketplaces provide: - -* **Centralized discovery**: Browse plugins from multiple sources in one place -* **Version management**: Track and update plugin versions automatically -* **Team distribution**: Share required plugins across your organization -* **Flexible sources**: Support for git repositories, GitHub repos, local paths, and package managers - -### Prerequisites - -* Claude Code installed and running -* Basic familiarity with JSON file format -* For creating marketplaces: Git repository or local development environment +Looking to install plugins from an existing marketplace? See [Discover and install prebuilt plugins](/en/discover-plugins). -## Add and use marketplaces - -Add marketplaces using the `/plugin marketplace` commands to access plugins from different sources: - -### Add GitHub marketplaces - -```shell Add a GitHub repository containing .claude-plugin/marketplace.json theme={null} -/plugin marketplace add owner/repo -``` +## Overview -### Add Git repositories +Creating and distributing a marketplace involves: -```shell Add any git repository theme={null} -/plugin marketplace add https://gitlab.com/company/plugins.git -``` +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)). -### Add local marketplaces for development +Once your marketplace is live, you can update it by pushing changes to your repository. Users refresh their local copy with `/plugin marketplace update`. -```shell Add local directory containing .claude-plugin/marketplace.json theme={null} -/plugin marketplace add ./my-marketplace -``` +## Walkthrough: create a local marketplace -```shell Add direct path to marketplace.json file theme={null} -/plugin marketplace add ./path/to/marketplace.json -``` +This example creates a marketplace with one plugin: a `/review` command for code reviews. You'll create the directory structure, add a slash command, create the plugin manifest and marketplace catalog, then install and test it. -```shell Add remote marketplace.json via URL theme={null} -/plugin marketplace add https://url.of/marketplace.json -``` + + + ```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/commands + ``` + -### Install plugins from marketplaces + + Create a Markdown file that defines what the `/review` command does. -Once you've added marketplaces, install plugins directly: + ```markdown my-marketplace/plugins/review-plugin/commands/review.md theme={null} + Review the code I've selected or the recent changes for: + - Potential bugs or edge cases + - Security concerns + - Performance issues + - Readability improvements -```shell Install from any known marketplace theme={null} -/plugin install plugin-name@marketplace-name -``` + Be concise and actionable. + ``` + -```shell Browse available plugins interactively theme={null} -/plugin -``` + + Create a `plugin.json` file that describes the plugin. The manifest goes in the `.claude-plugin/` directory. -### Verify marketplace installation + ```json my-marketplace/plugins/review-plugin/.claude-plugin/plugin.json theme={null} + { + "name": "review-plugin", + "description": "Adds a /review command for quick code reviews", + "version": "1.0.0" + } + ``` + -After adding a marketplace: + + Create the marketplace catalog that lists your plugin. -1. **List marketplaces**: Run `/plugin marketplace list` to confirm it's added -2. **Browse plugins**: Use `/plugin` to see available plugins from your marketplace -3. **Test installation**: Try installing a plugin to verify the marketplace works correctly + ```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 command for quick code reviews" + } + ] + } + ``` + -### Example plugin marketplace + + Add the marketplace and install the plugin. -Claude Code maintains a marketplace of [demo plugins](https://github.com/anthropics/claude-code/tree/main/plugins). These plugins are examples of what's possible with the plugin system. + ```shell theme={null} + /plugin marketplace add ./my-marketplace + /plugin install review-plugin@my-plugins + ``` + -```shell Add the marketplace theme={null} -/plugin marketplace add anthropics/claude-code -``` + + Select some code in your editor and run your new command. -## Configure team marketplaces + ```shell theme={null} + /review + ``` + + -Set up automatic marketplace installation for team projects by specifying required marketplaces in `.claude/settings.json`: +To learn more about what plugins can do, including hooks, agents, MCP servers, and LSP servers, see [Plugins](/en/plugins). -```json theme={null} -{ - "extraKnownMarketplaces": { - "team-tools": { - "source": { - "source": "github", - "repo": "your-org/claude-plugins" - } - }, - "project-specific": { - "source": { - "source": "git", - "url": "https://git.company.com/project-plugins.git" - } - } - } -} -``` - -When team members trust the repository folder, Claude Code automatically installs these marketplaces and any plugins specified in the `enabledPlugins` field. - -*** - -## Create your own marketplace - -Build and distribute custom plugin collections for your team or community. + + **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. -### Prerequisites for marketplace creation + 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. + -* Git repository (GitHub, GitLab, or other git hosting) -* Understanding of JSON file format -* One or more plugins to distribute +## Create the marketplace file -### 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. -Create `.claude-plugin/marketplace.json` in your repository root: +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@company.com" + "email": "devtools@example.com" }, "plugins": [ { @@ -147,55 +137,62 @@ Create `.claude-plugin/marketplace.json` in your repository root: } ``` -### Marketplace schema +## 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 | -#### Required fields + + **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. + -| Field | Type | Description | -| :-------- | :----- | :--------------------------------------------- | -| `name` | string | Marketplace identifier (kebab-case, no spaces) | -| `owner` | object | Marketplace maintainer information | -| `plugins` | array | List of available plugins | +### Owner fields -#### Optional metadata +| Field | Type | Required | Description | +| :------ | :----- | :------- | :------------------------------- | +| `name` | string | Yes | Name of the maintainer or team | +| `email` | string | No | Contact email for the maintainer | -| Field | Type | Description | -| :--------------------- | :----- | :------------------------------------ | -| `metadata.description` | string | Brief marketplace description | -| `metadata.version` | string | Marketplace version | -| `metadata.pluginRoot` | string | Base path for relative plugin sources | +### Optional metadata -### Plugin entries +| 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 are based on the *plugin manifest schema* (with all fields made - optional) plus marketplace-specific fields (`source`, `category`, `tags`, - `strict`), with `name` being required. - +## 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:** +### Required fields -| Field | Type | Description | -| :------- | :------------- | :---------------------------------------- | -| `name` | string | Plugin identifier (kebab-case, no spaces) | -| `source` | string\|object | Where to fetch the plugin from | +| 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 +### Optional plugin fields **Standard metadata fields:** -| Field | Type | Description | -| :------------ | :------ | :---------------------------------------------------------------- | -| `description` | string | Brief plugin description | -| `version` | string | Plugin version | -| `author` | object | Plugin author information | -| `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 | Require plugin.json in plugin folder (default: true) 1 | +| 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:** @@ -205,12 +202,11 @@ Create `.claude-plugin/marketplace.json` in your repository root: | `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 | -*1 - When `strict: true` (default), the plugin must include a `plugin.json` manifest file, and marketplace fields supplement those values. When `strict: false`, the plugin.json is optional. If it's missing, the marketplace entry serves as the complete plugin manifest.* +## Plugin sources -### Plugin sources - -#### Relative paths +### Relative paths For plugins in the same repository: @@ -221,7 +217,11 @@ For plugins in the same repository: } ``` -#### GitHub repositories + + 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} { @@ -233,7 +233,7 @@ For plugins in the same repository: } ``` -#### Git repositories +### Git repositories ```json theme={null} { @@ -245,9 +245,9 @@ For plugins in the same repository: } ``` -#### Advanced plugin entries +### Advanced plugin entries -Plugin entries can override default component locations and provide additional metadata. Note that `${CLAUDE_PLUGIN_ROOT}` is an environment variable that resolves to the plugin's installation directory (for details see [Environment variables](/en/plugins-reference#environment-variables)): +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} { @@ -260,9 +260,9 @@ Plugin entries can override default component locations and provide additional m "version": "2.1.0", "author": { "name": "Enterprise Team", - "email": "enterprise@company.com" + "email": "enterprise@example.com" }, - "homepage": "https://docs.company.com/plugins/enterprise-tools", + "homepage": "https://docs.example.com/plugins/enterprise-tools", "repository": "https://github.com/company/enterprise-plugin", "license": "MIT", "keywords": ["enterprise", "workflow", "automation"], @@ -296,91 +296,185 @@ Plugin entries can override default component locations and provide additional m } ``` - - **Schema relationship**: Plugin entries use the plugin manifest schema with - all fields made optional, plus marketplace-specific fields (`source`, - `strict`, `category`, `tags`). This means any field valid in a `plugin.json` - file can also be used in a marketplace entry. When `strict: false`, the - marketplace entry serves as the complete plugin manifest if no `plugin.json` - exists. When `strict: true` (default), marketplace fields supplement the - plugin's own manifest file. - +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 -Choose the best hosting strategy for your plugin distribution needs. - ### 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**: Team members add with `/plugin marketplace add owner/repo` +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 for marketplace distribution, using a URL to an arbitrary git repository. - -For example, using GitLab: +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 ``` -### Use local marketplaces for development +### Private repositories -Test your marketplace locally before distribution: +Claude Code supports installing plugins from private repositories. Set the appropriate authentication token in your environment, and Claude Code will use it when authentication is required. -```shell Add local marketplace for testing theme={null} -/plugin marketplace add ./my-local-marketplace +| 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 ``` -```shell Test plugin installation theme={null} +Authentication tokens are only used when a repository requires authentication. Public repositories work without any tokens configured, even if tokens are present in your environment. + + + 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 ``` -## Manage marketplace operations +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`: -### List known marketplaces +```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: -```shell List all configured marketplaces theme={null} -/plugin marketplace list +```json theme={null} +{ + "enabledPlugins": { + "code-formatter@company-tools": true, + "deployment-tools@company-tools": true + } +} ``` -Shows all configured marketplaces with their sources and status. +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. -### Update marketplace metadata +When `strictKnownMarketplaces` is configured in managed settings, the restriction behavior depends on the value: -```shell Refresh marketplace metadata theme={null} -/plugin marketplace update marketplace-name +| 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": [] +} ``` -Refreshes plugin listings and metadata from the marketplace source. +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" + } + ] +} +``` -### Remove a marketplace +#### How restrictions work -```shell Remove a marketplace theme={null} -/plugin marketplace remove marketplace-name +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 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 + +Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-file-locations), 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 . ``` -Removes the marketplace from your configuration. +Or from within Claude Code: - - Removing a marketplace will uninstall any plugins you installed from it. - +```shell theme={null} +/plugin validate . +``` -*** +Add the marketplace for testing: -## Troubleshooting marketplaces +```shell theme={null} +/plugin marketplace add ./path/to/marketplace +``` -### Common marketplace issues +Install a test plugin to verify everything works: -#### Marketplace not loading +```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 @@ -388,10 +482,27 @@ Removes the marketplace from your configuration. * 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` +* Ensure JSON syntax is valid using `claude plugin validate` or `/plugin validate` * For private repositories, confirm you have access permissions -#### Plugin installation failures +### 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 @@ -402,53 +513,50 @@ Removes the marketplace from your configuration. * For GitHub sources, ensure repositories are public or you have access * Test plugin sources manually by cloning/downloading -### Validation and testing +### Private repository authentication fails -Test your marketplace before sharing: +**Symptoms**: Authentication errors when installing plugins from private repositories, even with tokens configured -```bash Validate marketplace JSON syntax theme={null} -claude plugin validate . -``` +**Solutions**: -```shell Add marketplace for testing theme={null} -/plugin marketplace add ./path/to/marketplace -``` +* Verify your token is set in the current shell session: `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 +* If using multiple git providers, ensure you've set the token for the correct provider -```shell Install test plugin theme={null} -/plugin install test-plugin@marketplace-name -``` +### Plugins with relative paths fail in URL-based marketplaces -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). +**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. -## Next steps +**Solutions**: -### For marketplace users +* **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. -* **Discover community marketplaces**: Search GitHub for Claude Code plugin collections -* **Contribute feedback**: Report issues and suggest improvements to marketplace maintainers -* **Share useful marketplaces**: Help your team discover valuable plugin collections +### Files not found after installation -### For marketplace creators +**Symptoms**: Plugin installs but references to files fail, especially files outside the plugin directory -* **Build plugin collections**: Create themed marketplace around specific use cases -* **Establish versioning**: Implement clear versioning and update policies -* **Community engagement**: Gather feedback and maintain active marketplace communities -* **Documentation**: Provide clear README files explaining your marketplace contents +**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. -### For organizations +**Solutions**: See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for workarounds including symlinks and directory restructuring. -* **Private marketplaces**: Set up internal marketplaces for proprietary tools -* **Governance policies**: Establish guidelines for plugin approval and security review -* **Training resources**: Help teams discover and adopt useful plugins effectively +For additional debugging tools and common issues, see [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools). ## See also -* [Plugins](/en/plugins) - Installing and using plugins +* [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 development](/en/plugins#develop-more-complex-plugins) - Creating your own plugins -* [Settings](/en/settings#plugin-configuration) - Plugin configuration options +* [Plugin settings](/en/settings#plugin-settings) - Plugin configuration options +* [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces) - Managed marketplace restrictions --- diff --git a/skills/working-with-claude-code/references/plugins-reference.md b/skills/working-with-claude-code/references/plugins-reference.md index eb34dbc..a0c005e 100644 --- a/skills/working-with-claude-code/references/plugins-reference.md +++ b/skills/working-with-claude-code/references/plugins-reference.md @@ -3,7 +3,7 @@ > Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications. - For hands-on tutorials and practical usage, see [Plugins](/en/plugins). For plugin management across teams and communities, see [Plugin marketplaces](/en/plugin-marketplaces). + 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. @@ -120,11 +120,13 @@ Plugins can provide event handlers that respond to Claude Code events automatica **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 -* `PostToolUse`: After Claude uses any tool * `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 @@ -133,8 +135,8 @@ Plugins can provide event handlers that respond to Claude Code events automatica **Hook types**: * `command`: Execute shell commands or scripts -* `validation`: Validate file contents or project state -* `notification`: Send alerts or status updates +* `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 @@ -172,6 +174,106 @@ Plugins can bundle Model Context Protocol (MCP) servers to connect Claude Code w * 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 @@ -196,8 +298,11 @@ The `plugin.json` file defines your plugin's metadata and configuration. This se "keywords": ["keyword1", "keyword2"], "commands": ["./custom/commands/special.md"], "agents": "./custom/agents/", + "skills": "./custom/skills/", "hooks": "./config/hooks.json", - "mcpServers": "./mcp-config.json" + "mcpServers": "./mcp-config.json", + "outputStyles": "./styles/", + "lspServers": "./.lsp.json" } ``` @@ -221,12 +326,15 @@ The `plugin.json` file defines your plugin's metadata and configuration. This se ### 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/"` | -| `hooks` | string\|object | Hook config path or inline config | `"./hooks.json"` | -| `mcpServers` | string\|object | MCP config path or inline config | `"./custom-mcp-config.json"` | +| 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 @@ -275,6 +383,59 @@ The `plugin.json` file defines your plugin's metadata and configuration. This se *** +## 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 @@ -287,7 +448,7 @@ enterprise-plugin/ │ └── plugin.json # Required: plugin manifest ├── commands/ # Default command location │ ├── status.md -│ └── logs.md +│ └── logs.md ├── agents/ # Default agent location │ ├── security-reviewer.md │ ├── performance-tester.md @@ -302,6 +463,7 @@ enterprise-plugin/ │ ├── 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 @@ -319,11 +481,128 @@ enterprise-plugin/ | Component | Default Location | Purpose | | :-------------- | :--------------------------- | :------------------------------- | | **Manifest** | `.claude-plugin/plugin.json` | Required metadata file | -| **Commands** | `commands/` | Slash command markdown files | -| **Agents** | `agents/` | Subagent markdown files | +| **Commands** | `commands/` | Slash command Markdown files | +| **Agents** | `agents/` | Subagent Markdown files | | **Skills** | `skills/` | Agent Skills with SKILL.md files | | **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 | | *** @@ -346,13 +625,81 @@ This shows: ### Common issues -| Issue | Cause | Solution | -| :--------------------- | :------------------------------ | :--------------------------------------------------- | -| Plugin not loading | Invalid `plugin.json` | Validate JSON syntax | -| 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 `./` | +| 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 *** @@ -363,18 +710,37 @@ This shows: 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 -- [Slash commands](/en/slash-commands) - Command development details -- [Subagents](/en/sub-agents) - Agent configuration and capabilities -- [Agent Skills](/en/skills) - Extend Claude's capabilities -- [Hooks](/en/hooks) - Event handling and automation -- [MCP](/en/mcp) - External tool integration -- [Settings](/en/settings) - Configuration options for plugins -``` +* [Plugins](/en/plugins) - Tutorials and practical usage +* [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing marketplaces +* [Slash commands](/en/slash-commands) - Command development details +* [Subagents](/en/sub-agents) - Agent configuration and capabilities +* [Agent Skills](/en/skills) - Extend Claude's capabilities +* [Hooks](/en/hooks) - Event handling and automation +* [MCP](/en/mcp) - External tool integration +* [Settings](/en/settings) - Configuration options for plugins --- diff --git a/skills/working-with-claude-code/references/plugins.md b/skills/working-with-claude-code/references/plugins.md index eaf4802..918dfaa 100644 --- a/skills/working-with-claude-code/references/plugins.md +++ b/skills/working-with-claude-code/references/plugins.md @@ -1,394 +1,411 @@ -# Plugins +# Create plugins -> Extend Claude Code with custom commands, agents, hooks, Skills, and MCP servers through the plugin system. +> Create custom plugins to extend Claude Code with slash commands, agents, hooks, Skills, 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 slash commands, agents, Skills, 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 slash commands, agents, and hooks: + +| Approach | Slash command 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 slash commands or hooks before packaging them +* You want short slash command names like `/hello` or `/review` + +**Use plugins when**: + +* You want to share functionality with your team or community +* You need the same slash commands/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 slash commands like `/my-plugin:hello` (namespacing prevents conflicts between plugins) - For complete technical specifications and schemas, see [Plugins reference](/en/plugins-reference). For marketplace management, see [Plugin marketplaces](/en/plugin-marketplaces). + 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. -Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. Install plugins from [marketplaces](/en/plugin-marketplaces) to add pre-built commands, agents, hooks, Skills, and MCP servers, or create your own to automate your workflows. - ## Quickstart -Let's create a simple greeting plugin to get you familiar with the plugin system. We'll build a working plugin that adds a custom command, test it locally, and understand the core concepts. +This quickstart walks you through creating a plugin with a custom slash command. You'll create a manifest (the configuration file that defines your plugin), add a slash command, and test it locally using the `--plugin-dir` flag. ### Prerequisites -* Claude Code installed on your machine -* Basic familiarity with command-line tools +* 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 - - ```bash theme={null} - mkdir test-marketplace - cd test-marketplace - ``` - - + Every plugin lives in its own directory containing a manifest and your custom commands, agents, or hooks. Create one now: + ```bash theme={null} mkdir my-first-plugin - cd my-first-plugin ``` - ```bash Create .claude-plugin/plugin.json theme={null} - mkdir .claude-plugin - cat > .claude-plugin/plugin.json << 'EOF' + 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 simple greeting plugin to learn the basics", + "description": "A greeting plugin to learn the basics", "version": "1.0.0", "author": { "name": "Your Name" } } - EOF ``` + + | Field | Purpose | + | :------------ | :--------------------------------------------------------------------------------------------------------------------- | + | `name` | Unique identifier and slash command namespace. Slash commands 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). - - ```bash Create commands/hello.md theme={null} - mkdir commands - cat > commands/hello.md << 'EOF' + + Slash commands are Markdown files in the `commands/` directory. The filename becomes the slash command name, prefixed with the plugin's namespace (`hello.md` in a plugin named `my-first-plugin` creates `/my-first-plugin:hello`). The Markdown content tells Claude how to respond when someone runs the slash command. + + Create a `commands` directory in your plugin folder: + + ```bash theme={null} + mkdir my-first-plugin/commands + ``` + + Then create `my-first-plugin/commands/hello.md` with this content: + + ```markdown my-first-plugin/commands/hello.md theme={null} --- - description: Greet the user with a personalized message + description: Greet the user with a friendly message --- # Hello Command - Greet the user warmly and ask how you can help them today. Make the greeting personal and encouraging. - EOF + Greet the user warmly and ask how you can help them today. ``` - - ```bash Create marketplace.json theme={null} - cd .. - mkdir .claude-plugin - cat > .claude-plugin/marketplace.json << 'EOF' - { - "name": "test-marketplace", - "owner": { - "name": "Test User" - }, - "plugins": [ - { - "name": "my-first-plugin", - "source": "./my-first-plugin", - "description": "My first test plugin" - } - ] - } - EOF - ``` - + + Run Claude Code with the `--plugin-dir` flag to load your plugin: - - ```bash Start Claude Code from parent directory theme={null} - cd .. - claude + ```bash theme={null} + claude --plugin-dir ./my-first-plugin ``` - ```shell Add the test marketplace theme={null} - /plugin marketplace add ./test-marketplace + Once Claude Code starts, try your new command: + + ```shell theme={null} + /my-first-plugin:hello ``` - ```shell Install your plugin theme={null} - /plugin install my-first-plugin@test-marketplace + You'll see Claude respond with a greeting. Run `/help` to see your command listed under the plugin namespace. + + + **Why namespacing?** Plugin slash commands are always namespaced (like `/greet:hello`) to prevent conflicts when multiple plugins have commands with the same name. + + To change the namespace prefix, update the `name` field in `plugin.json`. + + + + + Make your slash command dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the slash command. + + 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. ``` - Select "Install now". You'll then need to restart Claude Code in order to use the new plugin. + Restart Claude Code to pick up the changes, then try the command with your name: - ```shell Try your new command theme={null} - /hello + ```shell theme={null} + /my-first-plugin:hello Alex ``` - You'll see Claude use your greeting command! Check `/help` to see your new command listed. + Claude will greet you by name. For more argument options like `$1`, `$2` for individual parameters, see [Slash commands](/en/slash-commands). 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 slash commands -* **Test marketplace** - Allows you to test your plugin locally +* **Plugin manifest** (`.claude-plugin/plugin.json`): describes your plugin's metadata +* **Commands directory** (`commands/`): contains your custom slash commands +* **Command arguments** (`$ARGUMENTS`): captures user input for dynamic behavior -### Plugin structure overview + + 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). + -Your plugin follows this basic structure: +## Plugin structure overview -``` -my-first-plugin/ -├── .claude-plugin/ -│ └── plugin.json # Plugin metadata -├── commands/ # Custom slash commands (optional) -│ └── hello.md -├── agents/ # Custom agents (optional) -│ └── helper.md -├── skills/ # Agent Skills (optional) -│ └── my-skill/ -│ └── SKILL.md -└── hooks/ # Event handlers (optional) - └── hooks.json -``` +You've created a plugin with a slash command, but plugins can include much more: custom agents, Skills, hooks, MCP servers, and LSP servers. -**Additional components you can add:** + + **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. + -* **Commands**: Create markdown files in `commands/` directory -* **Agents**: Create agent definitions in `agents/` directory -* **Skills**: Create `SKILL.md` files in `skills/` directory -* **Hooks**: Create `hooks/hooks.json` for event handling -* **MCP servers**: Create `.mcp.json` for external tool integration +| Directory | Location | Purpose | +| :---------------- | :---------- | :---------------------------------------------- | +| `.claude-plugin/` | Plugin root | Contains only `plugin.json` manifest (required) | +| `commands/` | Plugin root | Slash commands 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, and MCP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/plugins-reference). + **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). -*** - -## Install and manage plugins - -Learn how to discover, install, and manage plugins to extend your Claude Code capabilities. +## Develop more complex plugins -### Prerequisites +Once you're comfortable with basic plugins, you can create more sophisticated extensions. -* Claude Code installed and running -* Basic familiarity with command-line interfaces +### Add Skills to your plugin -### Add marketplaces +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. -Marketplaces are catalogs of available plugins. Add them to discover and install plugins: +Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files: -```shell Add a marketplace theme={null} -/plugin marketplace add your-org/claude-plugins ``` - -```shell Browse available plugins theme={null} -/plugin +my-plugin/ +├── .claude-plugin/ +│ └── plugin.json +└── skills/ + └── code-review/ + └── SKILL.md ``` -For detailed marketplace management including Git repositories, local development, and team distribution, see [Plugin marketplaces](/en/plugin-marketplaces). - -### Install plugins +Each `SKILL.md` needs frontmatter with `name` and `description` fields, followed by instructions: -#### Via interactive menu (recommended for discovery) +```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. +--- -```shell Open the plugin management interface theme={null} -/plugin +When reviewing code, check for: +1. Code organization and structure +2. Error handling +3. Security concerns +4. Test coverage ``` -Select "Browse Plugins" to see available options with descriptions, features, and installation options. +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). -#### Via direct commands (for quick installation) +### Add LSP servers to your plugin -```shell Install a specific plugin theme={null} -/plugin install formatter@your-org -``` + + 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. + -```shell Enable a disabled plugin theme={null} -/plugin enable plugin-name@marketplace-name -``` +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: -```shell Disable without uninstalling theme={null} -/plugin disable plugin-name@marketplace-name +```json .lsp.json theme={null} +{ + "go": { + "command": "gopls", + "args": ["serve"], + "extensionToLanguage": { + ".go": "go" + } + } +} ``` -```shell Completely remove a plugin theme={null} -/plugin uninstall plugin-name@marketplace-name -``` +Users installing your plugin must have the language server binary installed on their machine. -### Verify installation +For complete LSP configuration options, see [LSP servers](/en/plugins-reference#lsp-servers). -After installing a plugin: +### Organize complex plugins -1. **Check available commands**: Run `/help` to see new commands -2. **Test plugin features**: Try the plugin's commands and features -3. **Review plugin details**: Use `/plugin` → "Manage Plugins" to see what the plugin provides +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). -## Set up team plugin workflows +### Test your plugins locally -Configure plugins at the repository level to ensure consistent tooling across your team. When team members trust your repository folder, Claude Code automatically installs specified marketplaces and plugins. +Use the `--plugin-dir` flag to test plugins during development. This loads your plugin directly without requiring installation. -**To set up team plugins:** +```bash theme={null} +claude --plugin-dir ./my-plugin +``` -1. Add marketplace and plugin configuration to your repository's `.claude/settings.json` -2. Team members trust the repository folder -3. Plugins install automatically for all team members +As you make changes to your plugin, restart Claude Code to pick up the updates. Test your plugin components: -For complete instructions including configuration examples, marketplace setup, and rollout best practices, see [Configure team marketplaces](/en/plugin-marketplaces#how-to-configure-team-marketplaces). +* 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: -## Develop more complex plugins + ```bash theme={null} + claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two + ``` + -Once you're comfortable with basic plugins, you can create more sophisticated extensions. +### Debug plugin issues -### Add Skills to your plugin +If your plugin isn't working as expected: -Plugins can include [Agent Skills](/en/skills) to extend Claude's capabilities. Skills are model-invoked—Claude autonomously uses them based on the task context. +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 -To add Skills to your plugin, create a `skills/` directory at your plugin root and add Skill folders with `SKILL.md` files. Plugin Skills are automatically available when the plugin is installed. +### Share your plugins -For complete Skill authoring guidance, see [Agent Skills](/en/skills). +When your plugin is ready to share: -### Organize complex plugins +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 -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). +Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins). -### Test your plugins locally + + For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference). + -When developing plugins, use a local marketplace to test changes iteratively. This workflow builds on the quickstart pattern and works for plugins of any complexity. +## Convert existing configurations to plugins - - - Organize your plugin and marketplace for testing: +If you already have custom commands, Skills, or hooks in your `.claude/` directory, you can convert them into a plugin for easier sharing and distribution. - ```bash Create directory structure theme={null} - mkdir dev-marketplace - cd dev-marketplace - mkdir my-plugin - ``` +### Migration steps - This creates: + + + Create a new plugin directory: + ```bash theme={null} + mkdir -p my-plugin/.claude-plugin ``` - dev-marketplace/ - ├── .claude-plugin/marketplace.json (you'll create this) - └── my-plugin/ (your plugin under development) - ├── .claude-plugin/plugin.json - ├── commands/ - ├── agents/ - └── hooks/ - ``` - - - ```bash Create marketplace.json theme={null} - mkdir .claude-plugin - cat > .claude-plugin/marketplace.json << 'EOF' - { - "name": "dev-marketplace", - "owner": { - "name": "Developer" - }, - "plugins": [ + Create the manifest file at `my-plugin/.claude-plugin/plugin.json`: + + ```json my-plugin/.claude-plugin/plugin.json theme={null} { "name": "my-plugin", - "source": "./my-plugin", - "description": "Plugin under development" + "description": "Migrated from standalone configuration", + "version": "1.0.0" } - ] - } - EOF ``` - - ```bash Start Claude Code from parent directory theme={null} - cd .. - claude - ``` + + Copy your existing configurations to the plugin directory: - ```shell Add your development marketplace theme={null} - /plugin marketplace add ./dev-marketplace - ``` - - ```shell Install your plugin theme={null} - /plugin install my-plugin@dev-marketplace - ``` + ```bash theme={null} + # Copy commands + cp -r .claude/commands my-plugin/ - Test your plugin components: + # Copy agents (if any) + cp -r .claude/agents my-plugin/ - * Try your commands with `/command-name` - * Check that agents appear in `/agents` - * Verify hooks work as expected + # Copy skills (if any) + cp -r .claude/skills my-plugin/ + ``` - - After making changes to your plugin code: + + If you have hooks in your settings, create a hooks directory: - ```shell Uninstall the current version theme={null} - /plugin uninstall my-plugin@dev-marketplace + ```bash theme={null} + mkdir my-plugin/hooks ``` - ```shell Reinstall to test changes theme={null} - /plugin install my-plugin@dev-marketplace - ``` + Create `my-plugin/hooks/hooks.json` with your hooks configuration. Copy the `hooks` object from your `.claude/settings.json` or `settings.local.json`—the format is the same: - Repeat this cycle as you develop and refine your plugin. + ```json my-plugin/hooks/hooks.json theme={null} + { + "hooks": { + "PostToolUse": [ + { + "matcher": "Write|Edit", + "hooks": [{ "type": "command", "command": "npm run lint:fix $FILE" }] + } + ] + } + } + ``` - - - - **For multiple plugins**: Organize plugins in subdirectories like `./plugins/plugin-name` and update your marketplace.json accordingly. See [Plugin sources](/en/plugin-marketplaces#plugin-sources) for organization patterns. - -### Debug plugin issues - -If your plugin isn't working as expected: + + Load your plugin to verify everything works: -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 + ```bash theme={null} + claude --plugin-dir ./my-plugin + ``` -### Share your plugins + Test each component: run your commands, check agents appear in `/agents`, and verify hooks trigger correctly. + + -When your plugin is ready to share: +### What changes when migrating -1. **Add documentation**: Include a README.md with installation and usage instructions -2. **Version your plugin**: Use semantic versioning in your `plugin.json` -3. **Create or use a marketplace**: Distribute through plugin marketplaces for installation -4. **Test with others**: Have team members test the plugin before wider distribution +| 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` | - For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference). + 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 plugins**: Browse community marketplaces for useful tools -* **Team adoption**: Set up repository-level plugins for your projects -* **Marketplace management**: Learn to manage multiple plugin sources -* **Advanced usage**: Explore plugin combinations and workflows +* [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 your first marketplace**: [Plugin marketplaces guide](/en/plugin-marketplaces) -* **Advanced components**: Dive deeper into specific plugin components: - * [Slash commands](/en/slash-commands) - Command development details - * [Subagents](/en/sub-agents) - Agent configuration and capabilities - * [Agent Skills](/en/skills) - Extend Claude's capabilities - * [Hooks](/en/hooks) - Event handling and automation - * [MCP](/en/mcp) - External tool integration -* **Distribution strategies**: Package and share your plugins effectively -* **Community contribution**: Consider contributing to community plugin collections - -### For team leads and administrators - -* **Repository configuration**: Set up automatic plugin installation for team projects -* **Plugin governance**: Establish guidelines for plugin approval and security review -* **Marketplace maintenance**: Create and maintain organization-specific plugin catalogs -* **Training and documentation**: Help team members adopt plugin workflows effectively - -## See also - -* [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing plugin catalogs -* [Slash commands](/en/slash-commands) - Understanding custom commands -* [Subagents](/en/sub-agents) - Creating and using specialized agents -* [Agent Skills](/en/skills) - Extend Claude's capabilities -* [Hooks](/en/hooks) - Automating workflows with event handlers -* [MCP](/en/mcp) - Connecting to external tools and services -* [Settings](/en/settings) - Configuration options for plugins +* [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: + * [Slash commands](/en/slash-commands): command development details + * [Subagents](/en/sub-agents): agent configuration and capabilities + * [Agent Skills](/en/skills): extend Claude's capabilities + * [Hooks](/en/hooks): event handling and automation + * [MCP](/en/mcp): external tool integration --- diff --git a/skills/working-with-claude-code/references/quickstart.md b/skills/working-with-claude-code/references/quickstart.md index d6398e7..cefd482 100644 --- a/skills/working-with-claude-code/references/quickstart.md +++ b/skills/working-with-claude-code/references/quickstart.md @@ -10,7 +10,7 @@ Make sure you have: * A terminal or command prompt open * A code project to work with -* A [Claude.ai](https://claude.ai) (recommended) or [Claude Console](https://console.anthropic.com/) account +* A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise) or [Claude Console](https://console.anthropic.com/) account ## Step 1: Install Claude Code @@ -18,12 +18,6 @@ To install Claude Code, use one of the following methods: - **Homebrew (macOS, Linux):** - - ```sh theme={null} - brew install --cask claude-code - ``` - **macOS, Linux, WSL:** ```bash theme={null} @@ -41,14 +35,30 @@ To install Claude Code, use one of the following methods: ```batch theme={null} curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd ``` - - - If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/): + + Native installations automatically update in the background to keep you on the latest version. + + + ```sh theme={null} - npm install -g @anthropic-ai/claude-code + 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. + @@ -66,9 +76,9 @@ claude # Follow the prompts to log in with your account ``` -You can log in using either account type: +You can log in using any of these account types: -* [Claude.ai](https://claude.ai) (subscription plans - recommended) +* [Claude Pro, Max, Teams, or Enterprise](https://claude.com/pricing) (recommended) * [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits) Once logged in, your credentials are stored and you won't need to log in again. @@ -240,17 +250,17 @@ There are a number of ways to work with Claude: 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 | `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` | +| 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. @@ -319,6 +329,10 @@ Now that you've learned the basics, explore more advanced features: Run tasks asynchronously in the cloud + + + Learn more on claude.com + ## Getting help diff --git a/skills/working-with-claude-code/references/sandboxing.md b/skills/working-with-claude-code/references/sandboxing.md index a6fc2be..4800d50 100644 --- a/skills/working-with-claude-code/references/sandboxing.md +++ b/skills/working-with-claude-code/references/sandboxing.md @@ -216,7 +216,7 @@ For implementation details and source code, visit the [GitHub repository](https: * [Security](/en/security) - Comprehensive security features and best practices * [IAM](/en/iam) - Permission configuration and access control * [Settings](/en/settings) - Complete configuration reference -* [CLI reference](/en/cli-reference) - Command-line options including `-sb` +* [CLI reference](/en/cli-reference) - Command-line options --- diff --git a/skills/working-with-claude-code/references/security.md b/skills/working-with-claude-code/references/security.md index d9a37fa..ef8d5dd 100644 --- a/skills/working-with-claude-code/references/security.md +++ b/skills/working-with-claude-code/references/security.md @@ -113,7 +113,7 @@ For more details on cloud execution, see [Claude Code on the web](/en/claude-cod ### Team security -* Use [enterprise managed policies](/en/iam#enterprise-managed-policy-settings) to enforce organizational standards +* Use [managed settings](/en/iam#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) diff --git a/skills/working-with-claude-code/references/settings.md b/skills/working-with-claude-code/references/settings.md index cb82919..31acdb4 100644 --- a/skills/working-with-claude-code/references/settings.md +++ b/skills/working-with-claude-code/references/settings.md @@ -4,6 +4,71 @@ 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 @@ -14,19 +79,22 @@ Code through hierarchical settings: * **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. -* For enterprise deployments of Claude Code, we also support **enterprise - managed policy settings**. These take precedence over user and project - settings. System administrators can deploy policies to: - * 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` - * `C:\ProgramData\ClaudeCode\managed-settings.json` will be deprecated in a future version. -* Enterprise deployments can also configure **managed MCP servers** that override - user-configured servers. See [Enterprise MCP configuration](/en/mcp#enterprise-mcp-configuration): - * 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` - * `C:\ProgramData\ClaudeCode\managed-mcp.json` will be deprecated in a future version. +* **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/iam#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`. ```JSON Example settings.json theme={null} @@ -60,40 +128,140 @@ Code through hierarchical 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 before or after tool executions. See [hooks documentation](/en/hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` | -| `disableAllHooks` | Disable all [hooks](/en/hooks) | `true` | -| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` | -| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` | -| `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 [Enterprise MCP configuration](/en/mcp#enterprise-mcp-configuration) | `[{ "serverName": "github" }]` | -| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including enterprise servers. Denylist takes precedence over allowlist. See [Enterprise MCP configuration](/en/mcp#enterprise-mcp-configuration) | `[{ "serverName": "filesystem" }]` | -| `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` | +| 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 before or after tool executions. See [hooks documentation](/en/hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` | +| `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` | +| `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) 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` | +| `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](/en/iam#configuring-permissions) to allow tool use. **Note:** Bash rules use prefix matching, not regex | `[ "Bash(git diff:*)" ]` | -| `ask` | Array of [permission rules](/en/iam#configuring-permissions) to ask for confirmation upon tool use. | `[ "Bash(git push:*)" ]` | -| `deny` | Array of [permission rules](/en/iam#configuring-permissions) to deny tool use. Use this to also exclude sensitive files from Claude Code access. **Note:** Bash patterns are prefix matches and can be bypassed (see [Bash permission limitations](/en/iam#tool-specific-permission-rules)) | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` | -| `additionalDirectories` | Additional [working directories](/en/iam#working-directories) that Claude has access to | `[ "../docs/" ]` | -| `defaultMode` | Default [permission mode](/en/iam#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 policy settings](/en/iam#enterprise-managed-policy-settings) | `"disable"` | +| 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/iam#tool-specific-permission-rules) | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` | +| `additionalDirectories` | Additional [working directories](/en/iam#working-directories) that Claude has access to | `[ "../docs/" ]` | +| `defaultMode` | Default [permission mode](/en/iam#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/iam#managed-settings) | `"disable"` | + +### Permission rule syntax + +Permission rules follow the format `Tool` or `Tool(specifier)`. Understanding the syntax helps you write rules that match exactly what you intend. + +#### Rule evaluation order + +When multiple rules could match the same tool use, rules are evaluated in this order: + +1. **Deny** rules are checked first +2. **Ask** rules are checked second +3. **Allow** rules are checked last + +The first matching rule determines the behavior. This means deny rules always take precedence over allow rules, even if both match the same command. + +#### Matching 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(*)` does **not** match all Bash commands. The `*` wildcard only matches within the specifier context. To allow or deny all uses of a tool, use just the tool name: `Bash`, not `Bash(*)`. + + +#### Using 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 + +Two wildcard syntaxes are available for Bash rules: + +| Wildcard | Position | Behavior | Example | +| :------- | :------------------ | :---------------------------------------------------------------------- | :-------------------------------------------------------- | +| `:*` | End of pattern only | **Prefix matching** - matches commands starting with the prefix | `Bash(npm run:*)` matches `npm run test`, `npm run build` | +| `*` | Anywhere in pattern | **Glob matching** - matches any sequence of characters at that position | `Bash(* install)` matches `npm install`, `yarn install` | + +**Prefix matching with `:*`** + +The `:*` suffix matches any command that starts with the specified prefix. This works with multi-word commands. The following configuration allows npm and git commit commands while blocking git push and rm -rf: + +```json theme={null} +{ + "permissions": { + "allow": [ + "Bash(npm run:*)", + "Bash(git commit:*)", + "Bash(docker compose:*)" + ], + "deny": [ + "Bash(git push:*)", + "Bash(rm -rf:*)" + ] + } +} +``` + +**Glob matching with `*`** + +The `*` wildcard can appear at the beginning, middle, or end of a pattern. The following configuration allows any git command targeting main (like `git checkout main`, `git merge main`) and any version check command (like `node --version`, `npm --version`): + +```json theme={null} +{ + "permissions": { + "allow": [ + "Bash(git * main)", + "Bash(* --version)" + ] + } +} +``` + + + Bash permission rules use pattern matching and can be bypassed using shell features like command flags, variables, or redirects. For example, `Bash(curl:*)` can be bypassed with `curl -X GET` reordered to `curl http://example.com -X GET`. Do not rely on Bash deny rules as a security boundary. + + +For detailed information about tool-specific permission patterns—including Read, Edit, WebFetch, MCP, Task rules, and Bash permission limitations—see [Tool-specific permission rules](/en/iam#tool-specific-permission-rules). ### Sandbox settings @@ -185,13 +353,65 @@ Claude Code adds attribution to git commits and pull requests. These are configu 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. **Enterprise managed policies** (`managed-settings.json`) - * Deployed by IT/DevOps - * Can't be overridden +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 @@ -205,7 +425,7 @@ Settings apply in order of precedence. From highest to lowest: 5. **User settings** (`~/.claude/settings.json`) * Personal global settings -This hierarchy ensures that enterprise security policies are always enforced while still allowing teams and individuals to customize their experience. +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. @@ -215,7 +435,7 @@ For example, if your user settings allow `Bash(npm run:*)` but a project's share * **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior * **Slash commands**: Custom commands that can be invoked during a session with `/command-name` * **MCP servers**: Extend Claude Code with additional tools and integrations -* **Precedence**: Higher-level configurations (Enterprise) override lower-level ones (User/Project) +* **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 @@ -262,14 +482,14 @@ Plugin-related settings in `settings.json`: ```json theme={null} { "enabledPlugins": { - "formatter@company-tools": true, - "deployer@company-tools": true, + "formatter@acme-tools": true, + "deployer@acme-tools": true, "analyzer@security-plugins": false }, "extraKnownMarketplaces": { - "company-tools": { + "acme-tools": { "source": "github", - "repo": "company/claude-plugins" + "repo": "acme-corp/claude-plugins" } } } @@ -313,16 +533,16 @@ Defines additional marketplaces that should be made available for the repository ```json theme={null} { "extraKnownMarketplaces": { - "company-tools": { + "acme-tools": { "source": { "source": "github", - "repo": "company-org/claude-plugins" + "repo": "acme-corp/claude-plugins" } }, "security-plugins": { "source": { "source": "git", - "url": "https://git.company.com/security/plugins.git" + "url": "https://git.example.com/security/plugins.git" } } } @@ -335,6 +555,194 @@ Defines additional marketplaces that should be made available for the repository * `git`: Any git URL (uses `url`) * `directory`: Local filesystem path (uses `path`, for development only) +#### `strictKnownMarketplaces` + +**Managed settings only**: Controls which plugin marketplaces users are allowed to add. This setting can only be configured in [`managed-settings.json`](/en/iam#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) + +**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 six marketplace source types. Each source must match exactly for a user's marketplace addition to be allowed. + +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`) + +**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": [] +} +``` + +**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: @@ -355,89 +763,101 @@ 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 you want to add to the request (in `Name: Value` format) | -| `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_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_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command | -| `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_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_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 | -| `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_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) | -| `HTTP_PROXY` | Specify HTTP proxy server for network connections | -| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections | -| `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` | Enable [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) and set the token budget for the thinking process. 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). Disabled by default. | -| `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 slash command metadata shown to [SlashCommand tool](/en/slash-commands#slashcommand-tool) (default: 15000) | -| `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 | +| 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 you want to add to the request (in `Name: Value` format) | +| `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_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_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_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_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_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_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 slash command metadata shown to the [Skill tool](/en/slash-commands#skill-tool) (default: 15000) | +| `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 the user multiple choice questions to gather information or clarify ambiguity | No | -| **Bash** | Executes shell commands in your environment (see [Bash tool behavior](#bash-tool-behavior) below) | Yes | -| **BashOutput** | Retrieves output from a background bash shell | 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 | -| **NotebookEdit** | Modifies Jupyter notebook cells | Yes | -| **Read** | Reads the contents of files | No | -| **Skill** | Executes a skill within the main conversation | Yes | -| **SlashCommand** | Runs a [custom slash command](/en/slash-commands#slashcommand-tool) | Yes | -| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No | -| **TodoWrite** | Creates and manages structured task lists | No | -| **WebFetch** | Fetches content from a specified URL | Yes | -| **WebSearch** | Performs web searches with domain filtering | Yes | -| **Write** | Creates or overwrites files | Yes | +| 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 or slash command](/en/slash-commands#skill-tool) within the main conversation | Yes | +| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No | +| **TodoWrite** | Creates and manages structured task lists | No | +| **WebFetch** | Fetches content from a specified URL | Yes | +| **WebSearch** | Performs web searches with domain filtering | Yes | +| **Write** | Creates or overwrites files | Yes | Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/iam#tool-specific-permission-rules). @@ -514,8 +934,9 @@ files by blocking Write operations to certain paths. ## See also -* [Identity and Access Management](/en/iam#configuring-permissions) - Learn about Claude Code's permission system -* [IAM and access control](/en/iam#enterprise-managed-policy-settings) - Enterprise policy management +* [Identity and Access Management](/en/iam#configuring-permissions) - Permission system overview and how allow/ask/deny rules interact +* [Tool-specific permission rules](/en/iam#tool-specific-permission-rules) - Detailed patterns for Bash, Read, Edit, WebFetch, MCP, and Task tools, including security limitations +* [Managed settings](/en/iam#managed-settings) - Managed policy configuration for organizations * [Troubleshooting](/en/troubleshooting#auto-updater-issues) - Solutions for common configuration issues diff --git a/skills/working-with-claude-code/references/setup.md b/skills/working-with-claude-code/references/setup.md index f193e66..06c9981 100644 --- a/skills/working-with-claude-code/references/setup.md +++ b/skills/working-with-claude-code/references/setup.md @@ -4,61 +4,67 @@ ## System requirements -* **Operating Systems**: macOS 10.15+, Ubuntu 20.04+/Debian 10+, or Windows 10+ (with WSL 1, WSL 2, or Git for Windows) +* **Operating Systems**: macOS 13.0+, Ubuntu 20.04+/Debian 10+, or Windows 10+ (with WSL 1, WSL 2, or Git for Windows) * **Hardware**: 4 GB+ RAM -* **Software**: [Node.js 18+](https://nodejs.org/en/download) (only required for npm installation) -* **Network**: Internet connection required for authentication and AI processing -* **Shell**: Works best in Bash, Zsh or Fish +* **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) -## Standard installation +## Installation To install Claude Code, use one of the following methods: - **Homebrew (macOS, Linux):** - - ```sh theme={null} theme={null} - brew install --cask claude-code - ``` - **macOS, Linux, WSL:** - ```bash theme={null} theme={null} + ```bash theme={null} curl -fsSL https://claude.ai/install.sh | bash ``` **Windows PowerShell:** - ```powershell theme={null} theme={null} + ```powershell theme={null} irm https://claude.ai/install.ps1 | iex ``` **Windows CMD:** - ```batch theme={null} theme={null} + ```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. + - - If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/): + + ```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. + + - ```sh theme={null} theme={null} - npm install -g @anthropic-ai/claude-code + + ```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. + - - Some users may be automatically migrated to an improved installation method. - - After the installation process completes, navigate to your project and start Claude Code: ```bash theme={null} @@ -66,113 +72,111 @@ cd your-awesome-project claude ``` -Claude Code offers the following authentication options: - -1. **Claude Console**: The default option. Connect through the Claude Console and complete the OAuth process. Requires active billing in the [Anthropic console](https://console.anthropic.com). 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. -2. **Claude App (with Pro or Max plan)**: Subscribe to Claude's [Pro or Max plan](https://claude.com/pricing) for a unified subscription that includes both Claude Code and the web interface. Get more value at the same price point while managing your account in one place. Log in with your Claude.ai account. During launch, choose the option that matches your subscription type. -3. **Enterprise platforms**: Configure Claude Code to use [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) for enterprise deployments with your existing cloud infrastructure. - - - Claude Code securely stores your credentials. See [Credential Management](/en/iam#credential-management) for details. - - -## Windows setup - -**Option 1: Claude Code within WSL** - -* Both WSL 1 and WSL 2 are supported - -**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" - ``` - -## Alternative installation methods - -Claude Code offers multiple installation methods to suit different environments. - -If you encounter any issues during installation, consult the [troubleshooting guide](/en/troubleshooting#linux-permission-issues). +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. -### Native installation options + + **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`. + -The native installation is the recommended method and offers several benefits: +### Authentication -* One self-contained executable -* No Node.js dependency -* Improved auto-updater stability +#### For individuals -If you have an existing installation of Claude Code, use `claude install` to migrate to the native binary installation. +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 advanced installation options with the native installer: +#### For teams and organizations -**macOS, Linux, WSL:** +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. -```bash theme={null} -# Install stable version (default) -curl -fsSL https://claude.ai/install.sh | bash +### Install a specific version -# Install latest version -curl -fsSL https://claude.ai/install.sh | bash -s latest +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. -# Install specific version number -curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58 -``` +To install the latest version (default): - - **Alpine Linux and other musl/uClibc-based distributions**: The native build requires `libgcc`, `libstdc++`, and `ripgrep`. For Alpine: `apk add libgcc libstdc++ ripgrep`. Set `USE_BUILTIN_RIPGREP=0`. - + + + ```bash theme={null} + curl -fsSL https://claude.ai/install.sh | bash + ``` + - - Claude Code installed via Homebrew will auto-update outside of the brew directory unless explicitly disabled with the `DISABLE_AUTOUPDATER` environment variable (see [Auto updates](#auto-updates) section). - + + ```powershell theme={null} + irm https://claude.ai/install.ps1 | iex + ``` + -**Windows PowerShell:** + + ```batch theme={null} + curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd + ``` + + -```powershell theme={null} -# Install stable version (default) -irm https://claude.ai/install.ps1 | iex +To install the stable version: -# Install latest version -& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest + + + ```bash theme={null} + curl -fsSL https://claude.ai/install.sh | bash -s stable + ``` + -# Install specific version number -& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58 -``` + + ```powershell theme={null} + & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) stable + ``` + -**Windows CMD:** + + ```batch theme={null} + curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd stable && del install.cmd + ``` + + -```batch theme={null} -REM Install stable version (default) -curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd +To install a specific version number: -REM Install latest version -curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd latest && del install.cmd + + + ```bash theme={null} + curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58 + ``` + -REM Install specific version number -curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 1.0.58 && del install.cmd -``` + + ```powershell theme={null} + & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58 + ``` + - - Make sure that you remove any outdated aliases or symlinks before installing. - + + ```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** +### 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 +## 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`. -For environments where NPM is preferred or required: +**Global npm installation** ```sh theme={null} npm install -g @anthropic-ai/claude-code @@ -183,11 +187,19 @@ npm install -g @anthropic-ai/claude-code If you encounter permission errors, see [configure Claude Code](/en/troubleshooting#linux-permission-issues) for recommended solutions. -## Running on AWS or GCP +## Windows setup -By default, Claude Code uses the Claude API. +**Option 1: Claude Code within WSL** -For details on running Claude Code on AWS or GCP, see [third-party integrations](/en/third-party-integrations). +* Both WSL 1 and WSL 2 are supported + +**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 @@ -200,7 +212,30 @@ Claude Code automatically keeps itself up to date to ensure you have the latest * **Notifications**: You'll see a notification when updates are installed * **Applying updates**: Updates take effect the next time you start Claude Code -**Disable auto-updates:** + + 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/iam#managed-settings). + +### Disable auto-updates Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/settings): @@ -220,27 +255,27 @@ If you need to uninstall Claude Code, follow the instructions for your installat ### Native installation -Remove the Claude Code binary and symlink: +Remove the Claude Code binary and version files: **macOS, Linux, WSL:** ```bash theme={null} rm -f ~/.local/bin/claude -rm -rf ~/.claude-code +rm -rf ~/.local/share/claude ``` **Windows PowerShell:** ```powershell theme={null} -Remove-Item -Path "$env:LOCALAPPDATA\Programs\claude-code" -Recurse -Force -Remove-Item -Path "$env:LOCALAPPDATA\Microsoft\WindowsApps\claude.exe" -Force +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} -rmdir /s /q "%LOCALAPPDATA%\Programs\claude-code" -del "%LOCALAPPDATA%\Microsoft\WindowsApps\claude.exe" +del "%USERPROFILE%\.local\bin\claude.exe" +rmdir /s /q "%USERPROFILE%\.local\share\claude" ``` ### Homebrew installation @@ -249,6 +284,12 @@ del "%LOCALAPPDATA%\Microsoft\WindowsApps\claude.exe" brew uninstall --cask claude-code ``` +### WinGet installation + +```powershell theme={null} +winget uninstall Anthropic.ClaudeCode +``` + ### NPM installation ```bash theme={null} diff --git a/skills/working-with-claude-code/references/skills.md b/skills/working-with-claude-code/references/skills.md index 5058f50..18ac7b6 100644 --- a/skills/working-with-claude-code/references/skills.md +++ b/skills/working-with-claude-code/references/skills.md @@ -2,483 +2,412 @@ > Create, manage, and share Skills to extend Claude's capabilities in Claude Code. -This guide shows you how to create, use, and manage Agent Skills in Claude Code. Skills are modular capabilities that extend Claude's functionality through organized folders containing instructions, scripts, and resources. +This guide shows you how to create, use, and manage Agent Skills in Claude Code. For background on how Skills work across Claude products, see [What are Skills?](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview). -## Prerequisites +A Skill is a markdown file that teaches Claude how to do something specific: reviewing PRs using your team's standards, generating commit messages in your preferred format, or querying your company's database schema. When you ask Claude something that matches a Skill's purpose, Claude automatically applies it. -* Claude Code version 1.0 or later -* Basic familiarity with [Claude Code](/en/quickstart) +## Create your first Skill -## What are Agent Skills? +This example creates a personal Skill that teaches Claude to explain code using visual diagrams and analogies. Unlike Claude's default explanations, this Skill ensures every explanation includes an ASCII diagram and a real-world analogy. -Agent Skills package expertise into discoverable capabilities. Each Skill consists of a `SKILL.md` file with instructions that Claude reads when relevant, plus optional supporting files like scripts and templates. + + + Before creating a Skill, see what Skills Claude already has access to: -**How Skills are invoked**: Skills are **model-invoked**—Claude autonomously decides when to use them based on your request and the Skill's description. This is different from slash commands, which are **user-invoked** (you explicitly type `/command` to trigger them). + ``` + What Skills are available? + ``` -**Benefits**: + Claude will list any Skills currently loaded. You may see none, or you may see Skills from plugins or your organization. + -* Extend Claude's capabilities for your specific workflows -* Share expertise across your team via git -* Reduce repetitive prompting -* Compose multiple Skills for complex tasks + + Create a directory for the Skill in your personal Skills folder. Personal Skills are available across all your projects. (You can also create [project Skills](#where-skills-live) in `.claude/skills/` to share with your team.) -Learn more in the [Agent Skills overview](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview). + ```bash theme={null} + mkdir -p ~/.claude/skills/explaining-code + ``` + - - For a deep dive into the architecture and real-world applications of Agent Skills, read our engineering blog: [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills). - + + Every Skill needs a `SKILL.md` file. The file starts with YAML metadata between `---` markers and must include a `name` and `description`, followed by Markdown instructions that Claude follows when the Skill is active. -## Create a Skill + The `description` is especially important, because Claude uses it to decide when to apply the Skill. -Skills are stored as directories containing a `SKILL.md` file. + Create `~/.claude/skills/explaining-code/SKILL.md`: -### Personal Skills + ```yaml theme={null} + --- + name: explaining-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?" + --- -Personal Skills are available across all your projects. Store them in `~/.claude/skills/`: + When explaining code, always include: -```bash theme={null} -mkdir -p ~/.claude/skills/my-skill-name -``` + 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? -**Use personal Skills for**: + Keep explanations conversational. For complex concepts, use multiple analogies. + ``` + -* Your individual workflows and preferences -* Experimental Skills you're developing -* Personal productivity tools + + Skills are automatically loaded when created or modified. Verify the Skill appears in the list: -### Project Skills + ``` + What Skills are available? + ``` -Project Skills are shared with your team. Store them in `.claude/skills/` within your project: + You should see `explaining-code` in the list with its description. + -```bash theme={null} -mkdir -p .claude/skills/my-skill-name -``` + + Open any file in your project and ask Claude a question that matches the Skill's description: -**Use project Skills for**: + ``` + How does this code work? + ``` -* Team workflows and conventions -* Project-specific expertise -* Shared utilities and scripts + Claude should ask to use the `explaining-code` Skill, then include an analogy and ASCII diagram in its explanation. If the Skill doesn't trigger, try rephrasing to include more keywords from the description, like "explain how this works." + + -Project Skills are checked into git and automatically available to team members. +The rest of this guide covers how Skills work, configuration options, and troubleshooting. -### Plugin Skills +## How Skills work -Skills can also come from [Claude Code plugins](/en/plugins). Plugins may bundle Skills that are automatically available when the plugin is installed. These Skills work the same way as personal and project Skills. +Skills are **model-invoked**: Claude decides which Skills to use based on your request. You don't need to explicitly call a Skill. Claude automatically applies relevant Skills when your request matches their description. -## Write SKILL.md +When you send a request, Claude follows these steps to find and use relevant Skills: -Create a `SKILL.md` file with YAML frontmatter and Markdown content: + + + At startup, Claude loads only the name and description of each available Skill. This keeps startup fast while giving Claude enough context to know when each Skill might be relevant. + -```yaml theme={null} ---- -name: your-skill-name -description: Brief description of what this Skill does and when to use it ---- + + When your request matches a Skill's description, Claude asks to use the Skill. You'll see a confirmation prompt before the full `SKILL.md` is loaded into context. Since Claude reads these descriptions to find relevant Skills, [write descriptions](#skill-not-triggering) that include keywords users would naturally say. + -# Your Skill Name + + Claude follows the Skill's instructions, loading referenced files or running bundled scripts as needed. + + -## Instructions -Provide clear, step-by-step guidance for Claude. +### Where Skills live -## Examples -Show concrete examples of using this Skill. -``` +Where you store a Skill determines who can use it: -**Field requirements**: +| Location | Path | Applies to | +| :--------- | :----------------------------------------------- | :-------------------------------- | +| Enterprise | See [managed settings](/en/iam#managed-settings) | All users in your organization | +| Personal | `~/.claude/skills/` | You, across all projects | +| Project | `.claude/skills/` | Anyone working in this repository | +| Plugin | Bundled with [plugins](/en/plugins) | Anyone with the plugin installed | -* `name`: Must use lowercase letters, numbers, and hyphens only (max 64 characters) -* `description`: Brief description of what the Skill does and when to use it (max 1024 characters) +If two Skills have the same name, the higher row wins: managed overrides personal, personal overrides project, and project overrides plugin. -The `description` field is critical for Claude to discover when to use your Skill. It should include both what the Skill does and when Claude should use it. +#### Automatic discovery from nested directories -See the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance including validation rules. +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. -## Add supporting files +### When to use Skills versus other options -Create additional files alongside SKILL.md: +Claude Code offers several ways to customize behavior. The key difference: **Skills are triggered automatically by Claude** based on your request, while slash commands require you to type `/command` explicitly. -``` -my-skill/ -├── SKILL.md (required) -├── reference.md (optional documentation) -├── examples.md (optional examples) -├── scripts/ -│ └── helper.py (optional utility) -└── templates/ - └── template.txt (optional template) -``` +| Use this | When you want to... | When it runs | +| :--------------------------------------- | :------------------------------------------------------------------------- | :----------------------------------------- | +| **Skills** | Give Claude specialized knowledge (e.g., "review PRs using our standards") | Claude chooses when relevant | +| **[Slash commands](/en/slash-commands)** | Create reusable prompts (e.g., `/deploy staging`) | You type `/command` to run it | +| **[CLAUDE.md](/en/memory)** | Set project-wide instructions (e.g., "use TypeScript strict mode") | Loaded into every conversation | +| **[Subagents](/en/sub-agents)** | Delegate tasks to a separate context with its own tools | Claude delegates, or you invoke explicitly | +| **[Hooks](/en/hooks)** | Run scripts on events (e.g., lint on file save) | Fires on specific tool events | +| **[MCP servers](/en/mcp)** | Connect Claude to external tools and data sources | Claude calls MCP tools as needed | -Reference these files from SKILL.md: +**Skills vs. subagents**: Skills add knowledge to the current conversation. Subagents run in a separate context with their own tools. Use Skills for guidance and standards; use subagents when you need isolation or different tool access. -````markdown theme={null} -For advanced usage, see [reference.md](reference.md). +**Skills vs. MCP**: Skills tell Claude *how* to use tools; MCP *provides* the tools. For example, an MCP server connects Claude to your database, while a Skill teaches Claude your data model and query patterns. -Run the helper script: -```bash -python scripts/helper.py input.txt -``` -```` + + For a deep dive into the architecture and real-world applications of Agent Skills, read [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills). + + +## Configure Skills -Claude reads these files only when needed, using progressive disclosure to manage context efficiently. +This section covers Skill file structure, supporting files, tool restrictions, and distribution options. -## Restrict tool access with allowed-tools +### Write SKILL.md -Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active: +The `SKILL.md` file is the only required file in a Skill. It has two parts: YAML metadata (the section between `---` markers) at the top, and Markdown instructions that tell Claude how to use the Skill: ```yaml theme={null} --- -name: safe-file-reader -description: Read files without making changes. Use when you need read-only file access. -allowed-tools: Read, Grep, Glob +name: your-skill-name +description: Brief description of what this Skill does and when to use it --- -# Safe File Reader - -This Skill provides read-only file access. +# Your Skill Name ## Instructions -1. Use Read to view file contents -2. Use Grep to search within files -3. Use Glob to find files by pattern -``` - -When this Skill is active, Claude can only use the specified tools (Read, Grep, Glob) without needing to ask for permission. This is useful for: - -* Read-only Skills that shouldn't modify files -* Skills with limited scope: for example, only data analysis, no file writing -* Security-sensitive workflows where you want to restrict capabilities - -If `allowed-tools` isn't specified, Claude will ask for permission to use tools as normal, following the standard permission model. - - - `allowed-tools` is only supported for Skills in Claude Code. - - -## View available Skills - -Skills are automatically discovered by Claude from three sources: - -* Personal Skills: `~/.claude/skills/` -* Project Skills: `.claude/skills/` -* Plugin Skills: bundled with installed plugins - -**To view all available Skills**, ask Claude directly: - -``` -What Skills are available? -``` - -or - -``` -List all available Skills -``` - -This will show all Skills from all sources, including plugin Skills. - -**To inspect a specific Skill**, you can also check the filesystem: - -```bash theme={null} -# List personal Skills -ls ~/.claude/skills/ - -# List project Skills (if in a project directory) -ls .claude/skills/ +Provide clear, step-by-step guidance for Claude. -# View a specific Skill's content -cat ~/.claude/skills/my-skill/SKILL.md +## Examples +Show concrete examples of using this Skill. ``` -## Test a Skill +#### Available metadata fields -After creating a Skill, test it by asking questions that match your description. +You can use the following fields in the YAML frontmatter: -**Example**: If your description mentions "PDF files": +| Field | Required | Description | +| :--------------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `name` | Yes | Skill name. Must use lowercase letters, numbers, and hyphens only (max 64 characters). Should match the directory name. | +| `description` | Yes | What the Skill does and when to use it (max 1024 characters). Claude uses this to decide when to apply the Skill. | +| `allowed-tools` | No | Tools Claude can use without asking permission when this Skill is active. Supports comma-separated values or YAML-style lists. See [Restrict tool access](#restrict-tool-access-with-allowed-tools). | +| `model` | No | [Model](https://docs.claude.com/en/docs/about-claude/models/overview) to use when this Skill is active (e.g., `claude-sonnet-4-20250514`). Defaults to the conversation's model. | +| `context` | No | Set to `fork` to run the Skill in a forked sub-agent context with its own conversation history. | +| `agent` | No | Specify which [agent type](/en/sub-agents#built-in-subagents) to use when `context: fork` is set (e.g., `Explore`, `Plan`, `general-purpose`, or a custom agent name from `.claude/agents/`). Defaults to `general-purpose` if not specified. Only applicable when combined with `context: fork`. | +| `hooks` | No | Define hooks scoped to this Skill's lifecycle. Supports `PreToolUse`, `PostToolUse`, and `Stop` events. | +| `user-invocable` | No | Controls whether the Skill appears in the slash command menu. Does not affect the [`Skill` tool](/en/slash-commands#skill-tool) or automatic discovery. Defaults to `true`. See [Control Skill visibility](#control-skill-visibility). | -``` -Can you help me extract text from this PDF? -``` - -Claude autonomously decides to use your Skill if it matches the request—you don't need to explicitly invoke it. The Skill activates automatically based on the context of your question. - -## Debug a Skill +#### Available string substitutions -If Claude doesn't use your Skill, check these common issues: +Skills support string substitution for dynamic values in the Skill content: -### Make description specific +| Variable | Description | +| :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | +| `$ARGUMENTS` | All arguments passed when invoking the Skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: `. | +| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating Skill output with sessions. | -**Too vague**: +**Example using substitutions:** ```yaml theme={null} -description: Helps with documents -``` - -**Specific**: - -```yaml theme={null} -description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. -``` - -Include both what the Skill does and when to use it in the description. - -### Verify file path - -**Personal Skills**: `~/.claude/skills/skill-name/SKILL.md` -**Project Skills**: `.claude/skills/skill-name/SKILL.md` - -Check the file exists: +--- +name: session-logger +description: Log activity for this session +--- -```bash theme={null} -# Personal -ls ~/.claude/skills/my-skill/SKILL.md +Log the following to logs/${CLAUDE_SESSION_ID}.log: -# Project -ls .claude/skills/my-skill/SKILL.md +$ARGUMENTS ``` -### Check YAML syntax - -Invalid YAML prevents the Skill from loading. Verify the frontmatter: - -```bash theme={null} -cat SKILL.md | head -n 10 -``` - -Ensure: - -* Opening `---` on line 1 -* Closing `---` before Markdown content -* Valid YAML syntax (no tabs, correct indentation) - -### View errors - -Run Claude Code with debug mode to see Skill loading errors: - -```bash theme={null} -claude --debug -``` +See the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance including validation rules. -## Share Skills with your team +### Update or delete a Skill -**Recommended approach**: Distribute Skills through [plugins](/en/plugins). +To update a Skill, edit its `SKILL.md` file directly. To remove a Skill, delete its directory. Changes take effect immediately. -To share Skills via plugin: +### Add supporting files with progressive disclosure -1. Create a plugin with Skills in the `skills/` directory -2. Add the plugin to a marketplace -3. Team members install the plugin +Skills share Claude's context window with conversation history, other Skills, and your request. To keep context focused, use **progressive disclosure**: put essential information in `SKILL.md` and detailed reference material in separate files that Claude reads only when needed. -For complete instructions, see [Add Skills to your plugin](/en/plugins#add-skills-to-your-plugin). +This approach lets you bundle comprehensive documentation, examples, and scripts without consuming context upfront. Claude loads additional files only when the task requires them. -You can also share Skills directly through project repositories: +Keep `SKILL.md` under 500 lines for optimal performance. If your content exceeds this, split detailed reference material into separate files. -### Step 1: Add Skill to your project +#### Example: multi-file Skill structure -Create a project Skill: +Claude discovers supporting files through links in your `SKILL.md`. The following example shows a Skill with detailed documentation in separate files and utility scripts that Claude can execute without reading: -```bash theme={null} -mkdir -p .claude/skills/team-skill -# Create SKILL.md ``` - -### Step 2: Commit to git - -```bash theme={null} -git add .claude/skills/ -git commit -m "Add team Skill for PDF processing" -git push +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) ``` -### Step 3: Team members get Skills automatically +The `SKILL.md` file references these supporting files so Claude knows they exist: -When team members pull the latest changes, Skills are immediately available: +````markdown theme={null} +## Overview -```bash theme={null} -git pull -claude # Skills are now available -``` +[Essential instructions here] -## Update a Skill +## Additional resources -Edit SKILL.md directly: +- For complete API details, see [reference.md](reference.md) +- For usage examples, see [examples.md](examples.md) -```bash theme={null} -# Personal Skill -code ~/.claude/skills/my-skill/SKILL.md +## Utility scripts -# Project Skill -code .claude/skills/my-skill/SKILL.md +To validate input files, run the helper script. It checks for required fields and returns any validation errors: +```bash +python scripts/helper.py input.txt ``` +```` -Changes take effect the next time you start Claude Code. If Claude Code is already running, restart it to load the updates. +Keep references one level deep. Link directly from `SKILL.md` to reference files. Deeply nested references (file A links to file B which links to file C) may result in Claude partially reading files. -## Remove a Skill +**Bundle utility scripts for zero-context execution.** Scripts in your Skill directory can be executed without loading their contents into context. Claude runs the script and only the output consumes tokens. This is useful for: -Delete the Skill directory: +* Complex validation logic that would be verbose to describe in prose +* Data processing that's more reliable as tested code than generated code +* Operations that benefit from consistency across uses -```bash theme={null} -# Personal -rm -rf ~/.claude/skills/my-skill +In `SKILL.md`, tell Claude to run the script rather than read it: -# Project -rm -rf .claude/skills/my-skill -git commit -m "Remove unused Skill" +```markdown theme={null} +Run the validation script to check the form: +python scripts/validate_form.py input.pdf ``` -## Best practices - -### Keep Skills focused - -One Skill should address one capability: - -**Focused**: - -* "PDF form filling" -* "Excel data analysis" -* "Git commit messages" +For complete guidance on structuring Skills, see the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices#progressive-disclosure-patterns). -**Too broad**: +### Restrict tool access with allowed-tools -* "Document processing" (split into separate Skills) -* "Data tools" (split by data type or operation) - -### Write clear descriptions - -Help Claude discover when to use Skills by including specific triggers in your description: - -**Clear**: +Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active. You can specify tools as a comma-separated string or a YAML list: ```yaml theme={null} -description: Analyze Excel spreadsheets, create pivot tables, and generate charts. Use when working with Excel files, spreadsheets, or analyzing tabular data in .xlsx format. +--- +name: reading-files-safely +description: Read files without making changes. Use when you need read-only file access. +allowed-tools: Read, Grep, Glob +--- ``` -**Vague**: +Or use YAML-style lists for better readability: ```yaml theme={null} -description: For files -``` - -### Test with your team - -Have teammates use Skills and provide feedback: - -* Does the Skill activate when expected? -* Are the instructions clear? -* Are there missing examples or edge cases? - -### Document Skill versions - -You can document Skill versions in your SKILL.md content to track changes over time. Add a version history section: - -```markdown theme={null} -# My Skill - -## Version History -- v2.0.0 (2025-10-01): Breaking changes to API -- v1.1.0 (2025-09-15): Added new features -- v1.0.0 (2025-09-01): Initial release +--- +name: reading-files-safely +description: Read files without making changes. Use when you need read-only file access. +allowed-tools: + - Read + - Grep + - Glob +--- ``` -This helps team members understand what changed between versions. - -## Troubleshooting +When this Skill is active, Claude can only use the specified tools (Read, Grep, Glob) without needing to ask for permission. This is useful for: -### Claude doesn't use my Skill +* Read-only Skills that shouldn't modify files +* Skills with limited scope: for example, only data analysis, no file writing +* Security-sensitive workflows where you want to restrict capabilities -**Symptom**: You ask a relevant question but Claude doesn't use your Skill. +If `allowed-tools` is omitted, the Skill doesn't restrict tools. Claude uses its standard permission model and may ask you to approve tool usage. -**Check**: Is the description specific enough? + + `allowed-tools` is only supported for Skills in Claude Code. + -Vague descriptions make discovery difficult. Include both what the Skill does and when to use it, with key terms users would mention. +### Run Skills in a forked context -**Too generic**: +Use `context: fork` to run a Skill in an isolated sub-agent context with its own conversation history. This is useful for Skills that perform complex multi-step operations without cluttering the main conversation: ```yaml theme={null} -description: Helps with data +--- +name: code-analysis +description: Analyze code quality and generate detailed reports +context: fork +--- ``` -**Specific**: +### Define hooks for Skills + +Skills can define hooks that run during the Skill's lifecycle. Use the `hooks` field to specify `PreToolUse`, `PostToolUse`, or `Stop` handlers: ```yaml theme={null} -description: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files. +--- +name: secure-operations +description: Perform operations with additional security checks +hooks: + PreToolUse: + - matcher: "Bash" + hooks: + - type: command + command: "./scripts/security-check.sh $TOOL_INPUT" + once: true +--- ``` -**Check**: Is the YAML valid? +The `once: true` option runs the hook only once per session. After the first successful execution, the hook is removed. -Run validation to check for syntax errors: +Hooks defined in a Skill are scoped to that Skill's execution and are automatically cleaned up when the Skill finishes. -```bash theme={null} -# View frontmatter -cat .claude/skills/my-skill/SKILL.md | head -n 15 +See [Hooks](/en/hooks) for the complete hook configuration format. -# Check for common issues -# - Missing opening or closing --- -# - Tabs instead of spaces -# - Unquoted strings with special characters -``` +### Control Skill visibility -**Check**: Is the Skill in the correct location? +Skills can be invoked in three ways: -```bash theme={null} -# Personal Skills -ls ~/.claude/skills/*/SKILL.md +1. **Manual invocation**: You type `/skill-name` in the prompt +2. **Programmatic invocation**: Claude calls it via the [`Skill` tool](/en/slash-commands#skill-tool) +3. **Automatic discovery**: Claude reads the Skill's description and loads it when relevant to the conversation -# Project Skills -ls .claude/skills/*/SKILL.md -``` +The `user-invocable` field controls only manual invocation. When set to `false`, the Skill is hidden from the slash command menu but Claude can still invoke it programmatically or discover it automatically. -### Skill has errors +To block programmatic invocation via the `Skill` tool, use `disable-model-invocation: true` instead. -**Symptom**: The Skill loads but doesn't work correctly. +#### When to use each setting -**Check**: Are dependencies available? +| Setting | Slash menu | `Skill` tool | Auto-discovery | Use case | +| :------------------------------- | :--------- | :----------- | :------------- | :-------------------------------------------------------------- | +| `user-invocable: true` (default) | Visible | Allowed | Yes | Skills you want users to invoke directly | +| `user-invocable: false` | Hidden | Allowed | Yes | Skills that Claude can use but users shouldn't invoke manually | +| `disable-model-invocation: true` | Visible | Blocked | Yes | Skills you want users to invoke but not Claude programmatically | -Claude will automatically install required dependencies (or ask for permission to install them) when it needs them. +#### Example: model-only Skill -**Check**: Do scripts have execute permissions? +Set `user-invocable: false` to hide a Skill from the slash menu while still allowing Claude to invoke it programmatically: -```bash theme={null} -chmod +x .claude/skills/my-skill/scripts/*.py +```yaml theme={null} +--- +name: internal-review-standards +description: Apply internal code review standards when reviewing pull requests +user-invocable: false +--- ``` -**Check**: Are file paths correct? +With this setting, users won't see the Skill in the `/` menu, but Claude can still invoke it via the `Skill` tool or discover it automatically based on context. -Use forward slashes (Unix style) in all paths: +### Skills and subagents -**Correct**: `scripts/helper.py` -**Wrong**: `scripts\helper.py` (Windows style) +There are two ways Skills and subagents can work together: -### Multiple Skills conflict +#### Give a subagent access to Skills -**Symptom**: Claude uses the wrong Skill or seems confused between similar Skills. +[Subagents](/en/sub-agents) do not automatically inherit Skills from the main conversation. To give a custom subagent access to specific Skills, list them in the subagent's `skills` field: -**Be specific in descriptions**: Help Claude choose the right Skill by using distinct trigger terms in your descriptions. +```yaml theme={null} +# .claude/agents/code-reviewer.md +--- +name: code-reviewer +description: Review code for quality and best practices +skills: pr-review, security-check +--- +``` -Instead of: +The full content of each listed Skill is injected into the subagent's context at startup, not just made available for invocation. If the `skills` field is omitted, no Skills are loaded for that subagent. -```yaml theme={null} -# Skill 1 -description: For data analysis + + Built-in agents (Explore, Plan, general-purpose) do not have access to your Skills. Only custom subagents you define in `.claude/agents/` with an explicit `skills` field can use Skills. + -# Skill 2 -description: For analyzing data -``` +#### Run a Skill in a subagent context -Use: +Use `context: fork` and `agent` to run a Skill in a forked subagent with its own separate context. See [Run Skills in a forked context](#run-skills-in-a-forked-context) for details. -```yaml theme={null} -# Skill 1 -description: Analyze sales data in Excel files and CRM exports. Use for sales reports, pipeline analysis, and revenue tracking. +### Distribute Skills -# Skill 2 -description: Analyze log files and system metrics data. Use for performance monitoring, debugging, and system diagnostics. -``` +You can share Skills in several ways: + +* **Project Skills**: Commit `.claude/skills/` to version control. Anyone who clones the repository gets the Skills. +* **Plugins**: To share Skills across multiple repositories, create a `skills/` directory in your [plugin](/en/plugins) with Skill folders containing `SKILL.md` files. Distribute through a [plugin marketplace](/en/plugin-marketplaces). +* **Managed**: Administrators can deploy Skills organization-wide through [managed settings](/en/iam#managed-settings). See [Where Skills live](#where-skills-live) for managed Skill paths. ## Examples +These examples show common Skill patterns, from minimal single-file Skills to multi-file Skills with supporting documentation and scripts. + ### Simple Skill (single file) +A minimal Skill needs only a `SKILL.md` file with frontmatter and instructions. This example helps Claude generate commit messages by examining staged changes: + ``` commit-helper/ └── SKILL.md @@ -506,56 +435,27 @@ description: Generates clear commit messages from git diffs. Use when writing co - Explain what and why, not how ``` -### Skill with tool permissions +### Use multiple files -``` -code-reviewer/ -└── SKILL.md -``` - -```yaml theme={null} ---- -name: code-reviewer -description: Review code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality. -allowed-tools: Read, Grep, Glob ---- - -# Code Reviewer - -## Review checklist - -1. Code organization and structure -2. Error handling -3. Performance considerations -4. Security concerns -5. Test coverage - -## Instructions - -1. Read the target files using Read tool -2. Search for patterns using Grep -3. Find related files using Glob -4. Provide detailed feedback on code quality -``` - -### Multi-file Skill +For complex Skills, use progressive disclosure to keep the main `SKILL.md` focused while providing detailed documentation in supporting files. This PDF processing Skill includes reference docs, utility scripts, and uses `allowed-tools` to restrict Claude to specific tools: ``` pdf-processing/ -├── SKILL.md -├── FORMS.md -├── REFERENCE.md +├── SKILL.md # Overview and quick start +├── FORMS.md # Form field mappings and filling instructions +├── REFERENCE.md # API details for pypdf and pdfplumber └── scripts/ - ├── fill_form.py - └── validate.py + ├── fill_form.py # Utility to populate form fields + └── validate.py # Checks PDFs for required fields ``` -**SKILL.md**: +**`SKILL.md`**: ````yaml theme={null} --- name: pdf-processing description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages. +allowed-tools: Read, Bash(python:*) --- # PDF Processing @@ -581,10 +481,89 @@ pip install pypdf pdfplumber ```` - List required packages in the description. Packages must be installed in your environment before Claude can use them. + If your Skill requires external packages, list them in the description. Packages must be installed in your environment before Claude can use them. -Claude loads additional files only when needed. +## Troubleshooting + +### View and test Skills + +To see which Skills Claude has access to, ask Claude a question like "What Skills are available?" Claude loads all available Skill names and descriptions into the context window when a conversation starts, so it can list the Skills it currently has access to. + +To test a specific Skill, ask Claude to do a task that matches the Skill's description. For example, if your Skill has the description "Reviews pull requests for code quality", ask Claude to "Review the changes in my current branch." Claude automatically uses the Skill when the request matches its description. + +### Skill not triggering + +The description field is how Claude decides whether to use your Skill. Vague descriptions like "Helps with documents" don't give Claude enough information to match your Skill to relevant requests. + +A good description answers two questions: + +1. **What does this Skill do?** List the specific capabilities. +2. **When should Claude use it?** Include trigger terms users would mention. + +```yaml theme={null} +description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. +``` + +This description works because it names specific actions (extract, fill, merge) and includes keywords users would say (PDF, forms, document extraction). + +### Skill doesn't load + +**Check the file path.** Skills must be in the correct directory with the exact filename `SKILL.md` (case-sensitive): + +| Type | Path | +| :--------- | :---------------------------------------------------------------------- | +| Personal | `~/.claude/skills/my-skill/SKILL.md` | +| Project | `.claude/skills/my-skill/SKILL.md` | +| Enterprise | See [Where Skills live](#where-skills-live) for platform-specific paths | +| Plugin | `skills/my-skill/SKILL.md` inside the plugin directory | + +**Check the YAML syntax.** Invalid YAML in the frontmatter prevents the Skill from loading. The frontmatter must start with `---` on line 1 (no blank lines before it), end with `---` before the Markdown content, and use spaces for indentation (not tabs). + +**Run debug mode.** Use `claude --debug` to see Skill loading errors. + +### Skill has errors + +**Check dependencies are installed.** If your Skill uses external packages, they must be installed in your environment before Claude can use them. + +**Check script permissions.** Scripts need execute permissions: `chmod +x scripts/*.py` + +**Check file paths.** Use forward slashes (Unix style) in all paths. Use `scripts/helper.py`, not `scripts\helper.py`. + +### Multiple Skills conflict + +If Claude uses the wrong Skill or seems confused between similar Skills, the descriptions are probably too similar. Make each description distinct by using specific trigger terms. + +For example, instead of two Skills with "data analysis" in both descriptions, differentiate them: one for "sales data in Excel files and CRM exports" and another for "log files and system metrics". The more specific your trigger terms, the easier it is for Claude to match the right Skill to your request. + +### Plugin Skills not appearing + +**Symptom**: You installed a plugin from a marketplace, but its Skills don't appear when you ask Claude "What Skills are available?" + +**Solution**: Clear the plugin cache and reinstall: + +```bash theme={null} +rm -rf ~/.claude/plugins/cache +``` + +Then restart Claude Code and reinstall the plugin: + +```shell theme={null} +/plugin install plugin-name@marketplace-name +``` + +This forces Claude Code to re-download and re-register the plugin's Skills. + +**If Skills still don't appear**, verify the plugin's directory structure is correct. Skills must be in a `skills/` directory at the plugin root: + +``` +my-plugin/ +├── .claude-plugin/ +│ └── plugin.json +└── skills/ + └── my-skill/ + └── SKILL.md +``` ## Next steps diff --git a/skills/working-with-claude-code/references/slash-commands.md b/skills/working-with-claude-code/references/slash-commands.md index f8c1e48..d87cf7e 100644 --- a/skills/working-with-claude-code/references/slash-commands.md +++ b/skills/working-with-claude-code/references/slash-commands.md @@ -4,53 +4,62 @@ ## 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 | +| 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). Type to search and filter settings | +| `/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` | Run diagnostics to check installation health, detect configuration issues (invalid settings, MCP errors, keybinding problems), and identify context usage warnings (large CLAUDE.md files, high MCP token usage) | +| `/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) | +| `/plan` | Enter plan mode directly from the prompt | +| `/plugin` | Manage Claude Code plugins | +| `/pr-comments` | View pull request comments | +| `/privacy-settings` | View and update your privacy settings | +| `/release-notes` | View release notes | +| `/rename ` | Rename the current session for easier identification | +| `/remote-env` | Configure remote session environment (claude.ai subscribers) | +| `/resume [session]` | Resume a conversation by ID or name, or open the session picker | +| `/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. Press `r` to cycle date ranges (Last 7 days, Last 30 days, All time) | +| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity | +| `/statusline` | Set up Claude Code's status line UI | +| `/teleport` | Resume a remote session from claude.ai by session ID, or open a picker (claude.ai subscribers) | +| `/terminal-setup` | Install Shift+Enter key binding for newlines (VS Code, Alacritty, Zed, Warp) | +| `/theme` | Change the color theme | +| `/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. + + Slash command autocomplete works anywhere in your input, not just at the beginning. Type `/` at any position to see available commands. + + ### Syntax ``` @@ -197,9 +206,12 @@ Command files support frontmatter, useful for specifying metadata about the comm | :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------- | | `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 | +| `context` | Set to `fork` to run the command in a forked sub-agent context with its own conversation history. | Inline (no fork) | +| `agent` | Specify which [agent type](/en/sub-agents#built-in-subagents) to use when `context: fork` is set. Only applicable when combined with `context: fork`. | `general-purpose` | | `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 | +| `disable-model-invocation` | Whether to prevent the `Skill` tool from calling this command | false | +| `hooks` | Define hooks scoped to this command's execution. See [Define hooks for commands](#define-hooks-for-commands). | None | For example: @@ -226,6 +238,31 @@ Review PR #$1 with priority $2 and assign to $3. Focus on security, performance, and code style. ``` +#### Define hooks for commands + +Slash commands can define hooks that run during the command's execution. Use the `hooks` field to specify `PreToolUse`, `PostToolUse`, or `Stop` handlers: + +```markdown theme={null} +--- +description: Deploy to staging with validation +hooks: + PreToolUse: + - matcher: "Bash" + hooks: + - type: command + command: "./scripts/validate-deploy.sh" + once: true +--- + +Deploy the current branch to staging environment. +``` + +The `once: true` option runs the hook only once per session. After the first successful execution, the hook is removed. + +Hooks defined in a command are scoped to that command's execution and are automatically cleaned up when the command finishes. + +See [Hooks](/en/hooks) for the complete hook configuration format. + ## 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). @@ -332,78 +369,85 @@ Use the `/mcp` command to: ### 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: +To approve all tools from an MCP server, use either the server name alone or wildcard syntax: * `mcp__github` (approves all GitHub tools) +* `mcp__github__*` (wildcard syntax, also approves all GitHub tools) To approve specific tools, list each one explicitly: * `mcp__github__get_issue` * `mcp__github__list_issues` -## `SlashCommand` tool +See [MCP permission rules](/en/iam#tool-specific-permission-rules) for more details. -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. +## `Skill` tool -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: + + In earlier versions of Claude Code, slash command invocation was provided by a separate `SlashCommand` tool. This has been merged into the `Skill` tool. + -``` -> Run /write-unit-test when you are about to start writing tests. -``` +The `Skill` tool allows Claude to programmatically invoke both [custom slash commands](/en/slash-commands#custom-slash-commands) and [Agent Skills](/en/skills) during a conversation. This gives Claude the ability to use these capabilities on your behalf when appropriate. + +### What the `Skill` tool can invoke + +The `Skill` tool provides access to: -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. +| Type | Location | Requirements | +| :-------------------- | :------------------------------------------- | :--------------------------------------------- | +| Custom slash commands | `.claude/commands/` or `~/.claude/commands/` | Must have `description` frontmatter | +| Agent Skills | `.claude/skills/` or `~/.claude/skills/` | Must not have `disable-model-invocation: true` | -### `SlashCommand` tool supported commands +Built-in commands like `/compact` and `/init` are *not* available through this tool. -`SlashCommand` tool only supports custom slash commands that: +### Encourage Claude to use specific commands + +To encourage Claude to use the `Skill` tool, reference the command by name, including the slash, in your prompts or `CLAUDE.md` file: + +``` +> Run /write-unit-test when you are about to start writing tests. +``` -* 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. +This tool puts each available command's metadata into context up to the character budget limit. Use `/context` to monitor token usage. -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. +To see which commands and Skills are available to the `Skill` tool, run `claude --debug` and trigger a query. -### Disable `SlashCommand` tool +### Disable the `Skill` tool -To prevent Claude from executing any slash commands via the tool: +To prevent Claude from programmatically invoking any commands or Skills: ```bash theme={null} /permissions -# Add to deny rules: SlashCommand +# Add to deny rules: Skill ``` -This also removes the SlashCommand tool and command descriptions from context. +This removes the `Skill` tool and all command/Skill descriptions from context. -### Disable specific commands only +### Disable specific commands or Skills -To prevent a specific slash command from becoming available, add -`disable-model-invocation: true` to the slash command's frontmatter. +To prevent a specific command or Skill from being invoked programmatically via the `Skill` tool, add `disable-model-invocation: true` to its frontmatter. This also removes the item's metadata from context. -This also removes the command's metadata from context. + + The `user-invocable` field in Skills only controls menu visibility, not `Skill` tool access. Use `disable-model-invocation: true` to block programmatic invocation. See [Control Skill visibility](/en/skills#control-skill-visibility) for details. + -### `SlashCommand` permission rules +### `Skill` 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) +* **Exact match**: `Skill(commit)` (allows only `commit` with no arguments) +* **Prefix match**: `Skill(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 `Skill` tool includes a character budget to limit context usage. This prevents token overflow when many commands and Skills are available. -The budget includes each custom slash command's name, arguments, and description. +The budget includes each item's name, arguments, and description. * **Default limit**: 15,000 characters -* **Custom limit**: Set via `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable +* **Custom limit**: Set via `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable. The name is retained for backwards compatibility. -When the character budget is exceeded, Claude sees only a subset of the available commands. In `/context`, a warning shows "M of N commands". +When the budget is exceeded, Claude sees only a subset of available items. In `/context`, a warning shows how many are included. ## Skills vs slash commands diff --git a/skills/working-with-claude-code/references/statusline.md b/skills/working-with-claude-code/references/statusline.md index 1011f11..73d6408 100644 --- a/skills/working-with-claude-code/references/statusline.md +++ b/skills/working-with-claude-code/references/statusline.md @@ -62,7 +62,15 @@ Your status line command receives structured data via stdin in JSON format: "context_window": { "total_input_tokens": 15234, "total_output_tokens": 4521, - "context_window_size": 200000 + "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 + } } } ``` @@ -198,23 +206,51 @@ echo "[$MODEL] 📁 ${DIR##*/}" ### Context Window Usage -Display the percentage of context window consumed: +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) -INPUT_TOKENS=$(echo "$input" | jq -r '.context_window.total_input_tokens') -OUTPUT_TOKENS=$(echo "$input" | jq -r '.context_window.total_output_tokens') -CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size') MODEL=$(echo "$input" | jq -r '.model.display_name') - -TOTAL_TOKENS=$((INPUT_TOKENS + OUTPUT_TOKENS)) -PERCENT_USED=$((TOTAL_TOKENS * 100 / CONTEXT_SIZE)) +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 diff --git a/skills/working-with-claude-code/references/sub-agents.md b/skills/working-with-claude-code/references/sub-agents.md index 4368a6e..6939798 100644 --- a/skills/working-with-claude-code/references/sub-agents.md +++ b/skills/working-with-claude-code/references/sub-agents.md @@ -1,105 +1,159 @@ -# Subagents +# Create custom subagents > Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management. -Custom subagents in Claude Code are specialized AI assistants that can be invoked to handle specific types of tasks. They enable more efficient problem-solving by providing task-specific configurations with customized system prompts, tools and a separate context window. +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. -## What are subagents? +Subagents help you: -Subagents are pre-configured AI personalities that Claude Code can delegate tasks to. Each subagent: +* **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 -* Has a specific purpose and expertise area -* Uses its own context window separate from the main conversation -* Can be configured with specific tools it's allowed to use -* Includes a custom system prompt that guides its behavior +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. -When Claude Code encounters a task that matches a subagent's expertise, it can delegate that task to the specialized subagent, which works independently and returns results. +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). -## Key benefits +## 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. + - - - Each subagent operates in its own context, preventing pollution of the main conversation and keeping it focused on high-level objectives. - + + A capable agent for complex, multi-step tasks that require both exploration and action. - - Subagents can be fine-tuned with detailed instructions for specific domains, leading to higher success rates on designated tasks. - + * **Model**: Inherits from main conversation + * **Tools**: All tools + * **Purpose**: Complex research, multi-step operations, code modifications - - Once created, you can use subagents across different projects and share them with your team for consistent workflows. - + Claude delegates to general-purpose when the task requires both exploration and modification, complex reasoning to interpret results, or multiple dependent steps. + - - Each subagent can have different tool access levels, allowing you to limit powerful tools to specific subagent types. - - + + Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically, so you don't need to use them directly. -## Quick start + | 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 | + + -To create your first subagent: +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` slash 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. - Run the following command: + In Claude Code, run: ``` /agents ``` - - Choose whether to create a project-level or user-level subagent + + 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. - - * **Recommended**: generate with Claude first, then customize to make it yours - * Describe your subagent in detail, including when Claude should use it - * Select the tools you want to grant access to, or leave this blank to inherit all tools - * The interface shows all available tools - * If you're generating with Claude, you can also edit the system prompt in your own editor by pressing `e` + + Choose which model the subagent uses. For this example agent, select **Sonnet**, which balances capability and speed for analyzing code patterns. - - Your subagent is now available. Claude uses it automatically when appropriate, or you can invoke it explicitly: + + 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-reviewer subagent to check my recent changes + 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. -## Subagent configuration +You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements. -### File locations +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. -Subagents are stored as Markdown files with YAML frontmatter in two possible locations: +## Configure subagents -| Type | Location | Scope | Priority | -| :-------------------- | :------------------ | :---------------------------- | :------- | -| **Project subagents** | `.claude/agents/` | Available in current project | Highest | -| **User subagents** | `~/.claude/agents/` | Available across all projects | Lower | +### Use the /agents command -When subagent names conflict, project-level subagents take precedence over user-level subagents. +The `/agents` command provides an interactive interface for managing subagents. Run `/agents` to: -### Plugin agents +* 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 -[Plugins](/en/plugins) can provide custom subagents that integrate seamlessly with Claude Code. Plugin agents work identically to user-defined agents and appear in the `/agents` interface. +This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly. -**Plugin agent locations**: plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest). +### Choose the subagent scope -**Using plugin agents**: +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. -* Plugin agents appear in `/agents` alongside your custom agents -* Can be invoked explicitly: "Use the code-reviewer agent from the security-plugin" -* Can be invoked automatically by Claude when appropriate -* Can be managed (viewed, inspected) through `/agents` interface +| 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) | -See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin agents. +**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. -### CLI-based configuration +**User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects. -You can also define subagents dynamically using the `--agents` CLI flag, which accepts a JSON object: +**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 '{ @@ -112,258 +166,373 @@ claude --agents '{ }' ``` -**Priority**: CLI-defined subagents have lower priority than project-level subagents but higher priority than user-level subagents. +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. -**Use case**: This approach is useful for: +**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. -* Quick testing of subagent configurations -* Session-specific subagents that don't need to be saved -* Automation scripts that need custom subagents -* Sharing subagent definitions in documentation or scripts +### Write subagent files -For detailed information about the JSON format and all available options, see the [CLI reference documentation](/en/cli-reference#agents-flag-format). +Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown: -### File format - -Each subagent is defined in a Markdown file with this structure: + + 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: your-sub-agent-name -description: Description of when this subagent should be invoked -tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted -model: sonnet # Optional - specify model alias or 'inherit' -permissionMode: default # Optional - permission mode for the subagent -skills: skill1, skill2 # Optional - skills to auto-load +name: code-reviewer +description: Reviews code for quality and best practices +tools: Read, Glob, Grep +model: sonnet --- -Your subagent's system prompt goes here. This can be multiple paragraphs -and should clearly define the subagent's role, capabilities, and approach -to solving problems. - -Include specific instructions, best practices, and any constraints -the subagent should follow. +You are a code reviewer. When invoked, analyze the code and provide +specific, actionable feedback on quality, security, and best practices. ``` -#### Configuration fields +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 -| Field | Required | Description | -| :--------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `name` | Yes | Unique identifier using lowercase letters and hyphens | -| `description` | Yes | Natural language description of the subagent's purpose | -| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread | -| `model` | No | Model to use for this subagent. Can be a model alias (`sonnet`, `opus`, `haiku`) or `'inherit'` to use the main conversation's model. If omitted, defaults to the [configured subagent model](/en/model-config) | -| `permissionMode` | No | Permission mode for the subagent. Valid values: `default`, `acceptEdits`, `bypassPermissions`, `plan`, `ignore`. Controls how the subagent handles permission requests | -| `skills` | No | Comma-separated list of skill names to auto-load when the subagent starts. Skills are loaded into the subagent's context automatically | +The following fields can be used in the YAML frontmatter. Only `name` and `description` are required. -### Model selection +| 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 `sonnet` | +| `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 | -The `model` field allows you to control which [AI model](/en/model-config) the subagent uses: +### 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 (useful for consistency) +* **inherit**: Use the same model as the main conversation (useful for consistency) * **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`) - - Using `'inherit'` is particularly useful when you want your subagents to adapt to the model choice of the main conversation, ensuring consistent capabilities and response style throughout your session. - +### Control subagent capabilities -### Available tools +You can control what subagents can do through tool access, permission modes, and conditional rules. -Subagents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/settings#tools-available-to-claude) for a complete list of available tools. +#### Available tools - - **Recommended:** Use the `/agents` command to modify tool access - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the ones you need. - +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. -You have two options for configuring tools: +| 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) | -* **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools -* **Specify individual tools** as a comma-separated list for more granular control (can be edited manually or via `/agents`) + + Use `bypassPermissions` with caution. It skips all permission checks, allowing the subagent to execute any operation without approval. + -**MCP Tools**: Subagents can access MCP tools from configured MCP servers. When the `tools` field is omitted, subagents inherit all MCP tools available to the main thread. +If the parent uses `bypassPermissions`, this takes precedence and cannot be overridden. -## Managing subagents +#### Conditional rules with hooks -### Using the /agents command (Recommended) +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. -The `/agents` command provides a comprehensive interface for subagent management: +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" +--- ``` -/agents + +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) 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 ``` -This opens an interactive menu where you can: +See [Hook input](/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/en/hooks#exit-codes) for how exit codes affect behavior. -* View all available subagents (built-in, user, and project) -* Create new subagents with guided setup -* Edit existing custom subagents, including their tool access -* Delete custom subagents -* See which subagents are active when duplicates exist -* **Manage tool permissions** with a complete list of available tools +#### Disable specific subagents -### Direct file management +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. -You can also manage subagents by working directly with their files: +```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} -# Create a project subagent -mkdir -p .claude/agents -echo '--- -name: test-runner -description: Use proactively to run tests and fix failures ---- +claude --disallowedTools "Task(Explore)" +``` + +See [IAM documentation](/en/iam#tool-specific-permission-rules) for more details on permission rules. -You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent.' > .claude/agents/test-runner.md +### Define hooks for subagents -# Create a user subagent -mkdir -p ~/.claude/agents -# ... create subagent file +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. + +| 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 | + +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" +--- ``` - - Subagents created by manually adding files will be loaded the next time you start a Claude Code session. To create and use a subagent immediately without restarting, use the `/agents` command instead. - +`Stop` hooks in frontmatter are automatically converted to `SubagentStop` events. -## Using subagents effectively +#### Project-level hooks for subagent events -### Automatic delegation +Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session. Use the `matcher` field to target specific agent types by name. -Claude Code proactively delegates tasks based on: +| Event | Matcher input | When it fires | +| :-------------- | :-------------- | :------------------------------- | +| `SubagentStart` | Agent type name | When a subagent begins execution | +| `SubagentStop` | Agent type name | When a subagent completes | -* The task description in your request -* The `description` field in subagent configurations -* Current context and available tools +This example runs setup and cleanup scripts only when the `db-agent` subagent starts and stops: - - To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field. - +```json theme={null} +{ + "hooks": { + "SubagentStart": [ + { + "matcher": "db-agent", + "hooks": [ + { "type": "command", "command": "./scripts/setup-db-connection.sh" } + ] + } + ], + "SubagentStop": [ + { + "matcher": "db-agent", + "hooks": [ + { "type": "command", "command": "./scripts/cleanup-db-connection.sh" } + ] + } + ] + } +} +``` -### Explicit invocation +See [Hooks](/en/hooks) for the complete hook configuration format. -Request a specific subagent by mentioning it in your command: +## 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 -> Ask the debugger subagent to investigate this error +Use the test-runner subagent to fix failing tests +Have the code-reviewer subagent look at my recent changes ``` -## Built-in subagents +### Run subagents in foreground or background -Claude Code includes built-in subagents that are available out of the box: +Subagents can run in the foreground (blocking) or background (concurrent): -### General-purpose subagent +* **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. They inherit the parent's permissions and auto-deny anything not pre-approved. If a background subagent needs a permission it doesn't have or needs to ask clarifying questions, that tool call fails but the subagent continues. MCP tools are not available in background subagents. -The general-purpose subagent is a capable agent for complex, multi-step tasks that require both exploration and action. Unlike the Explore subagent, it can modify files and execute a wider range of operations. +If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts. -**Key characteristics:** +Claude decides whether to run subagents in the foreground or background based on the task. You can also: -* **Model**: Uses Sonnet for more capable reasoning -* **Tools**: Has access to all tools -* **Mode**: Can read and write files, execute commands, make changes -* **Purpose**: Complex research tasks, multi-step operations, code modifications +* Ask Claude to "run this in the background" +* Press **Ctrl+B** to background a running task -**When Claude uses it:** +To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/settings#environment-variables). -Claude delegates to the general-purpose subagent when: +### Common patterns -* The task requires both exploration and modification -* Complex reasoning is needed to interpret search results -* Multiple strategies may be needed if initial searches fail -* The task has multiple steps that depend on each other +#### Isolate high-volume operations -**Example scenario:** +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. ``` -User: Find all the places where we handle authentication and update them to use the new token format - -Claude: [Invokes general-purpose subagent] -[Agent searches for auth-related code across codebase] -[Agent reads and analyzes multiple files] -[Agent makes necessary edits] -[Returns detailed writeup of changes made] +Use a subagent to run the test suite and report only the failing tests with their error messages ``` -### Plan subagent +#### Run parallel research -The Plan subagent is a specialized built-in agent designed for use during plan mode. When Claude is operating in plan mode (non-execution mode), it uses the Plan subagent to conduct research and gather information about your codebase before presenting a plan. +For independent investigations, spawn multiple subagents to work simultaneously: -**Key characteristics:** +``` +Research the authentication, database, and API modules in parallel using separate subagents +``` -* **Model**: Uses Sonnet for more capable analysis -* **Tools**: Has access to Read, Glob, Grep, and Bash tools for codebase exploration -* **Purpose**: Searches files, analyzes code structure, and gathers context -* **Automatic invocation**: Claude automatically uses this agent when in plan mode and needs to research the codebase +Each subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths don't depend on each other. -**How it works:** -When you're in plan mode and Claude needs to understand your codebase to create a plan, it delegates research tasks to the Plan subagent. This prevents infinite nesting of agents (subagents cannot spawn other subagents) while still allowing Claude to gather the necessary context. + + When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context. + -**Example scenario:** +#### Chain subagents -``` -User: [In plan mode] Help me refactor the authentication module +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. -Claude: Let me research your authentication implementation first... -[Internally invokes Plan subagent to explore auth-related files] -[Plan subagent searches codebase and returns findings] -Claude: Based on my research, here's my proposed plan... +``` +Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them ``` - - The Plan subagent is only used in plan mode. In normal execution mode, Claude uses the general-purpose agent or other custom subagents you've created. - +### Choose between subagents and main conversation -### Explore subagent +Use the **main conversation** when: -The Explore subagent is a fast, lightweight agent optimized for searching and analyzing codebases. It operates in strict read-only mode and is designed for rapid file discovery and code exploration. +* 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 -**Key characteristics:** +Use **subagents** when: -* **Model**: Uses Haiku for fast, low-latency searches -* **Mode**: Strictly read-only - cannot create, modify, or delete files -* **Tools available**: - * Glob - File pattern matching - * Grep - Content searching with regular expressions - * Read - Reading file contents - * Bash - Read-only commands only (ls, git status, git log, git diff, find, cat, head, tail) +* 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 -**When Claude uses it:** +Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context. -Claude will delegate to the Explore subagent when it needs to search or understand a codebase but doesn't need to make changes. This is more efficient than the main agent running multiple search commands directly, as content found during the exploration process doesn't bloat the main conversation. + + Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation. + -**Thoroughness levels:** +### Manage subagent context -When invoking the Explore subagent, Claude specifies a thoroughness level: +#### Resume subagents -* **Quick** - Fast searches with minimal exploration. Good for targeted lookups. -* **Medium** - Moderate exploration. Balances speed and thoroughness. -* **Very thorough** - Comprehensive analysis across multiple locations and naming conventions. Used when the target might be in unexpected places. +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. -**Example scenarios:** +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. -``` -User: Where are errors from the client handled? +When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work: -Claude: [Invokes Explore subagent with "medium" thoroughness] -[Explore uses Grep to search for error handling patterns] -[Explore uses Read to examine promising files] -[Returns findings with absolute file paths] -Claude: Client errors are handled in src/services/process.ts:712... ``` +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] ``` -User: What's the codebase structure? -Claude: [Invokes Explore subagent with "quick" thoroughness] -[Explore uses Glob and ls to map directory structure] -[Returns overview of key directories and their purposes] +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`. + +For programmatic usage, see [Subagents in the Agent SDK](/en/agent-sdk/subagents). + +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 @@ -399,6 +568,8 @@ 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 @@ -434,6 +605,8 @@ 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 @@ -467,102 +640,75 @@ For each analysis: Always ensure queries are efficient and cost-effective. ``` -## Best practices - -* **Start with Claude-generated agents**: We highly recommend generating your initial subagent with Claude and then iterating on it to make it personally yours. This approach gives you the best results - a solid foundation that you can customize to your specific needs. - -* **Design focused subagents**: Create subagents with single, clear responsibilities rather than trying to make one subagent do everything. This improves performance and makes subagents more predictable. +### Database query validator -* **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the subagent will perform. +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. -* **Limit tool access**: Only grant tools that are necessary for the subagent's purpose. This improves security and helps the subagent focus on relevant actions. - -* **Version control**: Check project subagents into version control so your team can benefit from and improve them collaboratively. - -## Advanced usage +```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" +--- -### Chaining subagents +You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data. -For complex workflows, you can chain multiple subagents: +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. ``` -> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them -``` - -### Dynamic subagent selection - -Claude Code intelligently selects subagents based on context. Make your `description` fields specific and action-oriented for best results. - -### Resumable subagents -Subagents can be resumed to continue previous conversations, which is particularly useful for long-running research or analysis tasks that need to be continued across multiple invocations. +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) to block execution and returns an error message to Claude via stderr. -**How it works:** +Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration: -* Each subagent execution is assigned a unique `agentId` -* The agent's conversation is stored in a separate transcript file: `agent-{agentId}.jsonl` -* You can resume a previous agent by providing its `agentId` via the `resume` parameter -* When resumed, the agent continues with full context from its previous conversation +```bash theme={null} +#!/bin/bash +# Blocks SQL write operations, allows SELECT queries -**Example workflow:** +# Read JSON input from stdin +INPUT=$(cat) -Initial invocation: +# Extract the command field from tool_input using jq +COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty') -``` -> Use the code-analyzer agent to start reviewing the authentication module +if [ -z "$COMMAND" ]; then + exit 0 +fi -[Agent completes initial analysis and returns agentId: "abc123"] -``` - -Resume the agent: +# 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 ``` -> Resume agent abc123 and now analyze the authorization logic as well - -[Agent continues with full context from previous conversation] -``` - -**Use cases:** - -* **Long-running research**: Break down large codebase analysis into multiple sessions -* **Iterative refinement**: Continue refining a subagent's work without losing context -* **Multi-step workflows**: Have a subagent work on related tasks sequentially while maintaining context - -**Technical details:** -* Agent transcripts are stored in your project directory -* Recording is disabled during resume to avoid duplicating messages -* Both synchronous and asynchronous agents can be resumed -* The `resume` parameter accepts the agent ID from a previous execution +Make the script executable: -**Programmatic usage:** - -If you're using the Agent SDK or interacting with the AgentTool directly, you can pass the `resume` parameter: - -```typescript theme={null} -{ - "description": "Continue analysis", - "prompt": "Now examine the error handling patterns", - "subagent_type": "code-analyzer", - "resume": "abc123" // Agent ID from previous execution -} +```bash theme={null} +chmod +x ./scripts/validate-readonly-query.sh ``` - - Keep track of agent IDs for tasks you may want to resume later. Claude Code displays the agent ID when a subagent completes its work. - - -## Performance considerations +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-codes) for details on exit codes and [Hook input](/en/hooks#pretooluse-input) for the complete input schema. -* **Context efficiency**: Agents help preserve main context, enabling longer overall sessions -* **Latency**: Subagents start off with a clean slate each time they are invoked and may add latency as they gather context that they require to do their job effectively. +## Next steps -## Related documentation +Now that you understand subagents, explore these related features: -* [Plugins](/en/plugins) - Extend Claude Code with custom agents through plugins -* [Slash commands](/en/slash-commands) - Learn about other built-in commands -* [Settings](/en/settings) - Configure Claude Code behavior -* [Hooks](/en/hooks) - Automate workflows with event handlers +* [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 --- diff --git a/skills/working-with-claude-code/references/terminal-config.md b/skills/working-with-claude-code/references/terminal-config.md index 8abe007..d04a483 100644 --- a/skills/working-with-claude-code/references/terminal-config.md +++ b/skills/working-with-claude-code/references/terminal-config.md @@ -13,13 +13,18 @@ For additional customization of the Claude Code interface itself, you can config You have several options for entering line breaks into Claude Code: * **Quick escape**: Type `\` followed by Enter to create a newline -* **Keyboard shortcut**: Set up a keybinding to insert 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 (VS Code or iTerm2): +**Set up Shift+Enter for other terminals** -Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter. +Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter for VS Code, Alacritty, Zed, and Warp. -#### Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app): + + 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:** @@ -65,8 +70,14 @@ Claude Code supports a subset of Vim keybindings that can be enabled with `/vim` 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` +* 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. --- diff --git a/skills/working-with-claude-code/references/third-party-integrations.md b/skills/working-with-claude-code/references/third-party-integrations.md index 2f57ebb..a381bd7 100644 --- a/skills/working-with-claude-code/references/third-party-integrations.md +++ b/skills/working-with-claude-code/references/third-party-integrations.md @@ -2,15 +2,26 @@ > Learn how Claude Code can integrate with various third-party services and infrastructure to meet enterprise deployment requirements. -This page provides an overview of available deployment options and helps you choose the right configuration for your organization. +Organizations can deploy Claude Code through Anthropic directly or through a cloud provider. This page helps you choose the right configuration. -## Provider comparison +## 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: - + + @@ -18,9 +29,28 @@ This page provides an overview of available deployment options and helps you cho + + + + + + + + + + + + + + + + + + + @@ -32,10 +62,12 @@ This page provides an overview of available deployment options and helps you cho + + @@ -44,15 +76,26 @@ This page provides an overview of available deployment options and helps you cho - + + + + + + + + + + + - + + @@ -60,191 +103,143 @@ This page provides an overview of available deployment options and helps you cho
FeatureAnthropicClaude for Teams/EnterpriseAnthropic Console Amazon Bedrock Google Vertex AI Microsoft Foundry
Best forMost organizations (recommended)Individual developersAWS-native deploymentsGCP-native deploymentsAzure-native deployments
BillingTeams: \$150/seat (Premium) with PAYG available
Enterprise: Contact Sales
PAYGPAYG through AWSPAYG through GCPPAYG 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/)Enabled by default Enabled by default Enabled by defaultEnabled by default
AuthenticationClaude.ai SSO or email API key API key or AWS credentials GCP credentials
Cost trackingDashboardUsage dashboardUsage dashboard AWS Cost Explorer GCP Billing Azure Cost Management
Includes Claude on webYesNoNoNoNo
Enterprise featuresTeams, usage monitoringTeam management, SSO, usage monitoringNone IAM policies, CloudTrail IAM roles, Cloud Audit Logs RBAC policies, Azure Monitor
-## Cloud providers - - - - Use Claude models through AWS infrastructure with API key or IAM-based authentication and AWS-native monitoring - - - - Access Claude models via Google Cloud Platform with enterprise-grade security and compliance - - - - Access Claude through Azure with API key or Microsoft Entra ID authentication and Azure billing - - - -## Corporate infrastructure - - - - Configure Claude Code to work with your organization's proxy servers and SSL/TLS requirements - +Select a deployment option to view setup instructions: - - Deploy centralized model access with usage tracking, budgeting, and audit logging - - +* [Claude for Teams or Enterprise](/en/iam#claude-for-teams-or-enterprise-recommended) +* [Anthropic Console](/en/iam#claude-console-authentication) +* [Amazon Bedrock](/en/amazon-bedrock) +* [Google Vertex AI](/en/google-vertex-ai) +* [Microsoft Foundry](/en/microsoft-foundry) -## Configuration overview +## Configure proxies and gateways -Claude Code supports flexible configuration options that allow you to combine different providers and infrastructure: +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: - - Understand the difference between: +* **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). - * **Corporate proxy**: An HTTP/HTTPS proxy for routing traffic (set via `HTTPS_PROXY` or `HTTP_PROXY`) - * **LLM Gateway**: A service that handles authentication and provides provider-compatible endpoints (set via `ANTHROPIC_BASE_URL`, `ANTHROPIC_BEDROCK_BASE_URL`, or `ANTHROPIC_VERTEX_BASE_URL`) +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. - Both configurations can be used in tandem. - +### Amazon Bedrock -### Using Bedrock with corporate proxy + + + Route Bedrock traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables): -Route Bedrock traffic through a corporate HTTP/HTTPS proxy: + ```bash theme={null} + # Enable Bedrock + export CLAUDE_CODE_USE_BEDROCK=1 + export AWS_REGION=us-east-1 -```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' + ``` + -# 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): -### Using Bedrock with LLM Gateway + ```bash theme={null} + # Enable Bedrock + export CLAUDE_CODE_USE_BEDROCK=1 -Use a gateway service that provides Bedrock-compatible endpoints: + # 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 + ``` + + -```bash theme={null} -# Enable Bedrock -export CLAUDE_CODE_USE_BEDROCK=1 +### Microsoft Foundry -# 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 -``` + + + Route Foundry traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables): -### Using Foundry with corporate proxy + ```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 -Route Azure traffic through a corporate HTTP/HTTPS proxy: + # Configure corporate proxy + export HTTPS_PROXY='https://proxy.example.com:8080' + ``` + -```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 + + Route Foundry traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables): -# Configure corporate proxy -export HTTPS_PROXY='https://proxy.example.com:8080' -``` + ```bash theme={null} + # Enable Microsoft Foundry + export CLAUDE_CODE_USE_FOUNDRY=1 -### Using Foundry with LLM Gateway + # 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 + ``` + + -Use a gateway service that provides Azure-compatible endpoints: +### Google Vertex AI -```bash theme={null} -# Enable Microsoft Foundry -export CLAUDE_CODE_USE_FOUNDRY=1 + + + Route Vertex AI traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables): -# 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 -``` + ```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 -### Using Vertex AI with corporate proxy + # Configure corporate proxy + export HTTPS_PROXY='https://proxy.example.com:8080' + ``` + -Route Vertex AI traffic through a corporate HTTP/HTTPS proxy: + + 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 -export CLOUD_ML_REGION=us-east5 -export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id + ```bash theme={null} + # Enable Vertex + export CLAUDE_CODE_USE_VERTEX=1 -# Configure corporate proxy -export HTTPS_PROXY='https://proxy.example.com:8080' -``` + # 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 + ``` + + -### Using Vertex AI with LLM Gateway - -Combine Google Vertex AI models with an LLM gateway for centralized management: - -```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 -``` - -### Authentication configuration - -Claude Code uses the `ANTHROPIC_AUTH_TOKEN` for the `Authorization` header when needed. The `SKIP_AUTH` flags (`CLAUDE_CODE_SKIP_BEDROCK_AUTH`, `CLAUDE_CODE_SKIP_VERTEX_AUTH`) are used in LLM gateway scenarios where the gateway handles provider authentication. - -## Choosing the right deployment configuration - -Consider these factors when selecting your deployment approach: - -### Direct provider access - -Best for organizations that: - -* Want the simplest setup -* Have existing AWS or GCP infrastructure -* Need provider-native monitoring and compliance - -### Corporate proxy - -Best for organizations that: - -* Have existing corporate proxy requirements -* Need traffic monitoring and compliance -* Must route all traffic through specific network paths - -### LLM Gateway - -Best for organizations that: - -* Need usage tracking across teams -* Want to dynamically switch between models -* Require custom rate limiting or budgets -* Need centralized authentication management - -## Debugging - -When debugging your deployment: - -* Use the `claude /status` [slash command](/en/slash-commands). This command provides observability into any applied authentication, proxy, and URL settings. -* Set environment variable `export ANTHROPIC_LOG=debug` to log requests. + + Use `/status` in Claude Code to verify your proxy and gateway configuration is applied correctly. + ## Best practices for organizations -### 1. Invest in documentation and memory +### 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](/en/memory). +Learn more in [Memory and CLAUDE.md files](/en/memory). -### 2. Simplify deployment +### 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. -### 3. Start with guided usage +### 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. -### 4. Configure security policies +### 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). -### 5. Leverage MCP for integrations +### 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). @@ -252,12 +247,11 @@ At Anthropic, we trust Claude Code to power development across every Anthropic c ## Next steps -* [Set up Amazon Bedrock](/en/amazon-bedrock) for AWS-native deployment -* [Configure Google Vertex AI](/en/google-vertex-ai) for GCP deployment -* [Set up Microsoft Foundry](/en/microsoft-foundry) for Azure deployment -* [Configure Enterprise Network](/en/network-config) for network requirements -* [Deploy LLM Gateway](/en/llm-gateway) for enterprise management -* [Settings](/en/settings) for configuration options and environment variables +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. --- diff --git a/skills/working-with-claude-code/references/troubleshooting.md b/skills/working-with-claude-code/references/troubleshooting.md index 08d0f5f..4218345 100644 --- a/skills/working-with-claude-code/references/troubleshooting.md +++ b/skills/working-with-claude-code/references/troubleshooting.md @@ -62,10 +62,6 @@ You may also encounter permission errors if your npm global prefix is not user w Claude Code has a native installation that doesn't depend on npm or Node.js. - - The native Claude Code installer is currently in beta. - - Use the following command to run the native installer. **macOS, Linux, WSL:** @@ -95,12 +91,47 @@ irm https://claude.ai/install.ps1 | iex ``` -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`. +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} @@ -135,23 +166,23 @@ This removes your stored authentication information and forces a clean login. 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, allowed tools) | -| `.mcp.json` | Project MCP servers (checked into source control) | -| `managed-settings.json` | [Enterprise managed settings](/en/settings#settings-files) | -| `managed-mcp.json` | [Enterprise managed MCP servers](/en/mcp#enterprise-mcp-configuration) | +| 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, allowed tools) | +| `.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`. -**Enterprise managed file locations:** +**Managed file locations:** * macOS: `/Library/Application Support/ClaudeCode/` * Linux/WSL: `/etc/claude-code/` -* Windows: `C:\ProgramData\ClaudeCode\` +* Windows: `C:\Program Files\ClaudeCode\` For details on configuring these files, see [Settings](/en/settings) and [MCP](/en/mcp). @@ -356,7 +387,14 @@ 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 check the health of your Claude Code installation +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 diff --git a/skills/working-with-claude-code/references/vs-code.md b/skills/working-with-claude-code/references/vs-code.md index 3d55b96..c82349a 100644 --- a/skills/working-with-claude-code/references/vs-code.md +++ b/skills/working-with-claude-code/references/vs-code.md @@ -1,120 +1,211 @@ -# Visual Studio Code +# Use Claude Code in VS Code -> Use Claude Code with Visual Studio Code through the native extension or CLI integration +> Install and configure the Claude Code extension for VS Code. Get AI coding assistance with inline diffs, @-mentions, plan review, and keyboard shortcuts. -Claude Code VS Code Extension Interface +VS Code editor with the Claude Code extension panel open on the right side, showing a conversation with Claude -## VS Code Extension (Beta) +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. -The VS Code extension, available in beta, lets you see Claude's changes in real-time through a native graphical interface integrated directly into your IDE. The VS Code extension makes it easier to access and interact with Claude Code for users who prefer a visual interface over the terminal. +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. -### Features +## Prerequisites -The VS Code extension provides: +* 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. -* **Native IDE experience**: Dedicated Claude Code sidebar panel accessed via the Spark icon -* **Plan mode with editing**: Review and edit Claude's plans before accepting them -* **Auto-accept edits mode**: Automatically apply Claude's changes as they're made -* **Extended thinking**: Toggle extended thinking on/off using the Extended Thinking button in the bottom-right corner of the prompt input -* **File management**: @-mention files or attach files and images using the system file picker -* **MCP server usage**: Use Model Context Protocol servers configured through the CLI -* **Conversation history**: Access to past conversations -* **Multiple sessions**: Run multiple Claude Code sessions simultaneously -* **Keyboard shortcuts**: Support for most shortcuts from the CLI -* **Slash commands**: Access most CLI slash commands directly in the extension +You don't need to install the Claude Code CLI first. However, some features like MCP server configuration require the CLI. See [VS Code extension vs. Claude Code CLI](#vs-code-extension-vs-claude-code-cli) for details. -### Requirements +## Install the extension -* VS Code 1.98.0 or higher +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) -### Installation +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**. -Download and install the extension from the [Visual Studio Code Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code). +You may need to restart VS Code or run "Developer: Reload Window" from the Command Palette after installation. -### How it works +## Get started Once installed, you can start using Claude Code through the VS Code interface: -1. Click the Spark icon in your editor's sidebar to open the Claude Code panel -2. Prompt Claude Code in the same way you would in the terminal -3. Watch as Claude analyzes your code and suggests changes -4. Review and accept edits directly in the interface - * **Tip**: Drag the sidebar wider to see inline diffs, then click them to expand for full details + + + Throughout VS Code, the Spark icon indicates Claude Code: Spark icon -### Configuration + 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. -The VS Code extension reads the same `settings.json` files as the CLI. See the [settings documentation](/en/settings) for details. + VS Code editor showing the Spark icon in the Editor Toolbar -#### Third-party providers and gateways + Other ways to open Claude Code: -To use the VS Code extension with third-party providers (Amazon Bedrock, Google Vertex AI, Microsoft Foundry) or gateways that handle authentication: + * **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. -1. Add the appropriate environment variables for your provider or gateway to your Claude Code `settings.json`: - ```json theme={null} - { - "env": { - "CLAUDE_CODE_USE_BEDROCK": "1", - "AWS_REGION": "us-east-2", - "AWS_PROFILE": "your-profile" - } - } - ``` + You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details. + -2. Disable the VS Code extension login prompt via [`vscode://settings/claudeCode.disableLoginPrompt`](vscode://settings/claudeCode.disableLoginPrompt) or in VS Code's settings: - ```json theme={null} - { - "claudeCode.disableLoginPrompt": true - } - ``` + + Ask Claude to help with your code or files, whether that's explaining how something works, debugging an issue, or making changes. -For detailed setup instructions and additional configuration options, see: + Select text in the editor and press `Alt+K` to insert an @-mention with the file path and line numbers directly into your prompt. -* [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) + Here's an example of asking about a particular line in a file: -### Not yet implemented + 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 + -The following features aren't yet available in the VS Code extension: + + When Claude wants to edit a file, it shows you a diff and asks for permission. You can accept, reject, or tell Claude what to do instead. -* **MCP server and Plugin configuration UI**: Type `/mcp` to open the terminal-based MCP server configuration, or `/plugin` for Plugin configuration. Once configured, MCP servers and Plugins work in the extension. You can also [configure MCP servers through the CLI](/en/mcp) first, then the extension will use them. -* **Subagents configuration**: Configure [subagents through the CLI](/en/sub-agents) to use them in VS Code -* **Checkpoints**: Save and restore conversation state at specific points -* **Conversation rewinding**: The `/rewind` command is coming soon -* **Advanced shortcuts**: - * `#` shortcut to add to memory (not supported) - * `!` shortcut to run bash commands directly (not supported) -* **Tab completion**: File path completion with tab key -* **Model selection UI for older models**: To use older model versions like `claude-sonnet-4-20250514`, open VS Code settings for Claude Code (the `/General Config` command) and insert the model string directly into the 'Selected Model' field + VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit + + -These features are planned for future updates. +For more ideas on what you can do with Claude Code, see [Common workflows](/en/common-workflows). -## Security considerations +## Customize your workflow + +Once you're up and running, you can reposition the Claude panel or switch to terminal mode. + +### Change the layout + +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** (default): The right side of the window +* **Primary sidebar**: The left sidebar with icons for Explorer, Search, etc. +* **Editor area**: Opens Claude as a tab alongside your files + + + The Spark icon only appears in the Activity Bar (left sidebar icons) when the Claude panel is docked to the left. Since Claude defaults to the right side, use the Editor Toolbar icon to open Claude. + + +### 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**. + +## 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: + + + These are VS Code commands for controlling the extension. For Claude Code slash commands (like `/help` or `/compact`), not all CLI commands are available in the extension yet. 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 (when Claude is focused) | +| Insert @-Mention Reference | `Alt+K` | Insert a reference to the current file (includes line numbers if text is selected) | +| Show Logs | — | View extension debug logs | +| Logout | — | Sign out of your Anthropic account | + +Use **Open in New Tab** or **Open in New Window** to run multiple conversations simultaneously. Each tab or window maintains its own conversation history and context. + +## Configure settings + +The extension has two types of settings: + +* **Extension settings**: Open with `Cmd+,` (Mac) or `Ctrl+,` (Windows/Linux), then go to Extensions → Claude Code. + + | Setting | Description | + | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | + | Selected Model | Default model for new conversations. Change per-session with `/model`. | + | Use Terminal | Launch Claude in terminal mode instead of graphical panel | + | Initial Permission Mode | Controls approval prompts for file edits and commands. Defaults to `default` (ask before each action). | + | Preferred Location | Default location: sidebar (right) or panel (new tab) | + | Autosave | Auto-save files before Claude reads or writes them | + | Use Ctrl+Enter to Send | Use Ctrl/Cmd+Enter instead of Enter to send prompts | + | Enable New Conversation Shortcut | Enable Cmd/Ctrl+N to start a new conversation | + | Respect Git Ignore | Exclude .gitignore patterns from file searches | + | Environment Variables | Set environment variables for the Claude process. **Not recommended**—use [Claude Code settings](/en/settings) instead so configuration is shared between extension and CLI. | + | Disable Login Prompt | Skip authentication prompts (for third-party provider setups) | + | Allow Dangerously Skip Permissions | Bypass all permission prompts. **Use with extreme caution**—recommended only for isolated sandboxes with no internet access. | + | Claude Process Wrapper | Executable path used to launch the Claude process | + +* **Claude Code settings** (`~/.claude/settings.json`): These settings are shared between the VS Code extension and the CLI. Use this file for allowed commands and directories, environment variables, hooks, and MCP servers. See the [settings documentation](/en/settings) for details. + +## 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: -When Claude Code runs in VS Code 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. + + + Open the [Disable Login Prompt setting](vscode://settings/claudeCode.disableLoginPrompt) and check the box. -When running in VS Code, consider: + 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**. + -* Enabling [VS Code Restricted Mode](https://code.visualstudio.com/docs/editor/workspace-trust#_restricted-mode) for untrusted workspaces -* Using manual approval mode for edits -* Taking extra care to ensure Claude is only used with trusted prompts + + Follow the setup guide for your provider: -## Legacy CLI integration + * [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) -The original VS Code integration allows Claude Code running in the terminal to interact with your IDE. It provides selection context sharing (current selection/tab is automatically shared with Claude Code), diff viewing in the IDE instead of terminal, file reference shortcuts (`Cmd+Option+K` on Mac or `Alt+Ctrl+K` on Windows/Linux to insert file references like @File#L1-99), and automatic diagnostic sharing (lint and syntax errors). + These guides cover configuring your provider in `~/.claude/settings.json`, which ensures your settings are shared between the VS Code extension and the CLI. + + -The legacy integration auto-installs when you run `claude` from VS Code's integrated terminal. Run `claude` from the terminal and all features activate. For external terminals, use the `/ide` command to connect Claude Code to your VS Code instance. To configure, run `claude`, enter `/config`, and set the diff tool to `auto` for automatic IDE detection. +## VS Code extension vs. Claude Code CLI -Both the extension and CLI integration work with Visual Studio Code, Cursor, Windsurf, and VSCodium. +The extension doesn't yet have full feature parity with the CLI. If you need CLI-only features, you can run `claude` directly in VS Code's integrated terminal. -## Troubleshooting +| Feature | CLI | VS Code Extension | +| ----------------- | ------------------------------ | ---------------------------------------- | +| Slash commands | [Full set](/en/slash-commands) | Subset (type `/` to see available) | +| MCP server config | Yes | No (configure via CLI, use in extension) | +| Checkpoints | Yes | Coming soon | +| `!` bash shortcut | Yes | No | +| Tab completion | Yes | No | -### Extension not installing +### Run CLI in VS Code -* Ensure you have a compatible version of VS Code (1.85.0 or later) +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. + +## Security considerations + +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. This could potentially bypass Claude Code's normal permission prompts. + +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 Marketplace website +### 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: @@ -124,20 +215,40 @@ If Claude Code isn't responding to your prompts: 3. **Try the CLI**: Run `claude` from the terminal to see if you get more detailed error messages 4. **File a bug report**: If the problem continues, [file an issue on GitHub](https://github.com/anthropics/claude-code/issues) with details about the error -### Legacy integration not working +### Standalone CLI not connecting to IDE -* Ensure you're running Claude Code from VS Code's integrated terminal +* Ensure you're running Claude Code from VS Code's integrated terminal (not an external terminal) * Ensure the CLI for your IDE variant is installed: * VS Code: `code` command should be available * Cursor: `cursor` command should be available * Windsurf: `windsurf` command should be available * VSCodium: `codium` command should be available -* If the command isn't installed: - 1. Open command palette with `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux) - 2. Search for `Shell Command: Install 'code' command in PATH` (or equivalent for your IDE) +* If the command isn't available, install it from the Command Palette → "Shell Command: Install 'code' command in PATH" + +## 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. + ---