Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:44:51 +08:00
commit ac511e2e50
51 changed files with 14001 additions and 0 deletions

View File

@@ -0,0 +1,283 @@
---
name: developing-claude-code-plugins
description: Use when working on Claude Code plugins (creating, modifying, testing, releasing, or maintaining) - provides streamlined workflows, patterns, and examples for the complete plugin lifecycle
---
# Developing Claude Code Plugins
## Overview
This skill provides efficient workflows for creating Claude Code plugins. Use it to make plugin development fast and correct - it synthesizes official docs into actionable steps and provides working examples.
## When to Use
Use this skill when:
- Creating a new Claude Code plugin from scratch
- Adding components to an existing plugin (skills, commands, hooks, MCP servers)
- Setting up a development marketplace for testing
- Troubleshooting plugin structure issues
- Understanding plugin architecture and patterns
- Releasing a plugin (versioning, tagging, marketplace distribution)
- Publishing updates or maintaining existing plugins
**For comprehensive official documentation**, use the `working-with-claude-code` skill to access full docs.
## Quick Reference
| Need to... | Read This | Official Docs |
|-----------|-----------|---------------|
| Understand directory structure | `references/plugin-structure.md` | `plugins.md` |
| Choose a plugin pattern | `references/common-patterns.md` | `plugins.md` |
| Debug plugin issues | `references/troubleshooting.md` | Various |
| See working examples | `examples/` directory | N/A |
## Plugin Development Workflow
### Phase 1: Plan
Before writing code:
1. **Define your plugin's purpose**
- What problem does it solve?
- Who will use it?
- What components will it need?
2. **Choose your pattern** (read `references/common-patterns.md`)
- Simple plugin with one skill?
- MCP integration with guidance?
- Command collection?
- Full-featured platform?
3. **Review examples**
- `examples/simple-greeter-plugin/` - Minimal plugin
- `examples/full-featured-plugin/` - All components
- Installed plugins in `~/.claude/plugins/`
### Phase 2: Create Structure
1. **Create directories** (see `references/plugin-structure.md` for details):
```bash
mkdir -p my-plugin/.claude-plugin
mkdir -p my-plugin/skills
# Add other component directories as needed
```
2. **Write plugin.json** (required):
```json
{
"name": "my-plugin",
"version": "1.0.0",
"description": "What your plugin does",
"author": {"name": "Your Name"}
}
```
See `references/plugin-structure.md` for complete format.
3. **Create development marketplace** (for local testing):
Create `.claude-plugin/marketplace.json`:
```json
{
"name": "my-dev",
"plugins": [{
"name": "my-plugin",
"source": "./"
}]
}
```
See `references/plugin-structure.md` for complete format.
### Phase 3: Add Components
Use TodoWrite to track component creation:
**Example:**
```
- Create skill: main-workflow
- Add command: /hello
- Configure hooks
- Write README
- Test installation
```
For each component type, see:
- **Format/syntax**: `references/plugin-structure.md`
- **When to use**: `references/common-patterns.md`
- **Working code**: `examples/` directory
### Phase 4: Test Locally
1. **Install for testing**:
```bash
/plugin marketplace add /path/to/my-plugin
/plugin install my-plugin@my-dev
```
Then restart Claude Code.
2. **Test each component**:
- Skills: Ask for tasks matching skill descriptions
- Commands: Run `/your-command`
- MCP servers: Check tools are available
- Hooks: Trigger relevant events
3. **Iterate**:
```bash
/plugin uninstall my-plugin@my-dev
# Make changes
/plugin install my-plugin@my-dev
# Restart Claude Code
```
### Phase 5: Debug and Refine
If something doesn't work, read `references/troubleshooting.md` for:
- Plugin not loading
- Skill not triggering
- Command not appearing
- MCP server not starting
- Hooks not firing
Common issues are usually:
- Wrong directory structure
- Hardcoded paths (use `${CLAUDE_PLUGIN_ROOT}`)
- Forgot to restart Claude Code
- Missing executable permissions on scripts
### Phase 6: Release and Distribute
1. **Write README** with:
- What the plugin does
- Installation instructions
- Usage examples
- Component descriptions
2. **Version your release** using semantic versioning:
- Update `version` in `.claude-plugin/plugin.json`
- Document changes in CHANGELOG.md or RELEASE-NOTES.md
- Example: `"version": "1.2.1"` (major.minor.patch)
3. **Commit and tag your release**:
```bash
git add .
git commit -m "Release v1.2.1: [brief description]"
git tag v1.2.1
git push origin main
git push origin v1.2.1
```
4. **Choose distribution method**:
**Option A: Direct GitHub distribution**
- Users add: `/plugin marketplace add your-org/your-plugin-repo`
- Your plugin.json serves as the manifest
**Option B: Marketplace distribution** (recommended for multi-plugin collections)
- Create separate marketplace repository
- Add `.claude-plugin/marketplace.json` with plugin references:
```json
{
"name": "my-marketplace",
"owner": {"name": "Your Name"},
"plugins": [{
"name": "your-plugin",
"source": {
"source": "url",
"url": "https://github.com/your-org/your-plugin.git"
},
"version": "1.2.1",
"description": "Plugin description"
}]
}
```
- Users add: `/plugin marketplace add your-org/your-marketplace`
- Update marketplace manifest for each plugin release
**Option C: Private/team distribution**
- Configure in team's `.claude/settings.json`:
```json
{
"extraKnownMarketplaces": {
"team-tools": {
"source": {"source": "github", "repo": "your-org/plugins"}
}
}
}
```
5. **Test the release**:
```bash
# Test fresh installation
/plugin marketplace add your-marketplace-source
/plugin install your-plugin@marketplace-name
# Verify functionality, then clean up
/plugin uninstall your-plugin@marketplace-name
```
6. **Announce and maintain**:
- GitHub releases (optional)
- Team notifications
- Monitor for issues and user feedback
- Plan maintenance updates
## Critical Rules
**Always follow these** (from `references/plugin-structure.md`):
1. **`.claude-plugin/` contains ONLY manifests** (`plugin.json` and optionally `marketplace.json`)
- ❌ Don't put skills, commands, or other components inside
- ✅ Put them at plugin root
2. **Use `${CLAUDE_PLUGIN_ROOT}` for all paths in config files**
- Makes plugin portable across systems
- Required for hooks, MCP servers, scripts
3. **Use relative paths in `plugin.json`**
- Start with `./`
- Relative to plugin root
4. **Make scripts executable**
- `chmod +x script.sh`
- Required for hooks and MCP servers
## Resources in This Skill
- **`references/plugin-structure.md`** - Directory layout, file formats, component syntax
- **`references/common-patterns.md`** - When to use each plugin pattern, examples
- **`references/troubleshooting.md`** - Debug guide for common issues
- **`examples/simple-greeter-plugin/`** - Minimal working plugin (one skill)
- **`examples/full-featured-plugin/`** - Complete plugin with all components
## Cross-References
For deep dives into official documentation, use the `working-with-claude-code` skill to access:
- `plugins.md` - Plugin development overview
- `plugins-reference.md` - Complete API reference
- `skills.md` - Skill authoring guide
- `slash-commands.md` - Command format
- `hooks.md`, `hooks-guide.md` - Hook system
- `mcp.md` - MCP server integration
- `plugin-marketplaces.md` - Distribution
## Best Practices
1. **Start simple** - Begin with minimal structure, add complexity when needed
2. **Test frequently** - Install → test → uninstall → modify → repeat
3. **Use examples** - Copy patterns from working plugins
4. **Follow conventions** - Match style of existing plugins
5. **Document everything** - Clear README helps users and future you
6. **Version properly** - Use semantic versioning (major.minor.patch)
## Workflow Summary
```
Plan → Choose pattern, review examples
Create → Make structure, write manifests
Add → Build components (skills, commands, etc.)
Test → Install via dev marketplace
Debug → Use troubleshooting guide
Release → Version, tag, distribute via marketplace
Maintain → Monitor, update, support users
```
**The correct path is the fast path.** Use references, follow patterns, test frequently.

View File

@@ -0,0 +1,225 @@
# Common Plugin Patterns
## Pattern: Simple Plugin with One Skill
**Use when:** Creating a focused plugin with documentation/reference material
**Structure:**
```
my-plugin/
├── .claude-plugin/
│ ├── plugin.json
│ └── marketplace.json
├── skills/
│ └── my-skill/
│ ├── SKILL.md
│ ├── scripts/ # Optional - Executable helpers
│ └── references/ # Optional - Documentation files
└── README.md
```
**Real example:** `superpowers-developing-for-claude-code`
- Single skill with comprehensive documentation
- Scripts for self-updating
- 40+ reference files
- No MCP servers, commands, or hooks
**When to use:**
- Teaching Claude about a specific topic/domain
- Providing process workflows (TDD, debugging, code review)
- Bundling documentation for easy reference
- Creating reusable knowledge bases
---
## Pattern: MCP Plugin with Skill
**Use when:** Providing both a tool integration (MCP) and guidance on using it (skill)
**Structure:**
```
my-plugin/
├── .claude-plugin/
│ └── plugin.json # Includes mcpServers config
├── skills/
│ └── using-the-tools/
│ └── SKILL.md # How to use the MCP tools
├── mcp/
│ └── dist/
│ └── index.js # MCP server implementation
└── README.md
```
**Real example:** `superpowers-chrome`
- MCP server provides browser control tools
- Skill teaches Claude how to use those tools effectively
- Skill includes patterns, examples, workflows
**When to use:**
- Adding new tools/capabilities to Claude
- Integrating external APIs or services
- Tools need guidance on when/how to use them
- Want Claude to use tools idiomatically, not just technically
**Key insight:** MCP provides *capability*, skill provides *judgment*. The MCP server exposes `click()`, the skill teaches "await elements before clicking them".
---
## Pattern: Command Collection
**Use when:** Providing multiple custom slash commands for common tasks
**Structure:**
```
my-plugin/
├── .claude-plugin/
│ └── plugin.json
├── commands/
│ ├── status.md
│ ├── logs.md
│ ├── deploy.md
│ └── rollback.md
└── README.md
```
**When to use:**
- Project-specific workflows (deploy, test, build)
- Common task shortcuts
- Standardized responses (greetings, status reports)
- Quick context injection
**Example use cases:**
- `/deploy-staging` - Step-by-step deployment workflow
- `/incident-report` - Template for incident documentation
- `/code-review` - Checklist for reviewing PRs
- `/security-check` - Security audit workflow
---
## Pattern: Hook-Enhanced Workflow
**Use when:** Automating actions in response to Claude's behavior
**Structure:**
```
my-plugin/
├── .claude-plugin/
│ └── plugin.json
├── hooks/
│ └── hooks.json
├── scripts/
│ ├── format-code.sh
│ ├── run-linter.sh
│ └── update-docs.sh
└── README.md
```
**Common hooks:**
- `PostToolUse[Write|Edit]` → Auto-format code
- `SessionStart` → Load project context
- `UserPromptSubmit` → Enforce conventions
- `PreCompact` → Save conversation summaries
**When to use:**
- Enforcing code style automatically
- Injecting project-specific context
- Running validations or checks
- Maintaining project conventions
**Warning:** Hooks that block operations can disrupt workflow. Use sparingly and make failure messages clear.
---
## Pattern: Full-Featured Plugin
**Use when:** Building a comprehensive plugin with multiple integration points
**Structure:**
```
my-plugin/
├── .claude-plugin/
│ └── plugin.json
├── skills/
│ ├── main-workflow/
│ └── advanced-techniques/
├── commands/
│ ├── start.md
│ └── help.md
├── hooks/
│ └── hooks.json
├── agents/
│ └── specialist.md
├── mcp/
│ └── dist/
│ └── server.js
└── README.md
```
**Real example:** See `examples/full-featured-plugin/` in this repo
**When to use:**
- Complete domain coverage (e.g., "the definitive AWS plugin")
- Multiple related workflows
- Tools + guidance + automation all needed
- Building a "platform" plugin
**Caution:** Start simple, add complexity only when justified. Most plugins don't need all components.
---
## Pattern: Skill with Bundled Resources
**Use when:** A skill needs reference material, scripts, or templates
**Structure:**
```
skills/my-skill/
├── SKILL.md # Main skill instructions
├── scripts/
│ ├── helper.py # Executable utilities
│ └── generator.js
├── references/
│ ├── api-docs.md # Documentation to load
│ ├── examples.md
│ └── cheatsheet.md
└── assets/
├── template.txt # Files for output
└── config-example.json
```
**How resources are used:**
- SKILL.md tells Claude to "read references/api-docs.md for complete API reference"
- Scripts can be executed via Bash tool
- Assets can be copied/modified for output
- References are loaded into context when skill is invoked
**When to use:**
- Skill needs detailed technical reference
- Want to separate workflow (SKILL.md) from reference (docs)
- Need executable helpers
- Providing templates or examples
---
## Choosing the Right Pattern
| Your Goal | Use This Pattern |
|-----------|------------------|
| Teach Claude a process/workflow | Simple Plugin with One Skill |
| Add new tools + guidance | MCP Plugin with Skill |
| Provide project shortcuts | Command Collection |
| Enforce conventions automatically | Hook-Enhanced Workflow |
| Comprehensive domain coverage | Full-Featured Plugin |
| Skill needs reference docs | Skill with Bundled Resources |
## Combining Patterns
Patterns are composable:
**Example: "superpowers" plugin**
- Multiple skills (brainstorming, TDD, debugging) ← Skill collection
- Each skill has references/ ← Bundled resources
- Could add hooks for enforcement ← Add hooks pattern
- Could add MCP for new tools ← Add MCP pattern
**Start simple, grow intentionally.** Add components when you have a clear reason, not because they exist.

View File

@@ -0,0 +1,314 @@
# Plugin Structure Reference
## Standard Directory Layout
All paths relative to plugin root:
```
my-plugin/
├── .claude-plugin/
│ ├── plugin.json # REQUIRED - Plugin metadata
│ └── marketplace.json # Optional - For local dev/distribution
├── skills/ # Optional - Agent Skills
│ └── skill-name/
│ ├── SKILL.md # Required for each skill
│ ├── scripts/ # Optional - Executable helpers
│ ├── references/ # Optional - Documentation
│ └── assets/ # Optional - Templates/files
├── commands/ # Optional - Custom slash commands
│ └── command-name.md
├── agents/ # Optional - Specialized subagents
│ └── agent-name.md
├── hooks/ # Optional - Event handlers
│ └── hooks.json
├── .mcp.json # Optional - MCP server config
├── LICENSE
└── README.md
```
## Critical Rules
### 1. `.claude-plugin/` Contains ONLY Manifests
**❌ WRONG:**
```
.claude-plugin/
├── plugin.json
├── skills/ # NO! Skills don't go here
└── commands/ # NO! Commands don't go here
```
**✅ CORRECT:**
```
.claude-plugin/
├── plugin.json # Only manifests
└── marketplace.json # Only manifests
skills/ # Skills at plugin root
commands/ # Commands at plugin root
```
### 2. Always Use `${CLAUDE_PLUGIN_ROOT}` for Paths in Config
**❌ WRONG - Hardcoded paths:**
```json
{
"mcpServers": {
"my-server": {
"command": "/Users/name/plugins/my-plugin/server.js"
}
}
}
```
**✅ CORRECT - Variable paths:**
```json
{
"mcpServers": {
"my-server": {
"command": "${CLAUDE_PLUGIN_ROOT}/server.js"
}
}
}
```
### 3. Use Relative Paths in `plugin.json`
All paths in `plugin.json` must:
- Start with `./`
- Be relative to plugin root
**❌ WRONG:**
```json
{
"mcpServers": {
"server": {
"args": ["server/index.js"] // Missing ./
}
}
}
```
**✅ CORRECT:**
```json
{
"mcpServers": {
"server": {
"args": ["${CLAUDE_PLUGIN_ROOT}/server/index.js"]
}
}
}
```
## Plugin Manifest (plugin.json)
### Minimal Version
```json
{
"name": "my-plugin",
"version": "1.0.0",
"description": "Brief description of what the plugin does",
"author": {
"name": "Your Name"
}
}
```
### Complete Version
```json
{
"name": "my-plugin",
"version": "1.0.0",
"description": "Comprehensive plugin description",
"author": {
"name": "Your Name",
"email": "you@example.com",
"url": "https://github.com/you"
},
"homepage": "https://github.com/you/my-plugin",
"repository": "https://github.com/you/my-plugin",
"license": "MIT",
"keywords": ["keyword1", "keyword2"],
"mcpServers": {
"server-name": {
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/path/to/server.js"],
"env": {
"ENV_VAR": "value"
}
}
}
}
```
## Development Marketplace (marketplace.json)
For local testing, create in `.claude-plugin/`:
```json
{
"name": "my-plugin-dev",
"description": "Development marketplace for my plugin",
"owner": {
"name": "Your Name"
},
"plugins": [
{
"name": "my-plugin",
"description": "Plugin description",
"version": "1.0.0",
"source": "./",
"author": {
"name": "Your Name"
}
}
]
}
```
**Installation:**
```bash
/plugin marketplace add /path/to/my-plugin
/plugin install my-plugin@my-plugin-dev
```
## Component Formats
### Skills (skills/skill-name/SKILL.md)
```markdown
---
name: skill-name
description: Use when [triggering conditions] - [what it does]
---
# Skill Name
## Overview
What this skill does in 1-2 sentences.
## When to Use
- Specific scenario 1
- Specific scenario 2
## Workflow
1. Step one
2. Step two
3. Step three
```
### Commands (commands/command-name.md)
```markdown
---
description: Brief description of what this command does
---
# Command Instructions
Tell Claude what to do when this command is invoked.
Be specific and clear about the expected behavior.
```
### Hooks (hooks/hooks.json)
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh"
}
]
}
],
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/init.sh"
}
]
}
]
}
}
```
**Available hook events:**
- `PreToolUse`, `PostToolUse`
- `UserPromptSubmit`
- `SessionStart`, `SessionEnd`
- `Stop`, `SubagentStop`
- `PreCompact`
- `Notification`
### MCP Servers
**Option 1: In plugin.json**
```json
{
"name": "my-plugin",
"mcpServers": {
"server-name": {
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/server/index.js"],
"env": {
"API_KEY": "${PLUGIN_ENV_API_KEY}"
}
}
}
}
```
**Option 2: Separate .mcp.json file**
```json
{
"mcpServers": {
"server-name": {
"command": "${CLAUDE_PLUGIN_ROOT}/bin/server",
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"]
}
}
}
```
### Agents (agents/agent-name.md)
```markdown
---
description: What this agent specializes in
capabilities: ["capability1", "capability2"]
---
# Agent Name
Detailed description of when to invoke this specialized agent.
## Expertise
- Specific domain knowledge
- Specialized techniques
- When to use vs other agents
```
## File Permissions
Scripts must be executable:
```bash
chmod +x scripts/helper.sh
chmod +x bin/server
```

View File

@@ -0,0 +1,374 @@
# Troubleshooting Plugin Development
## Plugin Not Loading
### Symptom
Plugin doesn't appear in `/plugin list` or components aren't available.
### Debug Steps
1. **Check plugin.json syntax**
```bash
# Validate JSON
cat .claude-plugin/plugin.json | jq .
```
If this errors, you have invalid JSON.
2. **Verify directory structure**
```bash
# Ensure .claude-plugin/ exists at plugin root
ls -la .claude-plugin/
# Should show plugin.json (required)
```
3. **Check all paths**
- Search for hardcoded paths: `grep -r "/Users/" .claude-plugin/`
- Should use `${CLAUDE_PLUGIN_ROOT}` instead
- Relative paths in plugin.json must start with `./`
4. **Restart Claude Code**
- Changes only take effect after restart
- Exit and relaunch the application
5. **Check installation**
```bash
/plugin list
# Your plugin should appear here
```
### Common Causes
| Problem | Solution |
|---------|----------|
| `.claude-plugin/` missing | Create directory with `plugin.json` |
| Invalid JSON in `plugin.json` | Validate with `jq` or JSON linter |
| Hardcoded paths | Replace with `${CLAUDE_PLUGIN_ROOT}` |
| Forgot to restart | Always restart after install/changes |
---
## Skill Not Triggering
### Symptom
Skill exists but Claude doesn't use it when expected.
### Debug Steps
1. **Check YAML frontmatter format**
```markdown
---
name: skill-name
description: Use when [clear trigger] - [what it does]
---
```
- Must have `---` delimiters
- Must include `name` and `description`
- No tabs, only spaces for indentation
2. **Verify description clarity**
- Description should clearly state WHEN to use skill
- Use "Use when..." format
- Be specific about triggering conditions
❌ Bad: `description: A helpful skill`
✅ Good: `description: Use when debugging test failures - systematic approach to finding root causes`
3. **Test explicitly**
Ask for a task that exactly matches the description:
```
"I need to debug a test failure"
# Should trigger systematic-debugging skill
```
4. **Check skill location**
- Must be in `skills/skill-name/SKILL.md`
- NOT in `.claude-plugin/skills/`
### Common Causes
| Problem | Solution |
|---------|----------|
| Vague description | Make description specific and action-oriented |
| Skill in wrong location | Move to `skills/` at plugin root |
| Missing frontmatter | Add YAML with name and description |
| Malformed YAML | Check for tabs, missing dashes, etc. |
---
## Command Not Appearing
### Symptom
Custom slash command doesn't show up or can't be executed.
### Debug Steps
1. **Verify location**
```bash
ls -la commands/
# Should show command-name.md files
```
Commands must be at `commands/` in plugin root, NOT in `.claude-plugin/`
2. **Check markdown format**
```markdown
---
description: Brief description of what this command does
---
# Command Instructions
Content here...
```
3. **Restart Claude Code**
Commands are loaded at startup.
4. **Test directly**
```
/your-command-name
```
### Common Causes
| Problem | Solution |
|---------|----------|
| Commands in `.claude-plugin/` | Move to `commands/` at root |
| Missing description frontmatter | Add YAML with description |
| No restart after adding | Restart Claude Code |
| Wrong file extension | Must be `.md` not `.txt` |
---
## MCP Server Not Starting
### Symptom
MCP server tools not available, or server fails silently.
### Debug Steps
1. **Verify path variables**
All paths in MCP config must use `${CLAUDE_PLUGIN_ROOT}`:
```json
{
"mcpServers": {
"my-server": {
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/server/index.js"]
}
}
}
```
2. **Check executable permissions**
```bash
chmod +x server/index.js
# Or for shell scripts:
chmod +x bin/server.sh
```
3. **Test server independently**
```bash
# Run server outside Claude Code to check for errors
node ${PLUGIN_ROOT}/server/index.js
```
4. **Check logs**
```bash
claude --debug
# Look for MCP server startup errors
```
5. **Verify command exists**
```bash
which node # Or whatever command you're using
```
### Common Causes
| Problem | Solution |
|---------|----------|
| Hardcoded paths | Use `${CLAUDE_PLUGIN_ROOT}` |
| Not executable | `chmod +x` on scripts |
| Command not in PATH | Use full path or ensure command available |
| Server crashes on startup | Test independently, check logs |
| Missing dependencies | `npm install` or equivalent |
---
## Hooks Not Firing
### Symptom
Hook scripts exist but don't execute when events occur.
### Debug Steps
1. **Check hooks.json location**
Must be at `hooks/hooks.json` in plugin root.
2. **Verify JSON format**
```bash
cat hooks/hooks.json | jq .
```
3. **Check matcher syntax**
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit", // Regex - matches Write OR Edit
"hooks": [...]
}
]
}
}
```
4. **Verify script paths**
```json
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh"
}
```
5. **Check script permissions**
```bash
chmod +x scripts/format.sh
```
6. **Test script directly**
```bash
# Run the hook script manually
./scripts/format.sh
```
### Common Causes
| Problem | Solution |
|---------|----------|
| Wrong hooks.json location | Move to `hooks/` at plugin root |
| Script not executable | `chmod +x` on all scripts |
| Invalid matcher regex | Test regex syntax |
| Script fails silently | Add error handling, test independently |
| Hardcoded paths | Use `${CLAUDE_PLUGIN_ROOT}` |
---
## Development Workflow Issues
### Can't Install Plugin Locally
**Problem:** `/plugin install my-plugin@my-dev` fails
**Solutions:**
1. Check marketplace.json exists in `.claude-plugin/`
2. Verify marketplace is added:
```bash
/plugin marketplace add /full/path/to/plugin
/plugin marketplace list # Should show your marketplace
```
3. Check marketplace.json format:
```json
{
"name": "my-dev",
"plugins": [{
"name": "my-plugin",
"source": "./" // Points to plugin root
}]
}
```
### Changes Not Taking Effect
**Problem:** Modified plugin but changes don't appear
**Solutions:**
1. Uninstall → modify → reinstall → restart:
```bash
/plugin uninstall my-plugin@my-dev
# Make your changes
/plugin install my-plugin@my-dev
# Restart Claude Code
```
2. For hook/MCP changes, restart is mandatory
3. For skill/command content changes, sometimes works without restart (but safer to restart)
---
## Common Pitfalls Summary
| Mistake | Why It Fails | How to Fix |
|---------|-------------|------------|
| Skills in `.claude-plugin/skills/` | Claude looks in `skills/` at root | Move to plugin root |
| Hardcoded absolute paths | Breaks on other systems | Use `${CLAUDE_PLUGIN_ROOT}` |
| Forgot to restart | Changes load at startup | Always restart after changes |
| Script not executable | Shell can't run it | `chmod +x script.sh` |
| Invalid JSON | Parser fails silently | Validate with `jq` or linter |
| Vague skill description | Claude doesn't know when to use it | Be specific about triggers |
| Missing YAML frontmatter | Metadata not parsed | Add `---` delimiters and fields |
| Testing without uninstall | Old version still cached | Uninstall before reinstalling |
---
## Debugging Workflow
When something isn't working:
1. **Validate all JSON files**
```bash
jq . .claude-plugin/plugin.json
jq . .claude-plugin/marketplace.json
jq . hooks/hooks.json
```
2. **Check all paths use variables**
```bash
grep -r "Users/" .
# Should return nothing in config files
```
3. **Verify permissions**
```bash
find . -name "*.sh" -o -name "*.js" | xargs ls -l
# Check executable bit (x) is set
```
4. **Test components independently**
- Run MCP servers directly
- Execute hook scripts manually
- Validate YAML frontmatter with a parser
5. **Clean reinstall**
```bash
/plugin uninstall my-plugin@my-dev
/plugin marketplace remove /path/to/plugin
# Fix issues
/plugin marketplace add /path/to/plugin
/plugin install my-plugin@my-dev
# Restart Claude Code
```
6. **Check logs**
```bash
claude --debug
# Look for error messages during startup
```
---
## Getting Help
If you're still stuck:
1. **Read official docs** via `working-with-claude-code` skill
2. **Check example plugins** in this repo and `~/.claude/plugins/`
3. **Simplify** - Remove components until it works, then add back one at a time
4. **Report issues** at https://github.com/anthropics/claude-code/issues
**Pro tip:** When asking for help, include:
- Your plugin.json
- Directory structure (`tree -L 3 -a`)
- Exact error messages
- What you've already tried

View File

@@ -0,0 +1,173 @@
---
name: working-with-claude-code
description: Use when working with Claude Code CLI, plugins, hooks, MCP servers, skills, configuration, or any Claude Code feature - provides comprehensive official documentation for all aspects of Claude Code
---
# Working with Claude Code
## 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.
## When to Use
Use this skill when:
- Creating or configuring Claude Code plugins
- Setting up MCP servers
- Working with hooks (pre-commit, session-start, etc.)
- Writing or testing skills
- Configuring Claude Code settings
- Troubleshooting Claude Code issues
- Understanding CLI commands
- Setting up integrations (VS Code, JetBrains, etc.)
- Configuring networking, security, or enterprise features
## Quick Reference
| Task | Read This File |
|------|---------------|
| Create a plugin | `plugins.md` then `plugins-reference.md` |
| Set up MCP server | `mcp.md` |
| Configure hooks | `hooks.md` then `hooks-guide.md` |
| Write a skill | `skills.md` |
| CLI commands | `cli-reference.md` |
| Troubleshoot issues | `troubleshooting.md` |
| General setup | `setup.md` or `quickstart.md` |
| Configuration options | `settings.md` |
## Documentation Organization
All documentation is stored as individual markdown files in `references/`. Use the Read tool to access specific documentation:
```
references/
├── 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
├── third-party-integrations.md # Other integrations
├── legal-and-compliance.md # Legal information
├── troubleshooting.md # Troubleshooting guide
└── migration-guide.md # Migration guide
```
## Workflow
### For Specific Questions
1. Identify the relevant documentation file from the list above
2. Use Read tool to load: `@references/filename.md`
3. Find the answer in the official documentation
4. Apply the solution
**Example:**
```
User: "How do I create a Claude Code plugin?"
→ Read @references/plugins.md
→ Follow the official plugin creation steps
```
### For Broad Topics
When exploring a topic, start with the overview document, then drill into specific files:
- **Extending Claude Code**: Start with `plugins.md`, `skills.md`, or `mcp.md`
- **Configuration**: Start with `settings.md` or `setup.md`
- **Integrations**: Check relevant integration file (vs-code.md, github-actions.md, etc.)
- **Troubleshooting**: Start with `troubleshooting.md`
### For Uncertain Topics
Use Grep tool to search across all documentation:
```bash
pattern: "search term"
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.
Run when:
- Documentation seems outdated
- New Claude Code features are released
- Official docs have been updated
```bash
node ~/.claude/skills/working-with-claude-code/scripts/update_docs.js
```
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
## Common Patterns
### Plugin Development
Read `plugins.md` for overview, then `plugins-reference.md` for API details.
### MCP Server Setup
Read `mcp.md` for configuration format and examples.
### Hook Configuration
Read `hooks.md` for overview, then `hooks-guide.md` for implementation details.
### Skill Creation
Read `skills.md` for the complete skill authoring guide.
## What This Skill Does NOT Do
- This skill provides **documentation access**, not procedural guidance
- For workflows on **how to build** plugins/skills, use the `extending-claude-code` skill (when available)
- This skill is a **reference library**, not a tutorial
## Red Flags
If you find yourself:
- Guessing about configuration file locations → Read `settings.md`
- Speculating about API structures → Read relevant reference doc
- Unsure about hook names → Read `hooks.md`
- Making assumptions about features → Search the docs first
**Always consult the official documentation before guessing.**

View File

@@ -0,0 +1,209 @@
# Claude Code on Amazon Bedrock
> Learn about configuring Claude Code through Amazon Bedrock, including setup, IAM configuration, and troubleshooting.
## Prerequisites
Before configuring Claude Code with Bedrock, ensure you have:
* An AWS account with Bedrock access enabled
* Access to desired Claude models (e.g., 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
First, ensure you have access to the required Claude models in your AWS 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)
### 2. Configure AWS credentials
Claude Code uses the default AWS SDK credential chain. Set up your credentials using one of these methods:
**Option A: AWS CLI configuration**
```bash theme={null}
aws configure
```
**Option B: Environment variables (access key)**
```bash theme={null}
export AWS_ACCESS_KEY_ID=your-access-key-id
export AWS_SECRET_ACCESS_KEY=your-secret-access-key
export AWS_SESSION_TOKEN=your-session-token
```
**Option C: Environment variables (SSO profile)**
```bash theme={null}
aws sso login --profile=<your-profile-name>
export AWS_PROFILE=your-profile-name
```
**Option D: Bedrock API keys**
```bash theme={null}
export AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key
```
Bedrock API keys provide a simpler authentication method without needing full AWS credentials. [Learn more about Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/).
#### Advanced credential configuration
Claude Code supports automatic credential refresh for AWS SSO and corporate identity providers. Add these settings to your Claude Code settings file (see [Settings](/en/docs/claude-code/settings) for file locations).
When Claude Code detects that your AWS credentials are expired (either locally based on their timestamp or when Bedrock returns a credential error), it will automatically run your configured `awsAuthRefresh` and/or `awsCredentialExport` commands to obtain new credentials before retrying the request.
##### Example configuration
```json theme={null}
{
"awsAuthRefresh": "aws sso login --profile myprofile",
"env": {
"AWS_PROFILE": "myprofile"
}
}
```
##### Configuration settings explained
**`awsAuthRefresh`**: Use this for commands that modify the `.aws` directory (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.
**`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:
```json theme={null}
{
"Credentials": {
"AccessKeyId": "value",
"SecretAccessKey": "value",
"SessionToken": "value"
}
}
```
### 3. Configure Claude Code
Set the following environment variables to enable Bedrock:
```bash theme={null}
# Enable Bedrock integration
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1 # or your preferred region
# Optional: Override the region for the small/fast model (Haiku)
export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2
```
When enabling Bedrock for Claude Code, keep the following in mind:
* `AWS_REGION` is a required environment variable. Claude Code does not read from the `.aws` config file for this setting.
* When using Bedrock, the `/login` and `/logout` commands are disabled since authentication is handled through AWS credentials.
* You can use settings files for environment variables like `AWS_PROFILE` that you don't want to leak to other processes. See [Settings](/en/docs/claude-code/settings) for more information.
### 4. Model configuration
Claude Code uses these default models for Bedrock:
| Model type | Default value |
| :--------------- | :------------------------------------------------- |
| Primary model | `global.anthropic.claude-sonnet-4-5-20250929-v1:0` |
| Small/fast model | `us.anthropic.claude-haiku-4-5-20251001-v1:0` |
<Note>
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`).
</Note>
To customize models, use one of these methods:
```bash theme={null}
# Using inference profile ID
export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-5-20250929-v1:0'
export ANTHROPIC_SMALL_FAST_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'
# Using application inference profile ARN
export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id'
# Optional: Disable prompt caching if needed
export DISABLE_PROMPT_CACHING=1
```
<Note>
[Prompt caching](/en/docs/build-with-claude/prompt-caching) may not be available in all regions
</Note>
### 5. Output token configuration
When using Claude Code with Amazon Bedrock, we recommend the following token settings:
```bash theme={null}
# Recommended output token settings for Bedrock
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096
export MAX_THINKING_TOKENS=1024
```
**Why these values:**
* **`CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096`**: Bedrock's burndown throttling logic sets a minimum of 4096 tokens as the max\_token penalty. Setting this lower won't reduce costs but may cut off long tool uses, causing the Claude Code agent loop to fail persistently. Claude Code typically uses less than 4096 output tokens without extended thinking, but may need this headroom for tasks involving significant file creation or Write tool usage.
* **`MAX_THINKING_TOKENS=1024`**: This provides space for extended thinking without cutting off tool use responses, while still maintaining focused reasoning chains. This balance helps prevent trajectory changes that aren't always helpful for coding tasks specifically.
## IAM configuration
Create an IAM policy with the required permissions for Claude Code:
```json theme={null}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream",
"bedrock:ListInferenceProfiles"
],
"Resource": [
"arn:aws:bedrock:*:*:inference-profile/*",
"arn:aws:bedrock:*:*:application-inference-profile/*"
]
}
]
}
```
For more restrictive permissions, you can limit the Resource to specific inference profile ARNs.
For details, see [Bedrock IAM documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html).
<Note>
We recommend creating a dedicated AWS account for Claude Code to simplify cost tracking and access control.
</Note>
## Troubleshooting
If you encounter region issues:
* Check model availability: `aws bedrock list-inference-profiles --region your-region`
* Switch to a supported region: `export AWS_REGION=us-east-1`
* Consider using inference profiles for cross-region access
If you receive an error "on-demand throughput isnt supported":
* Specify the model as an [inference profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) ID
Claude Code uses the Bedrock [Invoke API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html) and does not support the Converse API.
## Additional resources
* [Bedrock documentation](https://docs.aws.amazon.com/bedrock/)
* [Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)
* [Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)
* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)- [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)

View File

@@ -0,0 +1,87 @@
# Analytics
> View detailed usage insights and productivity metrics for your organization's Claude Code deployment.
Claude Code provides an analytics dashboard that helps organizations understand developer usage patterns, track productivity metrics, and optimize their Claude Code adoption.
<Note>
Analytics are currently available only for organizations using Claude Code with the Claude API through the Claude Console.
</Note>
## Access analytics
Navigate to the analytics dashboard at [console.anthropic.com/claude-code](https://console.anthropic.com/claude-code).
### Required roles
* **Primary Owner**
* **Owner**
* **Billing**
* **Admin**
* **Developer**
<Note>
Users with **User**, **Claude Code User** or **Membership Admin** roles cannot access analytics.
</Note>
## Available metrics
### Lines of code accepted
Total lines of code written by Claude Code that users have accepted in their sessions.
* Excludes rejected code suggestions
* Doesn't track subsequent deletions
### Suggestion accept rate
Percentage of times users accept code editing tool usage, including:
* Edit
* Write
* NotebookEdit
### Activity
**users**: Number of active users in a given day (number on left Y-axis)
**sessions**: Number of active sessions in a given day (number on right Y-axis)
### Spend
**users**: Number of active users in a given day (number on left Y-axis)
**spend**: Total dollars spent in a given day (number on right Y-axis)
### Team insights
**Members**: All users who have authenticated to Claude Code
* API key users are displayed by **API key identifier**
* OAuth users are displayed by **email address**
**Spend this month:** Per-user total spend for the current month.
**Lines this month:** Per-user total of accepted code lines for the current month.
## Using analytics effectively
### Monitor adoption
Track team member status to identify:
* Active users who can share best practices
* Overall adoption trends across your organization
### Measure productivity
Tool acceptance rates and code metrics help you:
* Understand developer satisfaction with Claude Code suggestions
* Track code generation effectiveness
* Identify opportunities for training or process improvements
## 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

View File

@@ -0,0 +1,65 @@
# Checkpointing
> Automatically track and rewind Claude's edits to quickly recover from unwanted changes.
Claude Code automatically tracks Claude's file edits as you work, allowing you to quickly undo changes and rewind to previous states if anything gets off track.
## How checkpoints work
As you work with Claude, checkpointing automatically captures the state of your code before each edit. This safety net lets you pursue ambitious, wide-scale tasks knowing you can always return to a prior code state.
### Automatic tracking
Claude Code tracks all changes made by its file editing tools:
* Every user prompt creates a new checkpoint
* Checkpoints persist across sessions, so you can access them in resumed conversations
* Automatically cleaned up along with sessions after 30 days (configurable)
### Rewinding changes
Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open up the rewind menu. You can choose to restore:
* **Conversation only**: Rewind to a user message while keeping code changes
* **Code only**: Revert file changes while keeping the conversation
* **Both code and conversation**: Restore both to a prior point in the session
## Common use cases
Checkpoints are particularly useful when:
* **Exploring alternatives**: Try different implementation approaches without losing your starting point
* **Recovering from mistakes**: Quickly undo changes that introduced bugs or broke functionality
* **Iterating on features**: Experiment with variations knowing you can revert to working states
## Limitations
### Bash command changes not tracked
Checkpointing does not track files modified by bash commands. For example, if Claude Code runs:
```bash theme={null}
rm file.txt
mv old.txt new.txt
cp source.txt dest.txt
```
These file modifications cannot be undone through rewind. Only direct file edits made through Claude's file editing tools are tracked.
### External changes not tracked
Checkpointing only tracks files that have been edited within the current session. Manual changes you make to files outside of Claude Code and edits from other concurrent sessions are normally not captured, unless they happen to modify the same files as the current session.
### Not a replacement for version control
Checkpoints are designed for quick, session-level recovery. For permanent version history and collaboration:
* Continue using version control (ex. Git) for commits, branches, and long-term history
* Checkpoints complement but don't replace proper version control
* Think of checkpoints as "local undo" and Git as "permanent history"
## See also
* [Interactive mode](/en/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

View File

@@ -0,0 +1,89 @@
# CLI reference
> Complete reference for Claude Code command-line interface, including commands and flags.
## CLI commands
| Command | Description | Example |
| :--------------------------------- | :--------------------------------------------- | :----------------------------------------------------------------- |
| `claude` | Start interactive REPL | `claude` |
| `claude "query"` | Start REPL with initial prompt | `claude "explain this project"` |
| `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` |
| `cat file \| claude -p "query"` | Process piped content | `cat logs.txt \| claude -p "explain"` |
| `claude -c` | Continue most recent conversation | `claude -c` |
| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` |
| `claude -r "<session-id>" "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). |
## 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` |
<Tip>
The `--output-format json` flag is particularly useful for scripting and
automation, allowing you to parse Claude's responses programmatically.
</Tip>
### Agents flag format
The `--agents` flag accepts a JSON object that defines one or more custom subagents. Each subagent requires a unique name (as the key) and a definition object with the following fields:
| Field | Required | Description |
| :------------ | :------- | :-------------------------------------------------------------------------------------------------------------- |
| `description` | Yes | Natural language description of when the subagent should be invoked |
| `prompt` | Yes | The system prompt that guides the subagent's behavior |
| `tools` | No | Array of specific tools the subagent can use (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 |
Example:
```bash theme={null}
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
},
"debugger": {
"description": "Debugging specialist for errors and test failures.",
"prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
}
}'
```
For more details on creating and using subagents, see the [subagents documentation](/en/docs/claude-code/sub-agents).
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).
## 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

View File

@@ -0,0 +1,949 @@
# Common workflows
> Learn about common workflows with Claude Code.
Each task in this document includes clear instructions, example commands, and best practices to help you get the most from Claude Code.
## Understand new codebases
### Get a quick codebase overview
Suppose you've just joined a new project and need to understand its structure quickly.
<Steps>
<Step title="Navigate to the project root directory">
```bash theme={null}
cd /path/to/project
```
</Step>
<Step title="Start Claude Code">
```bash theme={null}
claude
```
</Step>
<Step title="Ask for a high-level overview">
```
> give me an overview of this codebase
```
</Step>
<Step title="Dive deeper into specific components">
```
> explain the main architecture patterns used here
```
```
> what are the key data models?
```
```
> how is authentication handled?
```
</Step>
</Steps>
<Tip>
Tips:
* Start with broad questions, then narrow down to specific areas
* Ask about coding conventions and patterns used in the project
* Request a glossary of project-specific terms
</Tip>
### Find relevant code
Suppose you need to locate code related to a specific feature or functionality.
<Steps>
<Step title="Ask Claude to find relevant files">
```
> find the files that handle user authentication
```
</Step>
<Step title="Get context on how components interact">
```
> how do these authentication files work together?
```
</Step>
<Step title="Understand the execution flow">
```
> trace the login process from front-end to database
```
</Step>
</Steps>
<Tip>
Tips:
* Be specific about what you're looking for
* Use domain language from the project
</Tip>
***
## Fix bugs efficiently
Suppose you've encountered an error message and need to find and fix its source.
<Steps>
<Step title="Share the error with Claude">
```
> I'm seeing an error when I run npm test
```
</Step>
<Step title="Ask for fix recommendations">
```
> suggest a few ways to fix the @ts-ignore in user.ts
```
</Step>
<Step title="Apply the fix">
```
> update user.ts to add the null check you suggested
```
</Step>
</Steps>
<Tip>
Tips:
* Tell Claude the command to reproduce the issue and get a stack trace
* Mention any steps to reproduce the error
* Let Claude know if the error is intermittent or consistent
</Tip>
***
## Refactor code
Suppose you need to update old code to use modern patterns and practices.
<Steps>
<Step title="Identify legacy code for refactoring">
```
> find deprecated API usage in our codebase
```
</Step>
<Step title="Get refactoring recommendations">
```
> suggest how to refactor utils.js to use modern JavaScript features
```
</Step>
<Step title="Apply the changes safely">
```
> refactor utils.js to use ES2024 features while maintaining the same behavior
```
</Step>
<Step title="Verify the refactoring">
```
> run tests for the refactored code
```
</Step>
</Steps>
<Tip>
Tips:
* Ask Claude to explain the benefits of the modern approach
* Request that changes maintain backward compatibility when needed
* Do refactoring in small, testable increments
</Tip>
***
## Use specialized subagents
Suppose you want to use specialized AI subagents to handle specific tasks more effectively.
<Steps>
<Step title="View available subagents">
```
> /agents
```
This shows all available subagents and lets you create new ones.
</Step>
<Step title="Use subagents automatically">
Claude Code will automatically delegate appropriate tasks to specialized subagents:
```
> review my recent code changes for security issues
```
```
> run all tests and fix any failures
```
</Step>
<Step title="Explicitly request specific subagents">
```
> use the code-reviewer subagent to check the auth module
```
```
> have the debugger subagent investigate why users can't log in
```
</Step>
<Step title="Create custom subagents for your workflow">
```
> /agents
```
Then select "Create New subagent" and follow the prompts to define:
* Subagent type (e.g., `api-designer`, `performance-optimizer`)
* When to use it
* Which tools it can access
* Its specialized system prompt
</Step>
</Steps>
<Tip>
Tips:
* Create project-specific subagents in `.claude/agents/` for team sharing
* Use descriptive `description` fields to enable automatic delegation
* Limit tool access to what each subagent actually needs
* Check the [subagents documentation](/en/docs/claude-code/sub-agents) for detailed examples
</Tip>
***
## 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.
### When to use Plan Mode
* **Multi-step implementation**: When your feature requires making edits to many files
* **Code exploration**: When you want to research the codebase thoroughly before changing anything
* **Interactive development**: When you want to iterate on the direction with Claude
### How to use Plan Mode
**Turn on Plan Mode during a session**
You can switch into Plan Mode during a session using **Shift+Tab** to cycle through permission modes.
If you are in Normal Mode, **Shift+Tab** 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`.
**Start a new session in Plan Mode**
To start a new session in Plan Mode, use the `--permission-mode plan` flag:
```bash theme={null}
claude --permission-mode plan
```
**Run "headless" queries in Plan Mode**
You can also run a query in Plan Mode directly with `-p` (i.e., in ["headless mode"](/en/docs/claude-code/sdk/sdk-headless)):
```bash theme={null}
claude --permission-mode plan -p "Analyze the authentication system and suggest improvements"
```
### Example: Planning a complex refactor
```bash theme={null}
claude --permission-mode plan
```
```
> I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.
```
Claude will analyze the current implementation and create a comprehensive plan. Refine with follow-ups:
```
> What about backward compatibility?
> How should we handle database migration?
```
### Configure Plan Mode as default
```json theme={null}
// .claude/settings.json
{
"permissions": {
"defaultMode": "plan"
}
}
```
See [settings documentation](/en/docs/claude-code/settings#available-settings) for more configuration options.
***
## Work with tests
Suppose you need to add tests for uncovered code.
<Steps>
<Step title="Identify untested code">
```
> find functions in NotificationsService.swift that are not covered by tests
```
</Step>
<Step title="Generate test scaffolding">
```
> add tests for the notification service
```
</Step>
<Step title="Add meaningful test cases">
```
> add test cases for edge conditions in the notification service
```
</Step>
<Step title="Run and verify tests">
```
> run the new tests and fix any failures
```
</Step>
</Steps>
<Tip>
Tips:
* Ask for tests that cover edge cases and error conditions
* Request both unit and integration tests when appropriate
* Have Claude explain the testing strategy
</Tip>
***
## Create pull requests
Suppose you need to create a well-documented pull request for your changes.
<Steps>
<Step title="Summarize your changes">
```
> summarize the changes I've made to the authentication module
```
</Step>
<Step title="Generate a PR with Claude">
```
> create a pr
```
</Step>
<Step title="Review and refine">
```
> enhance the PR description with more context about the security improvements
```
</Step>
<Step title="Add testing details">
```
> add information about how these changes were tested
```
</Step>
</Steps>
<Tip>
Tips:
* Ask Claude directly to make a PR for you
* Review Claude's generated PR before submitting
* Ask Claude to highlight potential risks or considerations
</Tip>
## Handle documentation
Suppose you need to add or update documentation for your code.
<Steps>
<Step title="Identify undocumented code">
```
> find functions without proper JSDoc comments in the auth module
```
</Step>
<Step title="Generate documentation">
```
> add JSDoc comments to the undocumented functions in auth.js
```
</Step>
<Step title="Review and enhance">
```
> improve the generated documentation with more context and examples
```
</Step>
<Step title="Verify documentation">
```
> check if the documentation follows our project standards
```
</Step>
</Steps>
<Tip>
Tips:
* Specify the documentation style you want (JSDoc, docstrings, etc.)
* Ask for examples in the documentation
* Request documentation for public APIs, interfaces, and complex logic
</Tip>
***
## Work with images
Suppose you need to work with images in your codebase, and you want Claude's help analyzing image content.
<Steps>
<Step title="Add an image to the conversation">
You can use any of these methods:
1. Drag and drop an image into the Claude Code window
2. Copy an image and paste it into the CLI with ctrl+v (Do not use cmd+v)
3. Provide an image path to Claude. E.g., "Analyze this image: /path/to/your/image.png"
</Step>
<Step title="Ask Claude to analyze the image">
```
> What does this image show?
```
```
> Describe the UI elements in this screenshot
```
```
> Are there any problematic elements in this diagram?
```
</Step>
<Step title="Use images for context">
```
> Here's a screenshot of the error. What's causing it?
```
```
> This is our current database schema. How should we modify it for the new feature?
```
</Step>
<Step title="Get code suggestions from visual content">
```
> Generate CSS to match this design mockup
```
```
> What HTML structure would recreate this component?
```
</Step>
</Steps>
<Tip>
Tips:
* Use images when text descriptions would be unclear or cumbersome
* Include screenshots of errors, UI designs, or diagrams for better context
* You can work with multiple images in a conversation
* Image analysis works with diagrams, screenshots, mockups, and more
</Tip>
***
## Reference files and directories
Use @ to quickly include files or directories without waiting for Claude to read them.
<Steps>
<Step title="Reference a single file">
```
> Explain the logic in @src/utils/auth.js
```
This includes the full content of the file in the conversation.
</Step>
<Step title="Reference a directory">
```
> What's the structure of @src/components?
```
This provides a directory listing with file information.
</Step>
<Step title="Reference MCP resources">
```
> 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.
</Step>
</Steps>
<Tip>
Tips:
* File paths can be relative or absolute
* @ file references add CLAUDE.md in the file's directory and parent directories to context
* Directory references show file listings, not contents
* You can reference multiple files in a single message (e.g., "@file1.js and @file2.js")
</Tip>
***
## Use extended thinking
Suppose you're working on complex architectural decisions, challenging bugs, or planning multi-step implementations that require deep reasoning.
<Note>
[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.
</Note>
<Steps>
<Step title="Provide context and ask Claude to think">
```
> 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.
</Step>
<Step title="Refine the thinking with follow-up prompts">
```
> think about potential security vulnerabilities in this approach
```
```
> think hard about edge cases we should handle
```
</Step>
</Steps>
<Tip>
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:
* Planning complex architectural changes
* Debugging intricate issues
* Creating implementation plans for new features
* Understanding complex codebases
* Evaluating tradeoffs between different approaches
Use `Tab` to toggle Thinking on and off during a session.
The way you prompt for thinking results in varying levels of thinking depth:
* "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).
</Tip>
<Note>
Claude will display its thinking process as italic gray text above the
response.
</Note>
***
## 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.
Claude Code provides two options for resuming previous conversations:
* `--continue` to automatically continue the most recent conversation
* `--resume` to display a conversation picker
<Steps>
<Step title="Continue the most recent conversation">
```bash theme={null}
claude --continue
```
This immediately resumes your most recent conversation without any prompts.
</Step>
<Step title="Continue in non-interactive mode">
```bash theme={null}
claude --continue --print "Continue with my task"
```
Use `--print` with `--continue` to resume the most recent conversation in non-interactive mode, perfect for scripts or automation.
</Step>
<Step title="Show conversation picker">
```bash theme={null}
claude --resume
```
This displays an interactive conversation selector with a clean list view showing:
* Session summary (or initial prompt)
* Metadata: time elapsed, message count, and git branch
Use arrow keys to navigate and press Enter to select a conversation. Press Esc to exit.
</Step>
</Steps>
<Tip>
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
* The resumed conversation starts with the same model and configuration as the original
How it works:
1. **Conversation Storage**: All conversations are automatically saved locally with their full message history
2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context
3. **Tool State**: Tool usage and results from the previous conversation are preserved
4. **Context Restoration**: The conversation resumes with all previous context intact
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"
```
</Tip>
***
## Run parallel Claude Code sessions with Git worktrees
Suppose you need to work on multiple tasks simultaneously with complete code isolation between Claude Code instances.
<Steps>
<Step title="Understand Git worktrees">
Git worktrees allow you to check out multiple branches from the same
repository into separate directories. Each worktree has its own working
directory with isolated files, while sharing the same Git history. Learn
more in the [official Git worktree
documentation](https://git-scm.com/docs/git-worktree).
</Step>
<Step title="Create a new worktree">
```bash theme={null}
# Create a new worktree with a new branch
git worktree add ../project-feature-a -b feature-a
# Or create a worktree with an existing branch
git worktree add ../project-bugfix bugfix-123
```
This creates a new directory with a separate working copy of your repository.
</Step>
<Step title="Run Claude Code in each worktree">
```bash theme={null}
# Navigate to your worktree
cd ../project-feature-a
# Run Claude Code in this isolated environment
claude
```
</Step>
<Step title="Run Claude in another worktree">
```bash theme={null}
cd ../project-bugfix
claude
```
</Step>
<Step title="Manage your worktrees">
```bash theme={null}
# List all worktrees
git worktree list
# Remove a worktree when done
git worktree remove ../project-feature-a
```
</Step>
</Steps>
<Tip>
Tips:
* Each worktree has its own independent file state, making it perfect for parallel Claude Code sessions
* Changes made in one worktree won't affect others, preventing Claude instances from interfering with each other
* All worktrees share the same Git history and remote connections
* For long-running tasks, you can have Claude working in one worktree while you continue development in another
* Use descriptive directory names to easily identify which task each worktree is for
* Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include:
* JavaScript projects: Running dependency installation (`npm install`, `yarn`)
* Python projects: Setting up virtual environments or installing with package managers
* Other languages: Following your project's standard setup process
</Tip>
***
## Use Claude as a unix-style utility
### Add Claude to your verification process
Suppose you want to use Claude Code as a linter or code reviewer.
**Add Claude to your build script:**
```json theme={null}
// package.json
{
...
"scripts": {
...
"lint:claude": "claude -p 'you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.'"
}
}
```
<Tip>
Tips:
* Use Claude for automated code review in your CI/CD pipeline
* Customize the prompt to check for specific issues relevant to your project
* Consider creating multiple scripts for different types of verification
</Tip>
### Pipe in, pipe out
Suppose you want to pipe data into Claude, and get back data in a structured format.
**Pipe data through Claude:**
```bash theme={null}
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
```
<Tip>
Tips:
* Use pipes to integrate Claude into existing shell scripts
* Combine with other Unix tools for powerful workflows
* Consider using --output-format for structured output
</Tip>
### Control output format
Suppose you need Claude's output in a specific format, especially when integrating Claude Code into scripts or other tools.
<Steps>
<Step title="Use text format (default)">
```bash theme={null}
cat data.txt | claude -p 'summarize this data' --output-format text > summary.txt
```
This outputs just Claude's plain text response (default behavior).
</Step>
<Step title="Use JSON format">
```bash theme={null}
cat code.py | claude -p 'analyze this code for bugs' --output-format json > analysis.json
```
This outputs a JSON array of messages with metadata including cost and duration.
</Step>
<Step title="Use streaming JSON format">
```bash theme={null}
cat log.txt | claude -p 'parse this log file for errors' --output-format stream-json
```
This outputs a series of JSON objects in real-time as Claude processes the request. Each message is a valid JSON object, but the entire output is not valid JSON if concatenated.
</Step>
</Steps>
<Tip>
Tips:
* Use `--output-format text` for simple integrations where you just need Claude's response
* Use `--output-format json` when you need the full conversation log
* Use `--output-format stream-json` for real-time output of each conversation turn
</Tip>
***
## Create custom slash commands
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.
### Create project-specific commands
Suppose you want to create reusable slash commands for your project that all team members can use.
<Steps>
<Step title="Create a commands directory in your project">
```bash theme={null}
mkdir -p .claude/commands
```
</Step>
<Step title="Create a Markdown file for each command">
```bash theme={null}
echo "Analyze the performance of this code and suggest three specific optimizations:" > .claude/commands/optimize.md
```
</Step>
<Step title="Use your custom command in Claude Code">
```
> /optimize
```
</Step>
</Steps>
<Tip>
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)
* 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
</Tip>
### Add command arguments with \$ARGUMENTS
Suppose you want to create flexible slash commands that can accept additional input from users.
<Steps>
<Step title="Create a command file with the $ARGUMENTS placeholder">
```bash theme={null}
echo 'Find and fix issue #$ARGUMENTS. Follow these steps: 1.
Understand the issue described in the ticket 2. Locate the relevant code in
our codebase 3. Implement a solution that addresses the root cause 4. Add
appropriate tests 5. Prepare a concise PR description' >
.claude/commands/fix-issue.md
```
</Step>
<Step title="Use the command with an issue number">
In your Claude session, use the command with arguments.
```
> /fix-issue 123
```
This will replace \$ARGUMENTS with "123" in the prompt.
</Step>
</Steps>
<Tip>
Tips:
* The \$ARGUMENTS placeholder is replaced with any text that follows the command
* You can position \$ARGUMENTS anywhere in your command template
* Other useful applications: generating test cases for specific functions, creating documentation for components, reviewing code in particular files, or translating content to specified languages
</Tip>
### Create personal slash commands
Suppose you want to create personal slash commands that work across all your projects.
<Steps>
<Step title="Create a commands directory in your home folder">
```bash theme={null}
mkdir -p ~/.claude/commands
```
</Step>
<Step title="Create a Markdown file for each command">
```bash theme={null}
echo "Review this code for security vulnerabilities, focusing on:" >
~/.claude/commands/security-review.md
```
</Step>
<Step title="Use your personal custom command">
```
> /security-review
```
</Step>
</Steps>
<Tip>
Tips:
* Personal commands show "(user)" in their description when listed with `/help`
* Personal commands are only available to you and not shared with your team
* Personal commands work across all your projects
* You can use these for consistent workflows across different codebases
</Tip>
***
## Ask Claude about its capabilities
Claude has built-in access to its documentation and can answer questions about its own features and limitations.
### Example questions
```
> can Claude Code create pull requests?
```
```
> how does Claude Code handle permissions?
```
```
> what slash commands are available?
```
```
> how do I use MCP with Claude Code?
```
```
> how do I configure Claude Code for Amazon Bedrock?
```
```
> what are the limitations of Claude Code?
```
<Note>
Claude provides documentation-based answers to these questions. For executable examples and hands-on demonstrations, refer to the specific workflow sections above.
</Note>
<Tip>
Tips:
* Claude always has access to the latest Claude Code documentation, regardless of the version you're using
* Ask specific questions to get detailed answers
* Claude can explain complex features like MCP integration, enterprise configurations, and advanced workflows
</Tip>
***
## Next steps
<Card title="Claude Code reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">
Clone our development container reference implementation.
</Card>

View File

@@ -0,0 +1,131 @@
# Manage costs effectively
> Learn how to track and optimize token usage and costs when using Claude Code.
Claude Code consumes tokens for each interaction. The average cost is \$6 per developer per day, with daily costs remaining below \$12 for 90% of users.
For team usage, Claude Code charges by API token consumption. On average, Claude Code costs \~\$100-200/developer per month with Sonnet 4.5 though there is large variance depending on how many instances users are running and whether they're using it in automation.
## Track your costs
### Using the `/cost` command
<Note>
The `/cost` command is not intended for Claude Max and Pro subscribers.
</Note>
The `/cost` command provides detailed token usage statistics for your current session:
```
Total cost: $0.55
Total duration (API): 6m 19.7s
Total duration (wall): 6h 33m 10.2s
Total code changes: 0 lines added, 0 lines removed
```
### Additional tracking options
Check [historical usage](https://support.claude.com/en/articles/9534590-cost-and-usage-reporting-in-console) in the Claude Console (requires Admin or Billing role) and set [workspace spend limits](https://support.claude.com/en/articles/9796807-creating-and-managing-workspaces) for the Claude Code workspace (requires Admin role).
<Note>
When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization. You cannot create API keys for this workspace - it is exclusively for Claude Code authentication and usage.
</Note>
## Managing costs for teams
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.
### Rate limit recommendations
When setting up Claude Code for teams, consider these Token Per Minute (TPM) and Request Per Minute (RPM) per-user recommendations based on your organization size:
| Team size | TPM per user | RPM per user |
| ------------- | ------------ | ------------ |
| 1-5 users | 200k-300k | 5-7 |
| 5-20 users | 100k-150k | 2.5-3.5 |
| 20-50 users | 50k-75k | 1.25-1.75 |
| 50-100 users | 25k-35k | 0.62-0.87 |
| 100-500 users | 15k-20k | 0.37-0.47 |
| 500+ users | 10k-15k | 0.25-0.35 |
For example, if you have 200 users, you might request 20k TPM for each user, or 4 million total TPM (200\*20,000 = 4 million).
The TPM per user decreases as team size grows because we expect fewer users to use Claude Code concurrently in larger organizations. These rate limits apply at the organization level, not per individual user, which means individual users can temporarily consume more than their calculated share when others aren't actively using the service.
<Note>
If you anticipate scenarios with unusually high concurrent usage (such as live training sessions with large groups), you may need higher TPM allocations per user.
</Note>
## Reduce token usage
* **Compact conversations:**
* Claude uses auto-compact by default when context exceeds 95% capacity
* 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`
* Customize compaction by adding to CLAUDE.md:
```markdown theme={null}
# Summary instructions
When you are using compact, please focus on test output and code changes
```
* **Write specific queries:** Avoid vague requests that trigger unnecessary scanning
* **Break down complex tasks:** Split large tasks into focused interactions
* **Clear history between tasks:** Use `/clear` to reset context
Costs can vary significantly based on:
* Size of codebase being analyzed
* Complexity of queries
* Number of files being searched or modified
* Length of conversation history
* Frequency of compacting conversations
## Background token usage
Claude Code uses tokens for some background functionality even when idle:
* **Conversation summarization**: Background jobs that summarize previous conversations for the `claude --resume` feature
* **Command processing**: Some commands like `/cost` may generate requests to check status
These background processes consume a small amount of tokens (typically under \$0.04 per session) even without active interaction.
## Tracking version changes and updates
### Current version information
To check your current Claude Code version and installation details:
```bash theme={null}
claude doctor
```
This command shows your version, installation type, and system information.
### Understanding changes in Claude Code behavior
Claude Code regularly receives updates that may change how features work, including cost reporting:
* **Version tracking**: Use `claude doctor` to see your current version
* **Behavior changes**: Features like `/cost` may display information differently across versions
* **Documentation access**: Claude always has access to the latest documentation, which can help explain current feature behavior
### When cost reporting changes
If you notice changes in how costs are displayed (such as the `/cost` command showing different information):
1. **Verify your version**: Run `claude doctor` to confirm your current version
2. **Consult documentation**: Ask Claude directly about current feature behavior, as it has access to up-to-date documentation
3. **Contact support**: For specific billing questions, contact Anthropic support through your Console account
<Note>
For team deployments, we recommend starting with a small pilot group to
establish usage patterns before wider rollout.
</Note>

View File

@@ -0,0 +1,76 @@
# Data usage
> Learn about Anthropic's data usage policies for Claude
## Data policies
### 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.
**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)).
### Development Partner Program
If you explicitly opt in to methods to provide us with materials to train on, such as via the [Development Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program), we may use those materials provided to train our models. An organization admin can expressly opt-in to the Development Partner Program for their organization. Note that this program is available only for Anthropic first-party API, and not for Bedrock or Vertex users.
### Feedback using the `/bug` command
If you choose to send us feedback about Claude Code using the `/bug` command, we may use your feedback to improve our products and services. Transcripts shared via `/bug` are retained for 5 years.
### Data retention
Anthropic retains Claude Code data based on your account type and preferences.
**Consumer users (Free, Pro, and Max plans)**:
* Users who allow data use for model improvement: 5-year retention period to support model development and safety improvements
* Users who don't allow data use for model improvement: 30-day retention period
* Privacy settings can be changed at any time at [claude.ai/settings/data-privacy-controls](claude.ai/settings/data-privacy-controls).
**Commercial users (Team, Enterprise, and API)**:
* Standard: 30-day retention period
* Zero data retention: Available with appropriately configured API keys - Claude Code will not retain chat transcripts on servers
* Local caching: Claude Code clients may store sessions locally for up to 30 days to enable session resumption (configurable)
Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/).
For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy).
## Data flow and dependencies
<img src="https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=4b30069d702719e7bfb974eaaafab21c" alt="Claude Code data flow diagram" data-og-width="1597" width="1597" data-og-height="1285" height="1285" data-path="images/claude-code-data-flow.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=280&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=067676caa12f89051cb193e6b3f7d0a0 280w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=560&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=5506197deff927f54f2fb5a349f358a8 560w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=840&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=bb4febe7974dde5b76b88744f89ab472 840w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=1100&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=b51af3074f87b33ccc342aaad655dcbf 1100w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=1650&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=8fd96f1dde615877d4e4bbe1874af12d 1650w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=2500&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=056deded541ec30e9b67a67d620f6aaf 2500w" />
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).
## Telemetry services
Claude Code connects from users' machines to the Statsig service to log operational metrics such as latency, reliability, and usage patterns. This logging does not include any code or file paths. Data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Statsig security documentation](https://www.statsig.com/trust/security). To opt out of Statsig telemetry, set the `DISABLE_TELEMETRY` environment variable.
Claude Code connects from users' machines to Sentry for operational error logging. The data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Sentry security documentation](https://sentry.io/security/). To opt out of error logging, set the `DISABLE_ERROR_REPORTING` environment variable.
When users run the `/bug` command, a copy of their full conversation history including code is sent to Anthropic. The data is encrypted in transit and at rest. Optionally, a Github issue is created in our public repository. To opt out of bug reporting, set the `DISABLE_BUG_COMMAND` environment variable.
## Default behaviors by API provider
By default, we disable all non-essential traffic (including error reporting, telemetry, and bug reporting functionality) when using Bedrock or Vertex. You can also opt out of all of these at once by setting the `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` environment variable. Here are the full default behaviors:
| Service | Claude API | Vertex API | Bedrock API |
| ------------------------------- | -------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ |
| **Statsig (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |
| **Sentry (Errors)** | Default on.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |
| **Claude API (`/bug` reports)** | Default on.<br />`DISABLE_BUG_COMMAND=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |
All environment variables can be checked into `settings.json` ([read more](/en/docs/claude-code/settings)).

View File

@@ -0,0 +1,77 @@
# Development containers
> Learn about the Claude Code development container for teams that need consistent, secure environments.
The reference [devcontainer setup](https://github.com/anthropics/claude-code/tree/main/.devcontainer) and associated [Dockerfile](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) offer a preconfigured development container that you can use as is, or customize for your needs. This devcontainer works with the Visual Studio Code [Dev Containers extension](https://code.visualstudio.com/docs/devcontainers/containers) and similar tools.
The container's enhanced security measures (isolation and firewall rules) allow you to run `claude --dangerously-skip-permissions` to bypass permission prompts for unattended operation.
<Warning>
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.
We recommend only using devcontainers when developing with trusted repositories.
Always maintain good security practices and monitor Claude's activities.
</Warning>
## Key features
* **Production-ready Node.js**: Built on Node.js 20 with essential development dependencies
* **Security by design**: Custom firewall restricting network access to only necessary services
* **Developer-friendly tools**: Includes git, ZSH with productivity enhancements, fzf, and more
* **Seamless VS Code integration**: Pre-configured extensions and optimized settings
* **Session persistence**: Preserves command history and configurations between container restarts
* **Works everywhere**: Compatible with macOS, Windows, and Linux development environments
## Getting started in 4 steps
1. Install VS Code and the Remote - Containers extension
2. Clone the [Claude Code reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository
3. Open the repository in VS Code
4. When prompted, click "Reopen in Container" (or use Command Palette: Cmd+Shift+P → "Remote-Containers: Reopen in Container")
## Configuration breakdown
The devcontainer setup consists of three primary components:
* [**devcontainer.json**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json): Controls container settings, extensions, and volume mounts
* [**Dockerfile**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile): Defines the container image and installed tools
* [**init-firewall.sh**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh): Establishes network security rules
## Security features
The container implements a multi-layered security approach with its firewall configuration:
* **Precise access control**: Restricts outbound connections to whitelisted domains only (npm registry, GitHub, Claude API, etc.)
* **Allowed outbound connections**: The firewall permits outbound DNS and SSH connections
* **Default-deny policy**: Blocks all other external network access
* **Startup verification**: Validates firewall rules when the container initializes
* **Isolation**: Creates a secure development environment separated from your main system
## Customization options
The devcontainer configuration is designed to be adaptable to your needs:
* Add or remove VS Code extensions based on your workflow
* Modify resource allocations for different hardware environments
* Adjust network access permissions
* Customize shell configurations and developer tooling
## Example use cases
### Secure client work
Use devcontainers to isolate different client projects, ensuring code and credentials never mix between environments.
### Team onboarding
New team members can get a fully configured development environment in minutes, with all necessary tools and settings pre-installed.
### Consistent CI/CD environments
Mirror your devcontainer configuration in CI/CD pipelines to ensure development and production environments match.
## Related resources
* [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)
* [Claude Code security best practices](/en/docs/claude-code/security)
* [Enterprise network configuration](/en/docs/claude-code/network-config)

View File

@@ -0,0 +1,669 @@
# Claude Code GitHub Actions
> Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions
Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards.
<Note>
Claude Code GitHub Actions is built on top of the [Claude Code
SDK](/en/docs/claude-code/sdk), which enables programmatic integration of
Claude Code into your applications. You can use the SDK to build custom
automation workflows beyond GitHub Actions.
</Note>
## Why use Claude Code GitHub Actions?
* **Instant PR creation**: Describe what you need, and Claude creates a complete PR with all necessary changes
* **Automated code implementation**: Turn issues into working code with a single command
* **Follows your standards**: Claude respects your `CLAUDE.md` guidelines and existing code patterns
* **Simple setup**: Get started in minutes with our installer and API key
* **Secure by default**: Your code stays on Github's runners
## What can Claude do?
Claude Code provides a powerful GitHub Action that transforms how you work with code:
### Claude Code Action
This GitHub Action allows you to run Claude Code within your GitHub Actions workflows. You can use this to build any custom workflow on top of Claude Code.
[View repository →](https://github.com/anthropics/claude-code-action)
## Setup
## Quick setup
The easiest way to set up this action is through Claude Code in the terminal. Just open claude and run `/install-github-app`.
This command will guide you through setting up the GitHub app and required secrets.
<Note>
* You must be a repository admin to install the GitHub app and add secrets
* The GitHub app will request read & write permissions for Contents, Issues, and Pull requests
* This quickstart method is only available for direct Claude API users. If
you're using AWS Bedrock or Google Vertex AI, please see the [Using with AWS
Bedrock & Google Vertex AI](#using-with-aws-bedrock-%26-google-vertex-ai)
section.
</Note>
## Manual setup
If the `/install-github-app` command fails or you prefer manual setup, please follow these manual setup instructions:
1. **Install the Claude GitHub app** to your repository: [https://github.com/apps/claude](https://github.com/apps/claude)
The Claude GitHub app requires the following repository permissions:
* **Contents**: Read & write (to modify repository files)
* **Issues**: Read & write (to respond to issues)
* **Pull requests**: Read & write (to create PRs and push changes)
For more details on security and permissions, see the [security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md).
2. **Add ANTHROPIC\_API\_KEY** to your repository secrets ([Learn how to use secrets in GitHub Actions](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions))
3. **Copy the workflow file** from [examples/claude.yml](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) into your repository's `.github/workflows/`
<Tip>
After completing either the quickstart or manual setup, test the action by
tagging `@claude` in an issue or PR comment!
</Tip>
## Upgrading from Beta
<Warning>
Claude Code GitHub Actions v1.0 introduces breaking changes that require updating your workflow files in order to upgrade to v1.0 from the beta version.
</Warning>
If you're currently using the beta version of Claude Code GitHub Actions, we recommend that you update your workflows to use the GA version. The new version simplifies configuration while adding powerful new features like automatic mode detection.
### Essential changes
All beta users must make these changes to their workflow files in order to upgrade:
1. **Update the action version**: Change `@beta` to `@v1`
2. **Remove mode configuration**: Delete `mode: "tag"` or `mode: "agent"` (now auto-detected)
3. **Update prompt inputs**: Replace `direct_prompt` with `prompt`
4. **Move CLI options**: Convert `max_turns`, `model`, `custom_instructions`, etc. to `claude_args`
### Breaking Changes Reference
| Old Beta Input | New v1.0 Input |
| --------------------- | -------------------------------- |
| `mode` | *(Removed - auto-detected)* |
| `direct_prompt` | `prompt` |
| `override_prompt` | `prompt` with GitHub variables |
| `custom_instructions` | `claude_args: --system-prompt` |
| `max_turns` | `claude_args: --max-turns` |
| `model` | `claude_args: --model` |
| `allowed_tools` | `claude_args: --allowedTools` |
| `disallowed_tools` | `claude_args: --disallowedTools` |
| `claude_env` | `settings` JSON format |
### Before and After Example
**Beta version:**
```yaml theme={null}
- uses: anthropics/claude-code-action@beta
with:
mode: "tag"
direct_prompt: "Review this PR for security issues"
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
custom_instructions: "Follow our coding standards"
max_turns: "10"
model: "claude-3-5-sonnet-20241022"
```
**GA version (v1.0):**
```yaml theme={null}
- uses: anthropics/claude-code-action@v1
with:
prompt: "Review this PR for security issues"
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
claude_args: |
--system-prompt "Follow our coding standards"
--max-turns 10
--model claude-sonnet-4-5-20250929
```
<Tip>
The action now automatically detects whether to run in interactive mode (responds to `@claude` mentions) or automation mode (runs immediately with a prompt) based on your configuration.
</Tip>
## Example use cases
Claude Code GitHub Actions can help you with a variety of tasks. The [examples directory](https://github.com/anthropics/claude-code-action/tree/main/examples) contains ready-to-use workflows for different scenarios.
### Basic workflow
```yaml theme={null}
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
jobs:
claude:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Responds to @claude mentions in comments
```
### Using slash commands
```yaml theme={null}
name: Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "/review"
claude_args: "--max-turns 5"
```
### Custom automation with prompts
```yaml theme={null}
name: Daily Report
on:
schedule:
- cron: "0 9 * * *"
jobs:
report:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Generate a summary of yesterday's commits and open issues"
claude_args: "--model claude-opus-4-1-20250805"
```
### Common use cases
In issue or PR comments:
```
@claude implement this feature based on the issue description
@claude how should I implement user authentication for this endpoint?
@claude fix the TypeError in the user dashboard component
```
Claude will automatically analyze the context and respond appropriately.
## Best practices
### CLAUDE.md configuration
Create a `CLAUDE.md` file in your repository root to define code style guidelines, review criteria, project-specific rules, and preferred patterns. This file guides Claude's understanding of your project standards.
### Security considerations
<Warning>Never commit API keys directly to your repository!</Warning>
For comprehensive security guidance including permissions, authentication, and best practices, see the [Claude Code Action security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md).
Always use GitHub Secrets for API keys:
* Add your API key as a repository secret named `ANTHROPIC_API_KEY`
* Reference it in workflows: `anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}`
* Limit action permissions to only what's necessary
* Review Claude's suggestions before merging
Always use GitHub Secrets (e.g., `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files.
### Optimizing performance
Use issue templates to provide context, keep your `CLAUDE.md` concise and focused, and configure appropriate timeouts for your workflows.
### CI costs
When using Claude Code GitHub Actions, be aware of the associated costs:
**GitHub Actions costs:**
* Claude Code runs on GitHub-hosted runners, which consume your GitHub Actions minutes
* See [GitHub's billing documentation](https://docs.github.com/en/billing/managing-billing-for-your-products/managing-billing-for-github-actions/about-billing-for-github-actions) for detailed pricing and minute limits
**API costs:**
* Each Claude interaction consumes API tokens based on the length of prompts and responses
* Token usage varies by task complexity and codebase size
* See [Claude's pricing page](https://claude.com/platform/api) for current token rates
**Cost optimization tips:**
* Use specific `@claude` commands to reduce unnecessary API calls
* Configure appropriate `--max-turns` in `claude_args` to prevent excessive iterations
* Set workflow-level timeouts to avoid runaway jobs
* Consider using GitHub's concurrency controls to limit parallel runs
## Configuration examples
The Claude Code Action v1 simplifies configuration with unified parameters:
```yaml theme={null}
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Your instructions here" # Optional
claude_args: "--max-turns 5" # Optional CLI arguments
```
Key features:
* **Unified prompt interface** - Use `prompt` for all instructions
* **Slash commands** - Pre-built prompts like `/review` or `/fix`
* **CLI passthrough** - Any Claude Code CLI argument via `claude_args`
* **Flexible triggers** - Works with any GitHub event
Visit the [examples directory](https://github.com/anthropics/claude-code-action/tree/main/examples) for complete workflow files.
<Tip>
When responding to issue or PR comments, Claude automatically responds to @claude mentions. For other events, use the `prompt` parameter to provide instructions.
</Tip>
## Using with AWS Bedrock & Google Vertex AI
For enterprise environments, you can use Claude Code GitHub Actions with your own cloud infrastructure. This approach gives you control over data residency and billing while maintaining the same functionality.
### Prerequisites
Before setting up Claude Code GitHub Actions with cloud providers, you need:
#### For Google Cloud Vertex AI:
1. A Google Cloud Project with Vertex AI enabled
2. Workload Identity Federation configured for GitHub Actions
3. A service account with the required permissions
4. A GitHub App (recommended) or use the default GITHUB\_TOKEN
#### For AWS Bedrock:
1. An AWS account with Amazon Bedrock enabled
2. GitHub OIDC Identity Provider configured in AWS
3. An IAM role with Bedrock permissions
4. A GitHub App (recommended) or use the default GITHUB\_TOKEN
<Steps>
<Step title="Create a custom GitHub App (Recommended for 3P Providers)">
For best control and security when using 3P providers like Vertex AI or Bedrock, we recommend creating your own GitHub App:
1. Go to [https://github.com/settings/apps/new](https://github.com/settings/apps/new)
2. Fill in the basic information:
* **GitHub App name**: Choose a unique name (e.g., "YourOrg Claude Assistant")
* **Homepage URL**: Your organization's website or the repository URL
3. Configure the app settings:
* **Webhooks**: Uncheck "Active" (not needed for this integration)
4. Set the required permissions:
* **Repository permissions**:
* Contents: Read & Write
* Issues: Read & Write
* Pull requests: Read & Write
5. Click "Create GitHub App"
6. After creation, click "Generate a private key" and save the downloaded `.pem` file
7. Note your App ID from the app settings page
8. Install the app to your repository:
* From your app's settings page, click "Install App" in the left sidebar
* Select your account or organization
* Choose "Only select repositories" and select the specific repository
* Click "Install"
9. Add the private key as a secret to your repository:
* Go to your repository's Settings → Secrets and variables → Actions
* Create a new secret named `APP_PRIVATE_KEY` with the contents of the `.pem` file
10. Add the App ID as a secret:
* Create a new secret named `APP_ID` with your GitHub App's ID
<Note>
This app will be used with the [actions/create-github-app-token](https://github.com/actions/create-github-app-token) action to generate authentication tokens in your workflows.
</Note>
**Alternative for Claude API or if you don't want to setup your own Github app**: Use the official Anthropic app:
1. Install from: [https://github.com/apps/claude](https://github.com/apps/claude)
2. No additional configuration needed for authentication
</Step>
<Step title="Configure cloud provider authentication">
Choose your cloud provider and set up secure authentication:
<AccordionGroup>
<Accordion title="AWS Bedrock">
**Configure AWS to allow GitHub Actions to authenticate securely without storing credentials.**
> **Security Note**: Use repository-specific configurations and grant only the minimum required permissions.
**Required Setup**:
1. **Enable Amazon Bedrock**:
* Request access to Claude models in Amazon Bedrock
* For cross-region models, request access in all required regions
2. **Set up GitHub OIDC Identity Provider**:
* Provider URL: `https://token.actions.githubusercontent.com`
* Audience: `sts.amazonaws.com`
3. **Create IAM Role for GitHub Actions**:
* Trusted entity type: Web identity
* Identity provider: `token.actions.githubusercontent.com`
* Permissions: `AmazonBedrockFullAccess` policy
* Configure trust policy for your specific repository
**Required Values**:
After setup, you'll need:
* **AWS\_ROLE\_TO\_ASSUME**: The ARN of the IAM role you created
<Tip>
OIDC is more secure than using static AWS access keys because credentials are temporary and automatically rotated.
</Tip>
See [AWS documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html) for detailed OIDC setup instructions.
</Accordion>
<Accordion title="Google Vertex AI">
**Configure Google Cloud to allow GitHub Actions to authenticate securely without storing credentials.**
> **Security Note**: Use repository-specific configurations and grant only the minimum required permissions.
**Required Setup**:
1. **Enable APIs** in your Google Cloud project:
* IAM Credentials API
* Security Token Service (STS) API
* Vertex AI API
2. **Create Workload Identity Federation resources**:
* Create a Workload Identity Pool
* Add a GitHub OIDC provider with:
* Issuer: `https://token.actions.githubusercontent.com`
* Attribute mappings for repository and owner
* **Security recommendation**: Use repository-specific attribute conditions
3. **Create a Service Account**:
* Grant only `Vertex AI User` role
* **Security recommendation**: Create a dedicated service account per repository
4. **Configure IAM bindings**:
* Allow the Workload Identity Pool to impersonate the service account
* **Security recommendation**: Use repository-specific principal sets
**Required Values**:
After setup, you'll need:
* **GCP\_WORKLOAD\_IDENTITY\_PROVIDER**: The full provider resource name
* **GCP\_SERVICE\_ACCOUNT**: The service account email address
<Tip>
Workload Identity Federation eliminates the need for downloadable service account keys, improving security.
</Tip>
For detailed setup instructions, consult the [Google Cloud Workload Identity Federation documentation](https://cloud.google.com/iam/docs/workload-identity-federation).
</Accordion>
</AccordionGroup>
</Step>
<Step title="Add Required Secrets">
Add the following secrets to your repository (Settings → Secrets and variables → Actions):
#### For Claude API (Direct):
1. **For API Authentication**:
* `ANTHROPIC_API_KEY`: Your Claude API key from [console.anthropic.com](https://console.anthropic.com)
2. **For GitHub App (if using your own app)**:
* `APP_ID`: Your GitHub App's ID
* `APP_PRIVATE_KEY`: The private key (.pem) content
#### For Google Cloud Vertex AI
1. **For GCP Authentication**:
* `GCP_WORKLOAD_IDENTITY_PROVIDER`
* `GCP_SERVICE_ACCOUNT`
2. **For GitHub App (if using your own app)**:
* `APP_ID`: Your GitHub App's ID
* `APP_PRIVATE_KEY`: The private key (.pem) content
#### For AWS Bedrock
1. **For AWS Authentication**:
* `AWS_ROLE_TO_ASSUME`
2. **For GitHub App (if using your own app)**:
* `APP_ID`: Your GitHub App's ID
* `APP_PRIVATE_KEY`: The private key (.pem) content
</Step>
<Step title="Create workflow files">
Create GitHub Actions workflow files that integrate with your cloud provider. The examples below show complete configurations for both AWS Bedrock and Google Vertex AI:
<AccordionGroup>
<Accordion title="AWS Bedrock workflow">
**Prerequisites:**
* AWS Bedrock access enabled with Claude model permissions
* GitHub configured as an OIDC identity provider in AWS
* IAM role with Bedrock permissions that trusts GitHub Actions
**Required GitHub secrets:**
| Secret Name | Description |
| -------------------- | ------------------------------------------------- |
| `AWS_ROLE_TO_ASSUME` | ARN of the IAM role for Bedrock access |
| `APP_ID` | Your GitHub App ID (from app settings) |
| `APP_PRIVATE_KEY` | The private key you generated for your GitHub App |
```yaml theme={null}
name: Claude PR Action
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
jobs:
claude-pr:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
runs-on: ubuntu-latest
env:
AWS_REGION: us-west-2
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
- name: Configure AWS Credentials (OIDC)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }}
aws-region: us-west-2
- uses: anthropics/claude-code-action@v1
with:
github_token: ${{ steps.app-token.outputs.token }}
use_bedrock: "true"
claude_args: '--model us.anthropic.claude-sonnet-4-5-20250929-v1:0 --max-turns 10'
```
<Tip>
The model ID format for Bedrock includes the region prefix (e.g., `us.anthropic.claude...`) and version suffix.
</Tip>
</Accordion>
<Accordion title="Google Vertex AI workflow">
**Prerequisites:**
* Vertex AI API enabled in your GCP project
* Workload Identity Federation configured for GitHub
* Service account with Vertex AI permissions
**Required GitHub secrets:**
| Secret Name | Description |
| -------------------------------- | ------------------------------------------------- |
| `GCP_WORKLOAD_IDENTITY_PROVIDER` | Workload identity provider resource name |
| `GCP_SERVICE_ACCOUNT` | Service account email with Vertex AI access |
| `APP_ID` | Your GitHub App ID (from app settings) |
| `APP_PRIVATE_KEY` | The private key you generated for your GitHub App |
```yaml theme={null}
name: Claude PR Action
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
jobs:
claude-pr:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
- name: Authenticate to Google Cloud
id: auth
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- uses: anthropics/claude-code-action@v1
with:
github_token: ${{ steps.app-token.outputs.token }}
trigger_phrase: "@claude"
use_vertex: "true"
claude_args: '--model claude-sonnet-4@20250514 --max-turns 10'
env:
ANTHROPIC_VERTEX_PROJECT_ID: ${{ steps.auth.outputs.project_id }}
CLOUD_ML_REGION: us-east5
VERTEX_REGION_CLAUDE_3_7_SONNET: us-east5
```
<Tip>
The project ID is automatically retrieved from the Google Cloud authentication step, so you don't need to hardcode it.
</Tip>
</Accordion>
</AccordionGroup>
</Step>
</Steps>
## Troubleshooting
### Claude not responding to @claude commands
Verify the GitHub App is installed correctly, check that workflows are enabled, ensure API key is set in repository secrets, and confirm the comment contains `@claude` (not `/claude`).
### CI not running on Claude's commits
Ensure you're using the GitHub App or custom app (not Actions user), check workflow triggers include the necessary events, and verify app permissions include CI triggers.
### Authentication errors
Confirm API key is valid and has sufficient permissions. For Bedrock/Vertex, check credentials configuration and ensure secrets are named correctly in workflows.
## Advanced configuration
### Action parameters
The Claude Code Action v1 uses a simplified configuration:
| Parameter | Description | Required |
| ------------------- | ----------------------------------------------- | -------- |
| `prompt` | Instructions for Claude (text or slash command) | No\* |
| `claude_args` | CLI arguments passed to Claude Code | No |
| `anthropic_api_key` | Claude API key | Yes\*\* |
| `github_token` | GitHub token for API access | No |
| `trigger_phrase` | Custom trigger phrase (default: "@claude") | No |
| `use_bedrock` | Use AWS Bedrock instead of Claude API | No |
| `use_vertex` | Use Google Vertex AI instead of Claude API | No |
\*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase\
\*\*Required for direct Claude API, not for Bedrock/Vertex
#### Using claude\_args
The `claude_args` parameter accepts any Claude Code CLI arguments:
```yaml theme={null}
claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929 --mcp-config /path/to/config.json"
```
Common arguments:
* `--max-turns`: Maximum conversation turns (default: 10)
* `--model`: Model to use (e.g., `claude-sonnet-4-5-20250929`)
* `--mcp-config`: Path to MCP configuration
* `--allowed-tools`: Comma-separated list of allowed tools
* `--debug`: Enable debug output
### Alternative integration methods
While the `/install-github-app` command is the recommended approach, you can also:
* **Custom GitHub App**: For organizations needing branded usernames or custom authentication flows. Create your own GitHub App with required permissions (contents, issues, pull requests) and use the actions/create-github-app-token action to generate tokens in your workflows.
* **Manual GitHub Actions**: Direct workflow configuration for maximum flexibility
* **MCP Configuration**: Dynamic loading of Model Context Protocol servers
See the [Claude Code Action documentation](https://github.com/anthropics/claude-code-action/blob/main/docs) for detailed guides on authentication, security, and advanced configuration.
### Customizing Claude's behavior
You can configure Claude's behavior in two ways:
1. **CLAUDE.md**: Define coding standards, review criteria, and project-specific rules in a `CLAUDE.md` file at the root of your repository. Claude will follow these guidelines when creating PRs and responding to requests. Check out our [Memory documentation](/en/docs/claude-code/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.

View File

@@ -0,0 +1,462 @@
# Claude Code GitLab CI/CD
> Learn about integrating Claude Code into your development workflow with GitLab CI/CD
<Info>
Claude Code for GitLab CI/CD is currently in beta. Features and functionality may evolve as we refine the experience.
This integration is maintained by GitLab. For support, see the following [GitLab issue](https://gitlab.com/gitlab-org/gitlab/-/issues/573776).
</Info>
<Note>
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.
</Note>
## Why use Claude Code with GitLab?
* **Instant MR creation**: Describe what you need, and Claude proposes a complete MR with changes and explanation
* **Automated implementation**: Turn issues into working code with a single command or mention
* **Project-aware**: Claude follows your `CLAUDE.md` guidelines and existing code patterns
* **Simple setup**: Add one job to `.gitlab-ci.yml` and a masked CI/CD variable
* **Enterprise-ready**: Choose Claude API, AWS Bedrock, or Google Vertex AI to meet data residency and procurement needs
* **Secure by default**: Runs in your GitLab runners with your branch protection and approvals
## How it works
Claude Code uses GitLab CI/CD to run AI tasks in isolated jobs and commit results back via MRs:
1. **Event-driven orchestration**: GitLab listens for your chosen triggers (for example, a comment that mentions `@claude` in an issue, MR, or review thread). The job collects context from the thread and repository, builds prompts from that input, and runs Claude Code.
2. **Provider abstraction**: Use the provider that fits your environment:
* Claude API (SaaS)
* AWS Bedrock (IAM-based access, cross-region options)
* Google Vertex AI (GCP-native, Workload Identity Federation)
3. **Sandboxed execution**: Each interaction runs in a container with strict network and filesystem rules. Claude Code enforces workspace-scoped permissions to constrain writes. Every change flows through an MR so reviewers see the diff and approvals still apply.
Pick regional endpoints to reduce latency and meet data-sovereignty requirements while using existing cloud agreements.
## What can Claude do?
Claude Code enables powerful CI/CD workflows that transform how you work with code:
* Create and update MRs from issue descriptions or comments
* Analyze performance regressions and propose optimizations
* Implement features directly in a branch, then open an MR
* Fix bugs and regressions identified by tests or comments
* Respond to follow-up comments to iterate on requested changes
## Setup
### Quick setup
The fastest way to get started is to add a minimal job to your `.gitlab-ci.yml` and set your API key as a masked variable.
1. **Add a masked CI/CD variable**
* Go to **Settings****CI/CD****Variables**
* Add `ANTHROPIC_API_KEY` (masked, protected as needed)
2. **Add a Claude job to `.gitlab-ci.yml`**
```yaml theme={null}
stages:
- ai
claude:
stage: ai
image: node:24-alpine3.21
# Adjust rules to fit how you want to trigger the job:
# - manual runs
# - merge request events
# - web/API triggers when a comment contains '@claude'
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
variables:
GIT_STRATEGY: fetch
before_script:
- apk update
- apk add --no-cache git curl bash
- npm install -g @anthropic-ai/claude-code
script:
# Optional: start a GitLab MCP server if your setup provides one
- /bin/gitlab-mcp-server || true
# Use AI_FLOW_* variables when invoking via web/API triggers with context payloads
- echo "$AI_FLOW_INPUT for $AI_FLOW_CONTEXT on $AI_FLOW_EVENT"
- >
claude
-p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"
--permission-mode acceptEdits
--allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
--debug
```
After adding the job and your `ANTHROPIC_API_KEY` variable, test by running the job manually from **CI/CD** → **Pipelines**, or trigger it from an MR to let Claude propose updates in a branch and open an MR if needed.
<Note>
To run on AWS Bedrock or Google Vertex AI instead of the Claude API, see the [Using with AWS Bedrock & Google Vertex AI](#using-with-aws-bedrock--google-vertex-ai) section below for authentication and environment setup.
</Note>
### Manual setup (recommended for production)
If you prefer a more controlled setup or need enterprise providers:
1. **Configure provider access**:
* **Claude API**: Create and store `ANTHROPIC_API_KEY` as a masked CI/CD variable
* **AWS Bedrock**: **Configure GitLab** → **AWS OIDC** and create an IAM role for Bedrock
* **Google Vertex AI**: **Configure Workload Identity Federation for GitLab** → **GCP**
2. **Add project credentials for GitLab API operations**:
* Use `CI_JOB_TOKEN` by default, or create a Project Access Token with `api` scope
* Store as `GITLAB_ACCESS_TOKEN` (masked) if using a PAT
3. **Add the Claude job to `.gitlab-ci.yml`** (see examples below)
4. **(Optional) Enable mention-driven triggers**:
* Add a project webhook for "Comments (notes)" to your event listener (if you use one)
* Have the listener call the pipeline trigger API with variables like `AI_FLOW_INPUT` and `AI_FLOW_CONTEXT` when a comment contains `@claude`
## Example use cases
### Turn issues into MRs
In an issue comment:
```
@claude implement this feature based on the issue description
```
Claude analyzes the issue and codebase, writes changes in a branch, and opens an MR for review.
### Get implementation help
In an MR discussion:
```
@claude suggest a concrete approach to cache the results of this API call
```
Claude proposes changes, adds code with appropriate caching, and updates the MR.
### Fix bugs quickly
In an issue or MR comment:
```
@claude fix the TypeError in the user dashboard component
```
Claude locates the bug, implements a fix, and updates the branch or opens a new MR.
## Using with AWS Bedrock & Google Vertex AI
For enterprise environments, you can run Claude Code entirely on your cloud infrastructure with the same developer experience.
<Tabs>
<Tab title="AWS Bedrock">
### Prerequisites
Before setting up Claude Code with AWS Bedrock, you need:
1. An AWS account with Amazon Bedrock access to the desired Claude models
2. GitLab configured as an OIDC identity provider in AWS IAM
3. An IAM role with Bedrock permissions and a trust policy restricted to your GitLab project/refs
4. GitLab CI/CD variables for role assumption:
* `AWS_ROLE_TO_ASSUME` (role ARN)
* `AWS_REGION` (Bedrock region)
### Setup instructions
Configure AWS to allow GitLab CI jobs to assume an IAM role via OIDC (no static keys).
**Required setup:**
1. Enable Amazon Bedrock and request access to your target Claude models
2. Create an IAM OIDC provider for GitLab if not already present
3. Create an IAM role trusted by the GitLab OIDC provider, restricted to your project and protected refs
4. Attach least-privilege permissions for Bedrock invoke APIs
**Required values to store in CI/CD variables:**
* `AWS_ROLE_TO_ASSUME`
* `AWS_REGION`
Add variables in Settings → CI/CD → Variables:
```yaml theme={null}
# For AWS Bedrock:
- AWS_ROLE_TO_ASSUME
- AWS_REGION
```
Use the AWS Bedrock job example above to exchange the GitLab job token for temporary AWS credentials at runtime.
</Tab>
<Tab title="Google Vertex AI">
### Prerequisites
Before setting up Claude Code with Google Vertex AI, you need:
1. A Google Cloud project with:
* Vertex AI API enabled
* Workload Identity Federation configured to trust GitLab OIDC
2. A dedicated service account with only the required Vertex AI roles
3. GitLab CI/CD variables for WIF:
* `GCP_WORKLOAD_IDENTITY_PROVIDER` (full resource name)
* `GCP_SERVICE_ACCOUNT` (service account email)
### Setup instructions
Configure Google Cloud to allow GitLab CI jobs to impersonate a service account via Workload Identity Federation.
**Required setup:**
1. Enable IAM Credentials API, STS API, and Vertex AI API
2. Create a Workload Identity Pool and provider for GitLab OIDC
3. Create a dedicated service account with Vertex AI roles
4. Grant the WIF principal permission to impersonate the service account
**Required values to store in CI/CD variables:**
* `GCP_WORKLOAD_IDENTITY_PROVIDER`
* `GCP_SERVICE_ACCOUNT`
Add variables in Settings → CI/CD → Variables:
```yaml theme={null}
# For Google Vertex AI:
- GCP_WORKLOAD_IDENTITY_PROVIDER
- GCP_SERVICE_ACCOUNT
- CLOUD_ML_REGION (for example, us-east5)
```
Use the Google Vertex AI job example above to authenticate without storing keys.
</Tab>
</Tabs>
## Configuration examples
Below are ready-to-use snippets you can adapt to your pipeline.
### Basic .gitlab-ci.yml (Claude API)
```yaml theme={null}
stages:
- ai
claude:
stage: ai
image: node:24-alpine3.21
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
variables:
GIT_STRATEGY: fetch
before_script:
- apk update
- apk add --no-cache git curl bash
- npm install -g @anthropic-ai/claude-code
script:
- /bin/gitlab-mcp-server || true
- >
claude
-p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"
--permission-mode acceptEdits
--allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
--debug
# Claude Code will use ANTHROPIC_API_KEY from CI/CD variables
```
### AWS Bedrock job example (OIDC)
**Prerequisites:**
* Amazon Bedrock enabled with access to your chosen Claude model(s)
* GitLab OIDC configured in AWS with a role that trusts your GitLab project and refs
* IAM role with Bedrock permissions (least privilege recommended)
**Required CI/CD variables:**
* `AWS_ROLE_TO_ASSUME`: ARN of the IAM role for Bedrock access
* `AWS_REGION`: Bedrock region (for example, `us-west-2`)
```yaml theme={null}
claude-bedrock:
stage: ai
image: node:24-alpine3.21
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
before_script:
- apk add --no-cache bash curl jq git python3 py3-pip
- pip install --no-cache-dir awscli
- npm install -g @anthropic-ai/claude-code
# Exchange GitLab OIDC token for AWS credentials
- export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}"
- if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi
- >
aws sts assume-role-with-web-identity
--role-arn "$AWS_ROLE_TO_ASSUME"
--role-session-name "gitlab-claude-$(date +%s)"
--web-identity-token "file://$AWS_WEB_IDENTITY_TOKEN_FILE"
--duration-seconds 3600 > /tmp/aws_creds.json
- export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId /tmp/aws_creds.json)"
- export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey /tmp/aws_creds.json)"
- export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken /tmp/aws_creds.json)"
script:
- /bin/gitlab-mcp-server || true
- >
claude
-p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"
--permission-mode acceptEdits
--allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
--debug
variables:
AWS_REGION: "us-west-2"
```
<Note>
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.
</Note>
### Google Vertex AI job example (Workload Identity Federation)
**Prerequisites:**
* Vertex AI API enabled in your GCP project
* Workload Identity Federation configured to trust GitLab OIDC
* A service account with Vertex AI permissions
**Required CI/CD variables:**
* `GCP_WORKLOAD_IDENTITY_PROVIDER`: Full provider resource name
* `GCP_SERVICE_ACCOUNT`: Service account email
* `CLOUD_ML_REGION`: Vertex region (for example, `us-east5`)
```yaml theme={null}
claude-vertex:
stage: ai
image: gcr.io/google.com/cloudsdktool/google-cloud-cli:slim
rules:
- if: '$CI_PIPELINE_SOURCE == "web"'
before_script:
- apt-get update && apt-get install -y git nodejs npm && apt-get clean
- npm install -g @anthropic-ai/claude-code
# Authenticate to Google Cloud via WIF (no downloaded keys)
- >
gcloud auth login --cred-file=<(cat <<EOF
{
"type": "external_account",
"audience": "${GCP_WORKLOAD_IDENTITY_PROVIDER}",
"subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
"service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${GCP_SERVICE_ACCOUNT}:generateAccessToken",
"token_url": "https://sts.googleapis.com/v1/token"
}
EOF
)
- gcloud config set project "$(gcloud projects list --format='value(projectId)' --filter="name:${CI_PROJECT_NAMESPACE}" | head -n1)" || true
script:
- /bin/gitlab-mcp-server || true
- >
CLOUD_ML_REGION="${CLOUD_ML_REGION:-us-east5}"
claude
-p "${AI_FLOW_INPUT:-'Review and update code as requested'}"
--permission-mode acceptEdits
--allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
--debug
variables:
CLOUD_ML_REGION: "us-east5"
```
<Note>
With Workload Identity Federation, you do not need to store service account keys. Use repository-specific trust conditions and least-privilege service accounts.
</Note>
## Best practices
### CLAUDE.md configuration
Create a `CLAUDE.md` file at the repository root to define coding standards, review criteria, and project-specific rules. Claude reads this file during runs and follows your conventions when proposing changes.
### Security considerations
Never commit API keys or cloud credentials to your repository! Always use GitLab CI/CD variables:
* Add `ANTHROPIC_API_KEY` as a masked variable (and protect it if needed)
* Use provider-specific OIDC where possible (no long-lived keys)
* Limit job permissions and network egress
* Review Claude's MRs like any other contributor
### Optimizing performance
* Keep `CLAUDE.md` focused and concise
* Provide clear issue/MR descriptions to reduce iterations
* Configure sensible job timeouts to avoid runaway runs
* Cache npm and package installs in runners where possible
### CI costs
When using Claude Code with GitLab CI/CD, be aware of associated costs:
* **GitLab Runner time**:
* Claude runs on your GitLab runners and consumes compute minutes
* See your GitLab plan's runner billing for details
* **API costs**:
* Each Claude interaction consumes tokens based on prompt and response size
* Token usage varies by task complexity and codebase size
* See [Anthropic pricing](/en/docs/about-claude/pricing) for details
* **Cost optimization tips**:
* Use specific `@claude` commands to reduce unnecessary turns
* Set appropriate `max_turns` and job timeout values
* Limit concurrency to control parallel runs
## Security and governance
* Each job runs in an isolated container with restricted network access
* Claude's changes flow through MRs so reviewers see every diff
* Branch protection and approval rules apply to AI-generated code
* Claude Code uses workspace-scoped permissions to constrain writes
* Costs remain under your control because you bring your own provider credentials
## Troubleshooting
### Claude not responding to @claude commands
* Verify your pipeline is being triggered (manually, MR event, or via a note event listener/webhook)
* Ensure CI/CD variables (`ANTHROPIC_API_KEY` or cloud provider settings) are present and unmasked
* Check that the comment contains `@claude` (not `/claude`) and that your mention trigger is configured
### Job can't write comments or open MRs
* Ensure `CI_JOB_TOKEN` has sufficient permissions for the project, or use a Project Access Token with `api` scope
* Check the `mcp__gitlab` tool is enabled in `--allowedTools`
* Confirm the job runs in the context of the MR or has enough context via `AI_FLOW_*` variables
### Authentication errors
* **For Claude API**: Confirm `ANTHROPIC_API_KEY` is valid and unexpired
* **For Bedrock/Vertex**: Verify OIDC/WIF configuration, role impersonation, and secret names; confirm region and model availability
## Advanced configuration
### Common parameters and variables
Claude Code supports these commonly used inputs:
* `prompt` / `prompt_file`: Provide instructions inline (`-p`) or via a file
* `max_turns`: Limit the number of back-and-forth iterations
* `timeout_minutes`: Limit total execution time
* `ANTHROPIC_API_KEY`: Required for the Claude API (not used for Bedrock/Vertex)
* Provider-specific environment: `AWS_REGION`, project/region vars for Vertex
<Note>
Exact flags and parameters may vary by version of `@anthropic-ai/claude-code`. Run `claude --help` in your job to see supported options.
</Note>
### Customizing Claude's behavior
You can guide Claude in two primary ways:
1. **CLAUDE.md**: Define coding standards, security requirements, and project conventions. Claude reads this during runs and follows your rules.
2. **Custom prompts**: Pass task-specific instructions via `prompt`/`prompt_file` in the job. Use different prompts for different jobs (for example, review, implement, refactor).

View File

@@ -0,0 +1,160 @@
# Claude Code on Google Vertex AI
> Learn about configuring Claude Code through Google Vertex AI, including setup, IAM configuration, and troubleshooting.
## Prerequisites
Before configuring Claude Code with Vertex AI, ensure you have:
* A Google Cloud Platform (GCP) account with billing enabled
* A GCP project with Vertex AI API enabled
* Access to desired Claude models (e.g., Claude Sonnet 4.5)
* Google Cloud SDK (`gcloud`) installed and configured
* Quota allocated in desired GCP region
## Region Configuration
Claude Code can be used with both Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai) and regional endpoints.
<Note>
Vertex AI may not support the Claude Code default models on all regions. You may need to switch to a [supported region or model](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models).
</Note>
<Note>
Vertex AI may not support the Claude Code default models on global endpoints. You may need to switch to a regional endpoint or [supported model](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models).
</Note>
## Setup
### 1. Enable Vertex AI API
Enable the Vertex AI API in your GCP project:
```bash theme={null}
# Set your project ID
gcloud config set project YOUR-PROJECT-ID
# Enable Vertex AI API
gcloud services enable aiplatform.googleapis.com
```
### 2. Request model access
Request access to Claude models in Vertex AI:
1. Navigate to the [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)
2. Search for "Claude" models
3. Request access to desired Claude models (e.g., Claude Sonnet 4.5)
4. Wait for approval (may take 24-48 hours)
### 3. Configure GCP credentials
Claude Code uses standard Google Cloud authentication.
For more information, see [Google Cloud authentication documentation](https://cloud.google.com/docs/authentication).
<Note>
When authenticating, Claude Code will automatically use the project ID from the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable. To override this, set one of these environment variables: `GCLOUD_PROJECT`, `GOOGLE_CLOUD_PROJECT`, or `GOOGLE_APPLICATION_CREDENTIALS`.
</Note>
### 4. Configure Claude Code
Set the following environment variables:
```bash theme={null}
# Enable Vertex AI integration
export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION=global
export ANTHROPIC_VERTEX_PROJECT_ID=YOUR-PROJECT-ID
# Optional: Disable prompt caching if needed
export DISABLE_PROMPT_CACHING=1
# When CLOUD_ML_REGION=global, override region for unsupported models
export VERTEX_REGION_CLAUDE_3_5_HAIKU=us-east5
# Optional: Override regions for other specific models
export VERTEX_REGION_CLAUDE_3_5_SONNET=us-east5
export VERTEX_REGION_CLAUDE_3_7_SONNET=us-east5
export VERTEX_REGION_CLAUDE_4_0_OPUS=europe-west1
export VERTEX_REGION_CLAUDE_4_0_SONNET=us-east5
export VERTEX_REGION_CLAUDE_4_1_OPUS=europe-west1
```
<Note>
[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.
</Note>
<Note>
When using Vertex AI, the `/login` and `/logout` commands are disabled since authentication is handled through Google Cloud credentials.
</Note>
### 5. Model configuration
Claude Code uses these default models for Vertex AI:
| Model type | Default value |
| :--------------- | :--------------------------- |
| Primary model | `claude-sonnet-4-5@20250929` |
| Small/fast model | `claude-haiku-4-5@20251001` |
<Note>
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`).
</Note>
To customize models:
```bash theme={null}
export ANTHROPIC_MODEL='claude-opus-4-1@20250805'
export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001'
```
## IAM configuration
Assign the required IAM permissions:
The `roles/aiplatform.user` role includes the required permissions:
* `aiplatform.endpoints.predict` - Required for model invocation
* `aiplatform.endpoints.computeTokens` - Required for token counting
For more restrictive permissions, create a custom role with only the permissions above.
For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/docs/general/access-control).
<Note>
We recommend creating a dedicated GCP project for Claude Code to simplify cost tracking and access control.
</Note>
### 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.
<Note>
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.
</Note>
## Troubleshooting
If you encounter quota issues:
* Check current quotas or request quota increase through [Cloud Console](https://cloud.google.com/docs/quotas/view-manage)
If you encounter "model not found" 404 errors:
* Confirm model is Enabled in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)
* Verify you have access to the specified region
* If using `CLOUD_ML_REGION=global`, check that your models support global endpoints in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) under "Supported features". For models that don't support global endpoints, either:
* Specify a supported model via `ANTHROPIC_MODEL` or `ANTHROPIC_SMALL_FAST_MODEL`, or
* Set a regional endpoint using `VERTEX_REGION_<MODEL_NAME>` environment variables
If you encounter 429 errors:
* For regional endpoints, ensure the primary model and small/fast model are supported in your selected region
* Consider switching to `CLOUD_ML_REGION=global` for better availability
## Additional resources
* [Vertex AI documentation](https://cloud.google.com/vertex-ai/docs)
* [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing)
* [Vertex AI quotas and limits](https://cloud.google.com/vertex-ai/docs/quotas)

View File

@@ -0,0 +1,204 @@
# Headless mode
> Run Claude Code programmatically without interactive UI
## Overview
The headless mode allows you to run Claude Code programmatically from command line scripts and automation tools without any interactive UI.
## 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:
```bash theme={null}
claude -p "Stage my changes and write a set of commits for them" \
--allowedTools "Bash,Read" \
--permission-mode acceptEdits
```
## Configuration Options
Headless mode leverages all the CLI options available in Claude Code. Here are the key ones for automation and scripting:
| 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 <br /><br /> string of comma-separated list of allowed tools | `claude --allowedTools mcp__slack mcp__filesystem`<br /><br />`claude --allowedTools "Bash(npm install),mcp__filesystem"` |
| `--disallowedTools` | Space-separated list of denied tools, or <br /><br /> string of comma-separated list of denied tools | `claude --disallowedTools mcp__splunk mcp__github`<br /><br />`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` |
For a complete list of CLI options and features, see the [CLI reference](/en/docs/claude-code/cli-reference) documentation.
## Multi-turn conversations
For multi-turn conversations, you can resume conversations or continue from the most recent session:
```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
```
## Output Formats
### Text Output (Default)
```bash theme={null}
claude -p "Explain file src/components/Header.tsx"
# Output: This is a React component showing...
```
### JSON Output
Returns structured data including metadata:
```bash theme={null}
claude -p "How does the data layer work?" --output-format json
```
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"
}
```
### Streaming JSON Output
Streams each message as it is received:
```bash theme={null}
claude -p "Build an application" --output-format stream-json
```
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.
## Input Formats
### Text Input (Default)
```bash theme={null}
# Direct argument
claude -p "Explain this code"
# From stdin
echo "Explain this code" | claude -p
```
### 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.
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
```
## Agent Integration Examples
### SRE Incident Response Bot
```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"
```
### Automated Security Review
```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
```
### Multi-turn Legal Assistant
```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"
```
## Best Practices
* **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')
```
* **Handle errors gracefully** - check exit codes and stderr:
```bash theme={null}
if ! claude -p "$prompt" 2>error.log; then
echo "Error occurred:" >&2
cat error.log >&2
exit 1
fi
```
* **Use session management** for maintaining context in multi-turn conversations
* **Consider timeouts** for long-running operations:
```bash theme={null}
timeout 300 claude -p "$complex_prompt" || echo "Timed out after 5 minutes"
```
* **Respect rate limits** when making multiple requests by adding delays between calls
## 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

View File

@@ -0,0 +1,332 @@
# Get started with Claude Code hooks
> Learn how to customize and extend Claude Code's behavior by registering shell commands
Claude Code hooks are user-defined shell commands that execute at various points
in Claude Code's lifecycle. Hooks provide deterministic control over Claude
Code's behavior, ensuring certain actions always happen rather than relying on
the LLM to choose to run them.
<Tip>
For reference documentation on hooks, see [Hooks reference](/en/docs/claude-code/hooks).
</Tip>
Example use cases for hooks include:
* **Notifications**: Customize how you get notified when Claude Code is awaiting
your input or permission to run something.
* **Automatic formatting**: Run `prettier` on .ts files, `gofmt` on .go files,
etc. after every file edit.
* **Logging**: Track and count all executed commands for compliance or
debugging.
* **Feedback**: Provide automated feedback when Claude Code produces code that
does not follow your codebase conventions.
* **Custom permissions**: Block modifications to production files or sensitive
directories.
By encoding these rules as hooks rather than prompting instructions, you turn
suggestions into app-level code that executes every time it is expected to run.
<Warning>
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.
</Warning>
## Hook Events Overview
Claude Code provides several hook events that run at different points in the
workflow:
* **PreToolUse**: Runs before tool calls (can block them)
* **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
* **Stop**: Runs when Claude Code finishes responding
* **SubagentStop**: Runs when subagent tasks complete
* **PreCompact**: Runs before Claude Code is about to run a compact operation
* **SessionStart**: Runs when Claude Code starts a new session or resumes an existing session
* **SessionEnd**: Runs when Claude Code session ends
Each event receives different data and can control Claude's behavior in
different ways.
## Quickstart
In this quickstart, you'll add a hook that logs the shell commands that Claude
Code runs.
### Prerequisites
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
the `PreToolUse` hook event.
`PreToolUse` hooks run before tool calls and can block them while providing
Claude feedback on what to do differently.
### Step 2: Add a matcher
Select `+ Add new matcher…` to run your hook only on Bash tool calls.
Type `Bash` for the matcher.
<Note>You can use `*` to match all tools.</Note>
### Step 3: Add the hook
Select `+ Add new hook…` and enter this command:
```bash theme={null}
jq -r '"\(.tool_input.command) - \(.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt
```
### Step 4: Save your configuration
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!
### Step 5: Verify your hook
Run `/hooks` again or check `~/.claude/settings.json` to see your configuration:
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \"No description\")\"' >> ~/.claude/bash-command-log.txt"
}
]
}
]
}
}
```
### Step 6: Test your hook
Ask Claude to run a simple command like `ls` and check your log file:
```bash theme={null}
cat ~/.claude/bash-command-log.txt
```
You should see entries like:
```
ls - Lists files and directories
```
## More Examples
<Note>
For a complete example implementation, see the [bash command validator example](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py) in our public codebase.
</Note>
### Code Formatting Hook
Automatically format TypeScript files after editing:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | { read file_path; if echo \"$file_path\" | grep -q '\\.ts$'; then npx prettier --write \"$file_path\"; fi; }"
}
]
}
]
}
}
```
### Markdown Formatting Hook
Automatically fix missing language tags and formatting issues in markdown files:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/markdown_formatter.py"
}
]
}
]
}
}
```
Create `.claude/hooks/markdown_formatter.py` with this content:
````python theme={null}
#!/usr/bin/env python3
"""
Markdown formatter for Claude Code output.
Fixes missing language tags and spacing issues while preserving code content.
"""
import json
import sys
import re
import os
def detect_language(code):
"""Best-effort language detection from code content."""
s = code.strip()
# JSON detection
if re.search(r'^\s*[{\[]', s):
try:
json.loads(s)
return 'json'
except:
pass
# Python detection
if re.search(r'^\s*def\s+\w+\s*\(', s, re.M) or \
re.search(r'^\s*(import|from)\s+\w+', s, re.M):
return 'python'
# JavaScript detection
if re.search(r'\b(function\s+\w+\s*\(|const\s+\w+\s*=)', s) or \
re.search(r'=>|console\.(log|error)', s):
return 'javascript'
# Bash detection
if re.search(r'^#!.*\b(bash|sh)\b', s, re.M) or \
re.search(r'\b(if|then|fi|for|in|do|done)\b', s):
return 'bash'
# SQL detection
if re.search(r'\b(SELECT|INSERT|UPDATE|DELETE|CREATE)\s+', s, re.I):
return 'sql'
return 'text'
def format_markdown(content):
"""Format markdown content with language detection."""
# Fix unlabeled code fences
def add_lang_to_fence(match):
indent, info, body, closing = match.groups()
if not info.strip():
lang = detect_language(body)
return f"{indent}```{lang}\n{body}{closing}\n"
return match.group(0)
fence_pattern = r'(?ms)^([ \t]{0,3})```([^\n]*)\n(.*?)(\n\1```)\s*$'
content = re.sub(fence_pattern, add_lang_to_fence, content)
# Fix excessive blank lines (only outside code fences)
content = re.sub(r'\n{3,}', '\n\n', content)
return content.rstrip() + '\n'
# Main execution
try:
input_data = json.load(sys.stdin)
file_path = input_data.get('tool_input', {}).get('file_path', '')
if not file_path.endswith(('.md', '.mdx')):
sys.exit(0) # Not a markdown file
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
formatted = format_markdown(content)
if formatted != content:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(formatted)
print(f"✓ Fixed markdown formatting in {file_path}")
except Exception as e:
print(f"Error formatting markdown: {e}", file=sys.stderr)
sys.exit(1)
````
Make the script executable:
```bash theme={null}
chmod +x .claude/hooks/markdown_formatter.py
```
This hook automatically:
* Detects programming languages in unlabeled code blocks
* Adds appropriate language tags for syntax highlighting
* Fixes excessive blank lines while preserving code content
* Only processes markdown files (`.md`, `.mdx`)
### Custom Notification Hook
Get desktop notifications when Claude needs input:
```json theme={null}
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "notify-send 'Claude Code' 'Awaiting your input'"
}
]
}
]
}
}
```
### File Protection Hook
Block edits to sensitive files:
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "python3 -c \"import json, sys; data=json.load(sys.stdin); path=data.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(p in path for p in ['.env', 'package-lock.json', '.git/']) else 0)\""
}
]
}
]
}
}
```
## 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
documentation.

View File

@@ -0,0 +1,837 @@
# Hooks reference
> This page provides reference documentation for implementing hooks in Claude Code.
<Tip>
For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/docs/claude-code/hooks-guide).
</Tip>
## Configuration
Claude Code hooks are configured in your [settings files](/en/docs/claude-code/settings):
* `~/.claude/settings.json` - User settings
* `.claude/settings.json` - Project settings
* `.claude/settings.local.json` - Local project settings (not committed)
* Enterprise managed policy settings
### Structure
Hooks are organized by matchers, where each matcher can have multiple hooks:
```json theme={null}
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{
"type": "command",
"command": "your-command-here"
}
]
}
]
}
}
```
* **matcher**: Pattern to match tool names, case-sensitive (only applicable for
`PreToolUse` 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`
that don't use matchers, you can omit the matcher field:
```json theme={null}
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "/path/to/prompt-validator.py"
}
]
}
]
}
}
```
### Project-Specific Hook Scripts
You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when
Claude Code spawns the hook command) to reference scripts stored in your project,
ensuring they work regardless of Claude's current directory:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"
}
]
}
]
}
}
```
### 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.
**How plugin hooks work**:
* Plugin hooks are defined in the plugin's `hooks/hooks.json` file or in a file given by a custom path to the `hooks` field.
* When a plugin is enabled, its hooks are merged with user and project hooks
* Multiple hooks from different sources can respond to the same event
* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files
**Example plugin hook configuration**:
```json theme={null}
{
"description": "Automatic code formatting",
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
"timeout": 30
}
]
}
]
}
}
```
<Note>
Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose.
</Note>
<Note>
Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.
</Note>
**Environment variables for plugins**:
* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin 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.
## Hook Events
### PreToolUse
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))
* `Bash` - Shell commands
* `Glob` - File pattern matching
* `Grep` - Content search
* `Read` - File reading
* `Edit` - File editing
* `Write` - File writing
* `WebFetch`, `WebSearch` - Web operations
### PostToolUse
Runs immediately after a tool completes successfully.
Recognizes the same matcher values as PreToolUse.
### Notification
Runs when Claude Code sends notifications. Notifications are sent when:
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"
### UserPromptSubmit
Runs when the user submits a prompt, before Claude processes it. This allows you
to add additional context based on the prompt/conversation, validate prompts, or
block certain types of prompts.
### Stop
Runs when the main Claude Code agent has finished responding. Does not run if
the stoppage occurred due to a user interrupt.
### SubagentStop
Runs when a Claude Code subagent (Task tool call) has finished responding.
### PreCompact
Runs before Claude Code is about to run a compact operation.
**Matchers:**
* `manual` - Invoked from `/compact`
* `auto` - Invoked from auto-compact (due to full context window)
### SessionStart
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.
**Matchers:**
* `startup` - Invoked from startup
* `resume` - Invoked from `--resume`, `--continue`, or `/resume`
* `clear` - Invoked from `/clear`
* `compact` - Invoked from auto or manual compact.
### SessionEnd
Runs when a Claude Code session ends. Useful for cleanup tasks, logging session
statistics, or saving session state.
The `reason` field in the hook input will be one of:
* `clear` - Session cleared with /clear command
* `logout` - User logged out
* `prompt_input_exit` - User exited while prompt input was visible
* `other` - Other exit reasons
## Hook Input
Hooks receive JSON data via stdin containing session information and
event-specific data:
```typescript theme={null}
{
// Common fields
session_id: string
transcript_path: string // Path to conversation JSON
cwd: string // The current working directory when the hook is invoked
// Event-specific fields
hook_event_name: string
...
}
```
### PreToolUse Input
The exact schema for `tool_input` depends on the tool.
```json theme={null}
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "PreToolUse",
"tool_name": "Write",
"tool_input": {
"file_path": "/path/to/file.txt",
"content": "file content"
}
}
```
### PostToolUse Input
The exact schema for `tool_input` and `tool_response` depends on the tool.
```json theme={null}
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "PostToolUse",
"tool_name": "Write",
"tool_input": {
"file_path": "/path/to/file.txt",
"content": "file content"
},
"tool_response": {
"filePath": "/path/to/file.txt",
"success": true
}
}
```
### Notification Input
```json theme={null}
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "Notification",
"message": "Task completed successfully"
}
```
### UserPromptSubmit Input
```json theme={null}
{
"session_id": "abc123",
"transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "UserPromptSubmit",
"prompt": "Write a function to calculate the factorial of a number"
}
```
### Stop and SubagentStop Input
`stop_hook_active` is true when Claude Code is already continuing as a result of
a stop hook. Check this value or process the transcript to prevent Claude Code
from running indefinitely.
```json theme={null}
{
"session_id": "abc123",
"transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"hook_event_name": "Stop",
"stop_hook_active": true
}
```
### PreCompact Input
For `manual`, `custom_instructions` comes from what the user passes into
`/compact`. For `auto`, `custom_instructions` is empty.
```json theme={null}
{
"session_id": "abc123",
"transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"hook_event_name": "PreCompact",
"trigger": "manual",
"custom_instructions": ""
}
```
### SessionStart Input
```json theme={null}
{
"session_id": "abc123",
"transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"hook_event_name": "SessionStart",
"source": "startup"
}
```
### SessionEnd Input
```json theme={null}
{
"session_id": "abc123",
"transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",
"cwd": "/Users/...",
"hook_event_name": "SessionEnd",
"reason": "exit"
}
```
## Hook Output
There are two 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.
### Simple: Exit Code
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.
<Warning>
Reminder: Claude Code does not see stdout if the exit code is 0, except for
the `UserPromptSubmit` hook where stdout is injected as context.
</Warning>
#### 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 |
### Advanced: JSON Output
Hooks can return structured JSON in `stdout` for more sophisticated control:
#### Common JSON Fields
All hook types can include these optional fields:
```json theme={null}
{
"continue": true, // Whether Claude should continue after hook execution (default: true)
"stopReason": "string", // Message shown when continue is false
"suppressOutput": true, // Hide stdout from transcript mode (default: false)
"systemMessage": "string" // Optional warning message shown to the user
}
```
If `continue` is false, Claude stops processing after the hooks run.
* For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which
only blocks a specific tool call and provides automatic feedback to Claude.
* For `PostToolUse`, this is different from `"decision": "block"`, which
provides automated feedback to Claude.
* For `UserPromptSubmit`, this prevents the prompt from being processed.
* For `Stop` and `SubagentStop`, this takes precedence over any
`"decision": "block"` output.
* In all cases, `"continue" = false` takes precedence over any
`"decision": "block"` output.
`stopReason` accompanies `continue` with a reason shown to the user, not shown
to Claude.
#### `PreToolUse` Decision Control
`PreToolUse` hooks can control whether a tool call proceeds.
* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown
to the user but not to Claude.
* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is
shown to Claude.
* `"ask"` asks the user to confirm the tool call in the UI.
`permissionDecisionReason` is shown to the user but not to Claude.
```json theme={null}
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow" | "deny" | "ask",
"permissionDecisionReason": "My reason here"
}
}
```
<Note>
The `decision` and `reason` fields are deprecated for PreToolUse hooks.
Use `hookSpecificOutput.permissionDecision` and
`hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields
`"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.
</Note>
#### `PostToolUse` Decision Control
`PostToolUse` hooks can provide feedback to Claude after tool execution.
* `"block"` automatically prompts Claude with `reason`.
* `undefined` does nothing. `reason` is ignored.
* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.
```json theme={null}
{
"decision": "block" | undefined,
"reason": "Explanation for decision",
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
"additionalContext": "Additional information for Claude"
}
}
```
#### `UserPromptSubmit` Decision Control
`UserPromptSubmit` hooks can control whether a user prompt is processed.
* `"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.
```json theme={null}
{
"decision": "block" | undefined,
"reason": "Explanation for decision",
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": "My additional context here"
}
}
```
#### `Stop`/`SubagentStop` Decision Control
`Stop` and `SubagentStop` hooks can control whether Claude must continue.
* `"block"` prevents Claude from stopping. You must populate `reason` for Claude
to know how to proceed.
* `undefined` allows Claude to stop. `reason` is ignored.
```json theme={null}
{
"decision": "block" | undefined,
"reason": "Must be provided when Claude is blocked from stopping"
}
```
#### `SessionStart` Decision Control
`SessionStart` hooks allow you to load in context at the start of a session.
* `"hookSpecificOutput.additionalContext"` adds the string to the context.
* Multiple hooks' `additionalContext` values are concatenated.
```json theme={null}
{
"hookSpecificOutput": {
"hookEventName": "SessionStart",
"additionalContext": "My additional context here"
}
}
```
#### `SessionEnd` Decision Control
`SessionEnd` hooks run when a session ends. They cannot block session termination
but can perform cleanup tasks.
#### Exit Code Example: Bash Command Validation
```python theme={null}
#!/usr/bin/env python3
import json
import re
import sys
# Define validation rules as a list of (regex pattern, message) tuples
VALIDATION_RULES = [
(
r"\bgrep\b(?!.*\|)",
"Use 'rg' (ripgrep) instead of 'grep' for better performance and features",
),
(
r"\bfind\s+\S+\s+-name\b",
"Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",
),
]
def validate_command(command: str) -> list[str]:
issues = []
for pattern, message in VALIDATION_RULES:
if re.search(pattern, command):
issues.append(message)
return issues
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
command = tool_input.get("command", "")
if tool_name != "Bash" or not command:
sys.exit(1)
# Validate the command
issues = validate_command(command)
if issues:
for message in issues:
print(f"• {message}", file=sys.stderr)
# Exit code 2 blocks tool call and shows stderr to Claude
sys.exit(2)
```
#### JSON Output Example: UserPromptSubmit to Add Context and Validation
<Note>
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
</Note>
```python theme={null}
#!/usr/bin/env python3
import json
import sys
import re
import datetime
# Load input from stdin
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
prompt = input_data.get("prompt", "")
# Check for sensitive patterns
sensitive_patterns = [
(r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),
]
for pattern, message in sensitive_patterns:
if re.search(pattern, prompt):
# Use JSON output to block with a specific reason
output = {
"decision": "block",
"reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."
}
print(json.dumps(output))
sys.exit(0)
# Add current time to context
context = f"Current time: {datetime.datetime.now()}"
print(context)
"""
The following is also equivalent:
print(json.dumps({
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": context,
},
}))
"""
# Allow the prompt to proceed with the additional context
sys.exit(0)
```
#### JSON Output Example: PreToolUse with Approval
```python theme={null}
#!/usr/bin/env python3
import json
import sys
# Load input from stdin
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
# Example: Auto-approve file reads for documentation files
if tool_name == "Read":
file_path = tool_input.get("file_path", "")
if file_path.endswith((".md", ".mdx", ".txt", ".json")):
# Use JSON output to auto-approve the tool call
output = {
"decision": "approve",
"reason": "Documentation file auto-approved",
"suppressOutput": True # Don't show in transcript mode
}
print(json.dumps(output))
sys.exit(0)
# For other cases, let the normal permission flow proceed
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
provide tools, they appear with a special naming pattern that you can match in
your hooks.
### MCP Tool Naming
MCP tools follow the pattern `mcp__<server>__<tool>`, for example:
* `mcp__memory__create_entities` - Memory server's create entities tool
* `mcp__filesystem__read_file` - Filesystem server's read file tool
* `mcp__github__search_repositories` - GitHub server's search tool
### Configuring Hooks for MCP Tools
You can target specific MCP tools or entire MCP servers:
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__memory__.*",
"hooks": [
{
"type": "command",
"command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"
}
]
},
{
"matcher": "mcp__.*__write.*",
"hooks": [
{
"type": "command",
"command": "/home/user/scripts/validate-mcp-write.py"
}
]
}
]
}
}
```
## Examples
<Tip>
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.
</Tip>
## Security Considerations
### Disclaimer
**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on
your system automatically. By using hooks, you acknowledge that:
* You are solely responsible for the commands you configure
* Hooks can modify, delete, or access any files your user account can access
* Malicious or poorly written hooks can cause data loss or system damage
* Anthropic provides no warranty and assumes no liability for any damages
resulting from hook usage
* You should thoroughly test hooks in a safe environment before production use
Always review and understand any hook commands before adding them to your
configuration.
### Security Best Practices
Here are some key practices for writing more secure hooks:
1. **Validate and sanitize inputs** - Never trust input data blindly
2. **Always quote shell variables** - Use `"$VAR"` not `$VAR`
3. **Block path traversal** - Check for `..` in file paths
4. **Use absolute paths** - Specify full paths for scripts (use
"\$CLAUDE\_PROJECT\_DIR" for the project path)
5. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.
### Configuration Safety
Direct edits to hooks in settings files don't take effect immediately. Claude
Code:
1. Captures a snapshot of hooks at startup
2. Uses this snapshot throughout the session
3. Warns if hooks are modified externally
4. Requires review in `/hooks` menu for changes to apply
This prevents malicious hook modifications from affecting your current session.
## Hook Execution Details
* **Timeout**: 60-second execution limit by default, configurable per command.
* A timeout for an individual command does not affect the other commands.
* **Parallelization**: All matching hooks run in parallel
* **Deduplication**: Multiple identical hook commands are deduplicated automatically
* **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)
* **Input**: JSON via stdin
* **Output**:
* PreToolUse/PostToolUse/Stop/SubagentStop: Progress shown in transcript (Ctrl-R)
* Notification/SessionEnd: Logged to debug only (`--debug`)
* UserPromptSubmit/SessionStart: stdout added as context for Claude
## Debugging
### Basic Troubleshooting
If your hooks aren't working:
1. **Check configuration** - Run `/hooks` to see if your hook is registered
2. **Verify syntax** - Ensure your JSON settings are valid
3. **Test commands** - Run hook commands manually first
4. **Check permissions** - Make sure scripts are executable
5. **Review logs** - Use `claude --debug` to see hook execution details
Common issues:
* **Quotes not escaped** - Use `\"` inside JSON strings
* **Wrong matcher** - Check tool names match exactly (case-sensitive)
* **Command not found** - Use full paths for scripts
### Advanced Debugging
For complex hook issues:
1. **Inspect hook execution** - Use `claude --debug` to see detailed hook
execution
2. **Validate JSON schemas** - Test hook input/output with external tools
3. **Check environment variables** - Verify Claude Code's environment is correct
4. **Test edge cases** - Try hooks with unusual file paths or inputs
5. **Monitor system resources** - Check for resource exhaustion during hook
execution
6. **Use structured logging** - Implement logging in your hook scripts
### Debug Output Example
Use `claude --debug` to see hook execution details:
```
[DEBUG] Executing hooks for PostToolUse:Write
[DEBUG] Getting matching hook commands for PostToolUse with query: Write
[DEBUG] Found 1 hook matchers in settings
[DEBUG] Matched 1 hooks for query "Write"
[DEBUG] Found 1 hook commands to execute
[DEBUG] Executing hook command: <Your command> with timeout 60000ms
[DEBUG] Hook command completed with status 0: <Your stdout>
```
Progress messages appear in transcript mode (Ctrl-R) showing:
* Which hook is running
* Command being executed
* Success/failure status
* Output or error messages

View File

@@ -0,0 +1,200 @@
# Identity and Access Management
> Learn how to configure user authentication, authorization, and access controls for Claude Code in your organization.
## Authentication methods
Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of three ways:
* Claude API via the Claude Console
* Amazon Bedrock
* Google Vertex AI
### Claude API authentication
**To set up Claude Code access for your team via Claude API:**
1. Use your existing Claude Console account or create a new Claude Console account
2. You can add users through either method below:
* Bulk invite users from within the Console (Console -> Settings -> Members -> Invite)
* [Set up SSO](https://support.claude.com/en/articles/10280258-setting-up-single-sign-on-on-the-api-console)
3. When inviting users, they need one of the following roles:
* "Claude Code" role means users can only create Claude Code API keys
* "Developer" role means users can create any kind of API key
4. Each invited user needs to complete these steps:
* Accept the Console invite
* [Check system requirements](/en/docs/claude-code/setup#system-requirements)
* [Install Claude Code](/en/docs/claude-code/setup#installation)
* Login with Console account credentials
### Cloud provider authentication
**To set up Claude Code access for your team via Bedrock or Vertex:**
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)
## Access control and permissions
We support fine-grained permissions so that you're able to specify exactly what the agent is allowed to do (e.g. run tests, run linter) and what it is not allowed to do (e.g. update cloud infrastructure). These permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers.
### Permission system
Claude Code uses a tiered permission system to balance power and safety:
| Tool Type | Example | Approval Required | "Yes, don't ask again" Behavior |
| :---------------- | :------------------- | :---------------- | :-------------------------------------------- |
| Read-only | File reads, LS, Grep | No | N/A |
| Bash Commands | Shell execution | Yes | Permanently per project directory and command |
| File Modification | Edit/write files | Yes | Until session end |
### Configuring permissions
You can view & manage Claude Code's tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from.
* **Allow** rules will allow Claude Code to use the specified tool without further manual approval.
* **Ask** rules will ask the user for confirmation whenever Claude Code tries to use the specified tool. Ask rules take precedence over allow rules.
* **Deny** rules will prevent Claude Code from using the specified tool. Deny rules take precedence over allow and ask rules.
* **Additional directories** extend Claude's file access to directories beyond the initial working directory.
* **Default mode** controls Claude's permission behavior when encountering new requests.
Permission rules use the format: `Tool` or `Tool(optional-specifier)`
A rule that is just the tool name matches any use of that tool. For example, adding `Bash` to the list of allow rules would allow Claude Code to use the Bash tool without requiring user approval.
#### Permission modes
Claude Code supports several permission modes that can be set as the `defaultMode` in [settings files](/en/docs/claude-code/settings#settings-files):
| Mode | Description |
| :------------------ | :--------------------------------------------------------------------------- |
| `default` | Standard behavior - prompts for permission on first use of each tool |
| `acceptEdits` | Automatically accepts file edit permissions for the session |
| `plan` | Plan Mode - Claude can analyze but not modify files or execute commands |
| `bypassPermissions` | Skips all permission prompts (requires safe environment - see warning below) |
#### Working directories
By default, Claude has access to files in the directory where it was launched. You can extend this access:
* **During startup**: Use `--add-dir <path>` CLI argument
* **During session**: Use `/add-dir` slash command
* **Persistent configuration**: Add to `additionalDirectories` in [settings files](/en/docs/claude-code/settings#settings-files)
Files in additional directories follow the same permission rules as the original working directory - they become readable without prompts, and file editing permissions follow the current permission mode.
#### Tool-specific permission rules
Some tools support more fine-grained permission controls:
**Bash**
* `Bash(npm run build)` Matches the exact Bash command `npm run build`
* `Bash(npm run test:*)` Matches Bash commands starting with `npm run test`
* `Bash(curl http://site.com/:*)` Matches curl commands that start with exactly `curl http://site.com/`
<Tip>
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`
</Tip>
<Warning>
Important limitations of Bash permission patterns:
1. This tool uses **prefix matches**, not regex or glob patterns
2. The wildcard `:*` only works at the end of a pattern to match any continuation
3. Patterns like `Bash(curl http://github.com/:*)` can be bypassed in many ways:
* Options before URL: `curl -X GET http://github.com/...` won't match
* Different protocol: `curl https://github.com/...` won't match
* Redirects: `curl -L http://bit.ly/xyz` (redirects to github)
* Variables: `URL=http://github.com && curl $URL` won't match
* Extra spaces: `curl http://github.com` won't match
For more reliable URL filtering, consider:
* Using the WebFetch tool with `WebFetch(domain:github.com)` permission
* Instructing Claude Code about your allowed curl patterns via CLAUDE.md
* Using hooks for custom permission validation
</Warning>
**Read & Edit**
`Edit` rules apply to all built-in tools that edit files. Claude will make a best-effort attempt to apply `Read` rules to all built-in tools that read files like Grep, Glob, and LS.
Read & Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types:
| Pattern | Meaning | Example | Matches |
| ------------------ | -------------------------------------- | -------------------------------- | ---------------------------------- |
| `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |
| `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |
| `/path` | Path **relative to settings file** | `Edit(/src/**/*.ts)` | `<settings file path>/src/**/*.ts` |
| `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `<cwd>/*.env` |
<Warning>
A pattern like `/Users/alice/file` is NOT an absolute path - it's relative to your settings file! Use `//Users/alice/file` for absolute paths.
</Warning>
* `Edit(/docs/**)` - Edits in `<project>/docs/` (NOT `/docs/`!)
* `Read(~/.zshrc)` - Reads your home directory's `.zshrc`
* `Edit(//tmp/scratch.txt)` - Edits the absolute path `/tmp/scratch.txt`
* `Read(src/**)` - Reads from `<current-directory>/src/`
**WebFetch**
* `WebFetch(domain:example.com)` Matches fetch requests to example.com
**MCP**
* `mcp__puppeteer` Matches any tool provided by the `puppeteer` server (name configured in Claude Code)
* `mcp__puppeteer__puppeteer_navigate` Matches the `puppeteer_navigate` tool provided by the `puppeteer` server
<Warning>
Unlike other permission types, MCP permissions do NOT support wildcards (`*`).
To approve all tools from an MCP server:
* ✅ Use: `mcp__github` (approves ALL GitHub tools)
* ❌ Don't use: `mcp__github__*` (wildcards are not supported)
To approve specific tools only, list each one:
* ✅ Use: `mcp__github__get_issue`
* ✅ Use: `mcp__github__list_issues`
</Warning>
### 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.
### 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:
* 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.
### Settings precedence
When multiple settings sources exist, they are applied in the following order (highest to lowest precedence):
1. Enterprise policies
2. Command line arguments
3. Local project settings (`.claude/settings.local.json`)
4. Shared project settings (`.claude/settings.json`)
5. User settings (`~/.claude/settings.json`)
This hierarchy ensures that organizational policies are always enforced while still allowing flexibility at the project and user levels where appropriate.
## Credential management
Claude Code securely manages your authentication credentials:
* **Storage location**: On macOS, API keys, OAuth tokens, and other credentials are stored in the encrypted macOS Keychain.
* **Supported authentication types**: Claude.ai credentials, Claude API credentials, 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.
* **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.

View File

@@ -0,0 +1,169 @@
# Interactive mode
> Complete reference for keyboard shortcuts, input modes, and interactive features in Claude Code sessions.
## Keyboard shortcuts
<Note>
Keyboard shortcuts may vary by platform and terminal. Press `?` to see available shortcuts for your environment.
</Note>
### 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 |
### 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 |
<Tip>
Configure your preferred line break behavior in terminal settings. Run `/terminal-setup` to install Shift+Enter binding for iTerm2 and VS Code terminals.
</Tip>
### 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/docs/claude-code/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
Enable vim-style editing with `/vim` command or configure permanently via `/config`.
### Mode switching
| Command | Action | From mode |
| :------ | :-------------------------- | :-------- |
| `Esc` | Enter NORMAL mode | INSERT |
| `i` | Insert before cursor | NORMAL |
| `I` | Insert at beginning of line | NORMAL |
| `a` | Insert after cursor | NORMAL |
| `A` | Insert at end of line | NORMAL |
| `o` | Open line below | NORMAL |
| `O` | Open line above | NORMAL |
### Navigation (NORMAL mode)
| Command | Action |
| :-------------- | :------------------------ |
| `h`/`j`/`k`/`l` | Move left/down/up/right |
| `w` | Next word |
| `e` | End of word |
| `b` | Previous word |
| `0` | Beginning of line |
| `$` | End of line |
| `^` | First non-blank character |
| `gg` | Beginning of input |
| `G` | End of input |
### Editing (NORMAL mode)
| Command | Action |
| :------------- | :---------------------- |
| `x` | Delete character |
| `dd` | Delete line |
| `D` | Delete to end of line |
| `dw`/`de`/`db` | Delete word/to end/back |
| `cc` | Change line |
| `C` | Change to end of line |
| `cw`/`ce`/`cb` | Change word/to end/back |
| `.` | Repeat last change |
## Command history
Claude Code maintains command history for the current session:
* History is stored per working directory
* Cleared with `/clear` command
* Use Up/Down arrows to navigate (see keyboard shortcuts above)
* **Note**: History expansion (`!`) is disabled by default
### Reverse search with Ctrl+R
Press `Ctrl+R` to interactively search through your command history:
1. **Start search**: Press `Ctrl+R` to activate reverse history search
2. **Type query**: Enter text to search for in previous commands - the search term will be highlighted in matching results
3. **Navigate matches**: Press `Ctrl+R` again to cycle through older matches
4. **Accept match**:
* Press `Tab` or `Esc` to accept the current match and continue editing
* Press `Enter` to accept and execute the command immediately
5. **Cancel search**:
* Press `Ctrl+C` to cancel and restore your original input
* Press `Backspace` on empty search to cancel
The search displays matching commands with the search term highlighted, making it easy to find and reuse previous inputs.
## Background bash commands
Claude Code supports running bash commands in the background, allowing you to continue working while long-running processes execute.
### How backgrounding works
When Claude Code runs a command in the background, it runs the command asynchronously and immediately returns a background task ID. Claude Code can respond to new prompts while the command continues executing in the background.
To run commands in the background, you can either:
* Prompt Claude Code to run a command in the background
* Press Ctrl+B to move a regular Bash tool invocation to the background. (Tmux users must press Ctrl+B twice due to tmux's prefix key.)
**Key features:**
* Output is buffered and Claude can retrieve it using the BashOutput tool
* Background tasks have unique IDs for tracking and output retrieval
* Background tasks are automatically cleaned up when Claude Code exits
**Common backgrounded commands:**
* Build tools (webpack, vite, make)
* Package managers (npm, yarn, pnpm)
* Test runners (jest, pytest)
* Development servers
* Long-running processes (docker, terraform)
### Bash mode with `!` prefix
Run bash commands directly without going through Claude by prefixing your input with `!`:
```bash theme={null}
! npm test
! git status
! ls -la
```
Bash mode:
* Adds the command and its output to the conversation context
* Shows real-time progress and output
* Supports the same `Ctrl+B` backgrounding for long-running commands
* Does not require Claude to interpret or approve the command
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

View File

@@ -0,0 +1,150 @@
# JetBrains IDEs
> Use Claude Code with JetBrains IDEs including IntelliJ, PyCharm, WebStorm, and more
Claude Code integrates with JetBrains IDEs through a dedicated plugin, providing features like interactive diff viewing, selection context sharing, and more.
## Supported IDEs
The Claude Code plugin works with most JetBrains IDEs, including:
* IntelliJ IDEA
* PyCharm
* Android Studio
* WebStorm
* PhpStorm
* GoLand
## Features
* **Quick launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open Claude Code directly from your editor, or click the Claude Code button in the UI
* **Diff viewing**: Code changes can be displayed directly in the IDE diff viewer instead of the terminal
* **Selection context**: The current selection/tab in the IDE is automatically shared with Claude Code
* **File reference shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references (e.g., @File#L1-99)
* **Diagnostic sharing**: Diagnostic errors (lint, syntax, etc.) from the IDE are automatically shared with Claude as you work
## Installation
### Marketplace Installation
Find and install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains marketplace and restart your IDE.
### 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.
<Note>
After installing the plugin, you must restart your IDE completely for it to take effect. You may need to restart multiple times.
</Note>
## Usage
### From Your IDE
Run `claude` from your IDE's integrated terminal, and all integration features will be active.
### From External Terminals
Use the `/ide` command in any external terminal to connect Claude Code to your JetBrains IDE and activate all features:
```bash theme={null}
claude
> /ide
```
If you want Claude to have access to the same files as your IDE, start Claude Code from the same directory as your IDE project root.
## Configuration
### Claude Code Settings
Configure IDE integration through Claude Code's settings:
1. Run `claude`
2. Enter the `/config` command
3. Set the diff tool to `auto` for automatic IDE detection
### Plugin Settings
Configure the Claude Code plugin by going to **Settings → Tools → Claude Code \[Beta]**:
#### General Settings
* **Claude command**: Specify a custom command to run Claude (e.g., `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)
<Tip>
For WSL users: Set `wsl -d Ubuntu -- bash -lic "claude"` as your Claude command (replace `Ubuntu` with your WSL distribution name)
</Tip>
#### ESC Key Configuration
If the ESC key doesn't interrupt Claude Code operations in JetBrains terminals:
1. Go to **Settings → Tools → Terminal**
2. Either:
* Uncheck "Move focus to the editor with Escape", or
* Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut
3. Apply the changes
This allows the ESC key to properly interrupt Claude Code operations.
## Special Configurations
### Remote Development
<Warning>
When using JetBrains Remote Development, you must install the plugin in the remote host via **Settings → Plugin (Host)**.
</Warning>
The plugin must be installed on the remote host, not on your local client machine.
### WSL Configuration
<Warning>
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.
</Warning>
WSL configuration may require:
* Proper terminal configuration
* Networking mode adjustments
* Firewall settings updates
## Troubleshooting
### Plugin Not Working
* Ensure you're running Claude Code from the project root directory
* Check that the JetBrains plugin is enabled in the IDE settings
* Completely restart the IDE (you may need to do this multiple times)
* For Remote Development, ensure the plugin is installed in the remote host
### IDE Not Detected
* Verify the plugin is installed and enabled
* Restart the IDE completely
* Check that you're running Claude Code from the integrated terminal
* For WSL users, see the [WSL troubleshooting guide](/en/docs/claude-code/troubleshooting#jetbrains-ide-not-detected-on-wsl2)
### Command Not Found
If clicking the Claude icon shows "command not found":
1. Verify Claude Code is installed: `npm list -g @anthropic-ai/claude-code`
2. Configure the Claude command path in plugin settings
3. For WSL users, use the WSL command format mentioned in the configuration section
## Security Considerations
When Claude Code runs in a JetBrains IDE with auto-edit permissions enabled, it may be able to modify IDE configuration files that can be automatically executed by your IDE. This may increase the risk of running Claude Code in auto-edit mode and allow bypassing Claude Code's permission prompts for bash execution.
When running in JetBrains IDEs, consider:
* Using manual approval mode for edits
* Taking extra care to ensure Claude is only used with trusted prompts
* Being aware of which files Claude Code has access to modify
For additional help, see our [troubleshooting guide](/en/docs/claude-code/troubleshooting).

View File

@@ -0,0 +1,36 @@
# Legal and compliance
> Legal agreements, compliance certifications, and security information for Claude Code.
## Legal agreements
### License
Your use of Claude Code is subject to:
* [Commercial Terms](https://www.anthropic.com/legal/commercial-terms) - for Team, Enterprise, and Claude API users
* [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) - for Free, Pro, and Max users
### Commercial agreements
Whether you're using the Claude API directly (1P) or accessing it through AWS Bedrock or Google Vertex (3P), your existing commercial agreement will apply to Claude Code usage, unless we've mutually agreed otherwise.
## Compliance
### Healthcare compliance (BAA)
If a customer has a Business Associate Agreement (BAA) with us, and wants to use Claude Code, the BAA will automatically extend to cover Claude Code if the customer has executed a BAA and has Zero Data Retention (ZDR) activated. The BAA will be applicable to that customer's API traffic flowing through Claude Code.
## Security and trust
### Trust and safety
You can find more information in the [Anthropic Trust Center](https://trust.anthropic.com) and [Transparency Hub](https://www.anthropic.com/transparency).
### Security vulnerability reporting
Anthropic manages our security program through HackerOne. [Use this form to report vulnerabilities](https://hackerone.com/anthropic-vdp/reports/new?type=team\&report_type=vulnerability).
***
© Anthropic PBC. All rights reserved. Use is subject to applicable Anthropic Terms of Service.

View File

@@ -0,0 +1,145 @@
# 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.
LLM gateways provide a centralized proxy layer between Claude Code and model providers, offering:
* **Centralized authentication** - Single point for API key management
* **Usage tracking** - Monitor usage across teams and projects
* **Cost controls** - Implement budgets and rate limits
* **Audit logging** - Track all model interactions for compliance
* **Model routing** - Switch between providers without code changes
## LiteLLM configuration
<Note>
LiteLLM is a third-party proxy service. Anthropic doesn't endorse, maintain, or audit LiteLLM's security or functionality. This guide is provided for informational purposes and may become outdated. Use at your own discretion.
</Note>
### Prerequisites
* Claude Code updated to the latest version
* LiteLLM Proxy Server deployed and accessible
* Access to Claude models through your chosen provider
### Basic LiteLLM setup
**Configure Claude Code**:
#### Authentication methods
##### Static API key
Simplest method using a fixed API key:
```bash theme={null}
# Set in environment
export ANTHROPIC_AUTH_TOKEN=sk-litellm-static-key
# Or in Claude Code settings
{
"env": {
"ANTHROPIC_AUTH_TOKEN": "sk-litellm-static-key"
}
}
```
This value will be sent as the `Authorization` header.
##### Dynamic API key with helper
For rotating keys or per-user authentication:
1. Create an API key helper script:
```bash theme={null}
#!/bin/bash
# ~/bin/get-litellm-key.sh
# Example: Fetch key from vault
vault kv get -field=api_key secret/litellm/claude-code
# Example: Generate JWT token
jwt encode \
--secret="${JWT_SECRET}" \
--exp="+1h" \
'{"user":"'${USER}'","team":"engineering"}'
```
2. Configure Claude Code settings to use the helper:
```json theme={null}
{
"apiKeyHelper": "~/bin/get-litellm-key.sh"
}
```
3. Set token refresh interval:
```bash theme={null}
# Refresh every hour (3600000 ms)
export CLAUDE_CODE_API_KEY_HELPER_TTL_MS=3600000
```
This value will be sent as `Authorization` and `X-Api-Key` headers. The `apiKeyHelper` has lower precedence than `ANTHROPIC_AUTH_TOKEN` or `ANTHROPIC_API_KEY`.
#### Unified endpoint (recommended)
Using LiteLLM's [Anthropic format endpoint](https://docs.litellm.ai/docs/anthropic_unified):
```bash theme={null}
export ANTHROPIC_BASE_URL=https://litellm-server:4000
```
**Benefits of the unified endpoint over pass-through endpoints:**
* Load balancing
* Fallbacks
* Consistent support for cost tracking and end-user tracking
#### Provider-specific pass-through endpoints (alternative)
##### Claude API through LiteLLM
Using [pass-through endpoint](https://docs.litellm.ai/docs/pass_through/anthropic_completion):
```bash theme={null}
export ANTHROPIC_BASE_URL=https://litellm-server:4000/anthropic
```
##### Amazon Bedrock through LiteLLM
Using [pass-through endpoint](https://docs.litellm.ai/docs/pass_through/bedrock):
```bash theme={null}
export ANTHROPIC_BEDROCK_BASE_URL=https://litellm-server:4000/bedrock
export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1
export CLAUDE_CODE_USE_BEDROCK=1
```
##### Google Vertex AI through LiteLLM
Using [pass-through endpoint](https://docs.litellm.ai/docs/pass_through/vertex_ai):
```bash theme={null}
export ANTHROPIC_VERTEX_BASE_URL=https://litellm-server:4000/vertex_ai/v1
export ANTHROPIC_VERTEX_PROJECT_ID=your-gcp-project-id
export CLAUDE_CODE_SKIP_VERTEX_AUTH=1
export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION=us-east5
```
### 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)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,103 @@
# Manage Claude's memory
> Learn how to manage Claude Code's memory across sessions with different memory locations and best practices.
Claude Code can remember your preferences across sessions, like style guidelines and common commands in your workflow.
## Determine memory type
Claude Code offers four memory locations in a hierarchical structure, each serving a different purpose:
| Memory Type | Location | Purpose | Use Case Examples | Shared With |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |
| **Enterprise policy** | macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`<br />Linux: `/etc/claude-code/CLAUDE.md`<br />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) |
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.md imports
CLAUDE.md files can import additional files using `@path/to/import` syntax. The following example imports 3 files:
```
See @README for project overview and @package.json for available npm commands for this project.
# Additional Instructions
- git workflow @docs/git-instructions.md
```
Both relative and absolute paths are allowed. 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.
```
# Individual Preferences
- @~/.claude/my-project-instructions.md
```
To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks.
```
This code span will not be treated as an import: `@anthropic-ai/claude-code`
```
Imported files can recursively import additional files, with a max-depth of 5 hops. You can see what memory files are loaded by running `/memory` command.
## How Claude looks up memories
Claude Code reads memories recursively: starting in the cwd, Claude Code recurses up to (but not including) the root directory */* and reads any CLAUDE.md or CLAUDE.local.md files it finds. This is especially convenient when working in large repositories where you run Claude Code in *foo/bar/*, and have memories in both *foo/CLAUDE.md* and *foo/bar/CLAUDE.md*.
Claude will also discover CLAUDE.md nested in subtrees under your current working directory. Instead of loading them at launch, they are only included when Claude reads files in those subtrees.
## 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.
## Set up project memory
Suppose you want to set up a CLAUDE.md file to store important project information, conventions, and frequently used commands. Project memory can be stored in either `./CLAUDE.md` or `./.claude/CLAUDE.md`.
Bootstrap a CLAUDE.md for your codebase with the following command:
```
> /init
```
<Tip>
Tips:
* Include frequently used commands (build, test, lint) to avoid repeated searches
* Document code style preferences and naming conventions
* Add important architectural patterns specific to your project
* CLAUDE.md memories can be used for both instructions shared with your team and for your individual preferences.
</Tip>
## 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`
2. Deploy via your configuration management system (MDM, Group Policy, Ansible, etc.) to ensure consistent distribution across all developer machines.
## Memory best practices
* **Be specific**: "Use 2-space indentation" is better than "Format code properly".
* **Use structure to organize**: Format each individual memory as a bullet point and group related memories under descriptive markdown headings.
* **Review periodically**: Update memories as your project evolves to ensure Claude is always using the most up to date information and context.

View File

@@ -0,0 +1,327 @@
# Migrate to Claude Agent SDK
> Guide for migrating the Claude Code TypeScript and Python SDKs to the Claude Agent SDK
## Overview
The Claude Code SDK has been renamed to the **Claude Agent SDK** and its documentation has been reorganized. This change reflects the SDK's broader capabilities for building AI agents beyond just coding tasks.
## What's Changed
| Aspect | Old | New |
| :------------------------- | :----------------------------- | :------------------------------- |
| **Package Name (TS/JS)** | `@anthropic-ai/claude-code` | `@anthropic-ai/claude-agent-sdk` |
| **Python Package** | `claude-code-sdk` | `claude-agent-sdk` |
| **Documentation Location** | Claude Code docs → SDK section | API Guide → Agent SDK section |
<Note>
**Documentation Changes:** The Agent SDK documentation has moved from the Claude Code docs to the API Guide under a dedicated [Agent SDK](/en/api/agent-sdk/overview) section. The Claude Code docs now focus on the CLI tool and automation features.
</Note>
## Migration Steps
### For TypeScript/JavaScript Projects
**1. Uninstall the old package:**
```bash theme={null}
npm uninstall @anthropic-ai/claude-code
```
**2. Install the new package:**
```bash theme={null}
npm install @anthropic-ai/claude-agent-sdk
```
**3. Update your imports:**
Change all imports from `@anthropic-ai/claude-code` to `@anthropic-ai/claude-agent-sdk`:
```typescript theme={null}
// Before
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-code";
// After
import {
query,
tool,
createSdkMcpServer,
} from "@anthropic-ai/claude-agent-sdk";
```
**4. Update package.json dependencies:**
If you have the package listed in your `package.json`, update it:
```json theme={null}
// Before
{
"dependencies": {
"@anthropic-ai/claude-code": "^1.0.0"
}
}
// After
{
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.1.0"
}
}
```
That's it! No other code changes are required.
### For Python Projects
**1. Uninstall the old package:**
```bash theme={null}
pip uninstall claude-code-sdk
```
**2. Install the new package:**
```bash theme={null}
pip install claude-agent-sdk
```
**3. Update your imports:**
Change all imports from `claude_code_sdk` to `claude_agent_sdk`:
```python theme={null}
# Before
from claude_code_sdk import query, ClaudeCodeOptions
# After
from claude_agent_sdk import query, ClaudeAgentOptions
```
**4. Update type names:**
Change `ClaudeCodeOptions` to `ClaudeAgentOptions`:
```python theme={null}
# Before
from claude_agent_sdk import query, ClaudeCodeOptions
options = ClaudeCodeOptions(
model="claude-sonnet-4-5"
)
# After
from claude_agent_sdk import query, ClaudeAgentOptions
options = ClaudeAgentOptions(
model="claude-sonnet-4-5"
)
```
**5. Review [breaking changes](#breaking-changes)**
Make any code changes needed to complete the migration.
## Breaking changes
<Warning>
To improve isolation and explicit configuration, Claude Agent SDK v0.1.0 introduces breaking changes for users migrating from Claude Code SDK. Review this section carefully before migrating.
</Warning>
### Python: ClaudeCodeOptions renamed to ClaudeAgentOptions
**What changed:** The Python SDK type `ClaudeCodeOptions` has been renamed to `ClaudeAgentOptions`.
**Migration:**
```python theme={null}
# BEFORE (v0.0.x)
from claude_agent_sdk import query, ClaudeCodeOptions
options = ClaudeCodeOptions(
model="claude-sonnet-4-5",
permission_mode="acceptEdits"
)
# AFTER (v0.1.0)
from claude_agent_sdk import query, ClaudeAgentOptions
options = ClaudeAgentOptions(
model="claude-sonnet-4-5",
permission_mode="acceptEdits"
)
```
**Why this changed:** The type name now matches the "Claude Agent SDK" branding and provides consistency across the SDK's naming conventions.
### System prompt no longer default
**What changed:** The SDK no longer uses Claude Code's system prompt by default.
**Migration:**
<CodeGroup>
```typescript TypeScript theme={null}
// BEFORE (v0.0.x) - Used Claude Code's system prompt by default
const result = query({ prompt: "Hello" });
// AFTER (v0.1.0) - Uses empty system prompt by default
// To get the old behavior, explicitly request Claude Code's preset:
const result = query({
prompt: "Hello",
options: {
systemPrompt: { type: "preset", preset: "claude_code" }
}
});
// Or use a custom system prompt:
const result = query({
prompt: "Hello",
options: {
systemPrompt: "You are a helpful coding assistant"
}
});
```
```python Python theme={null}
# BEFORE (v0.0.x) - Used Claude Code's system prompt by default
async for message in query(prompt="Hello"):
print(message)
# AFTER (v0.1.0) - Uses empty system prompt by default
# To get the old behavior, explicitly request Claude Code's preset:
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
system_prompt={"type": "preset", "preset": "claude_code"} # Use the preset
)
):
print(message)
# Or use a custom system prompt:
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
system_prompt="You are a helpful coding assistant"
)
):
print(message)
```
</CodeGroup>
**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code's CLI-focused instructions.
### Settings Sources No Longer Loaded by Default
**What changed:** The SDK no longer reads from filesystem settings (CLAUDE.md, settings.json, slash commands, etc.) by default.
**Migration:**
<CodeGroup>
```typescript TypeScript theme={null}
// BEFORE (v0.0.x) - Loaded all settings automatically
const result = query({ prompt: "Hello" });
// Would read from:
// - ~/.claude/settings.json (user)
// - .claude/settings.json (project)
// - .claude/settings.local.json (local)
// - CLAUDE.md files
// - Custom slash commands
// AFTER (v0.1.0) - No settings loaded by default
// To get the old behavior:
const result = query({
prompt: "Hello",
options: {
settingSources: ["user", "project", "local"]
}
});
// Or load only specific sources:
const result = query({
prompt: "Hello",
options: {
settingSources: ["project"] // Only project settings
}
});
```
```python Python theme={null}
# BEFORE (v0.0.x) - Loaded all settings automatically
async for message in query(prompt="Hello"):
print(message)
# Would read from:
# - ~/.claude/settings.json (user)
# - .claude/settings.json (project)
# - .claude/settings.local.json (local)
# - CLAUDE.md files
# - Custom slash commands
# AFTER (v0.1.0) - No settings loaded by default
# To get the old behavior:
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
setting_sources=["user", "project", "local"]
)
):
print(message)
# Or load only specific sources:
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
setting_sources=["project"] # Only project settings
)
):
print(message)
```
</CodeGroup>
**Why this changed:** Ensures SDK applications have predictable behavior independent of local filesystem configurations. This is especially important for:
* **CI/CD environments** - Consistent behavior without local customizations
* **Deployed applications** - No dependency on filesystem settings
* **Testing** - Isolated test environments
* **Multi-tenant systems** - Prevent settings leakage between users
<Note>
**Backward compatibility:** If your application relied on filesystem settings (custom slash commands, CLAUDE.md instructions, etc.), add `settingSources: ['user', 'project', 'local']` to your options.
</Note>
## Why the Rename?
The Claude Code SDK was originally designed for coding tasks, but it has evolved into a powerful framework for building all types of AI agents. The new name "Claude Agent SDK" better reflects its capabilities:
* Building business agents (legal assistants, finance advisors, customer support)
* Creating specialized coding agents (SRE bots, security reviewers, code review agents)
* Developing custom agents for any domain with tool use, MCP integration, and more
## Getting Help
If you encounter any issues during migration:
**For TypeScript/JavaScript:**
1. Check that all imports are updated to use `@anthropic-ai/claude-agent-sdk`
2. Verify your package.json has the new package name
3. Run `npm install` to ensure dependencies are updated
**For Python:**
1. Check that all imports are updated to use `claude_agent_sdk`
2. Verify your requirements.txt or pyproject.toml has the new package name
3. Run `pip install claude-agent-sdk` to ensure the package is installed
See the [Troubleshooting](/en/docs/claude-code/troubleshooting) guide for common issues.
## Next Steps
* Explore the [Agent SDK Overview](/en/api/agent-sdk/overview) to learn about available features
* Check out the [TypeScript SDK Reference](/en/api/agent-sdk/typescript) for detailed API documentation
* Review the [Python SDK Reference](/en/api/agent-sdk/python) for Python-specific documentation
* Learn about [Custom Tools](/en/api/agent-sdk/custom-tools) and [MCP Integration](/en/api/agent-sdk/mcp)

View File

@@ -0,0 +1,126 @@
# Model configuration
> Learn about the Claude Code model configuration, including model aliases like `opusplan`
## Available models
For the `model` setting in Claude Code, you can either configure:
* A **model alias**
* A full **[model name](/en/docs/about-claude/models/overview#model-names)**
* For Bedrock, an ARN
### 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 |
### Setting your model
You can configure your model in several ways, listed in order of priority:
1. **During session** - Use `/model <alias|name>` to switch models mid-session
2. **At startup** - Launch with `claude --model <alias|name>`
3. **Environment variable** - Set `ANTHROPIC_MODEL=<alias|name>`
4. **Settings** - Configure permanently in your settings file using the `model`
field.
Example usage:
```bash theme={null}
# Start with Opus
claude --model opus
# Switch to Sonnet during session
/model sonnet
```
Example settings file:
```
{
"permissions": {
...
},
"model": "opus"
}
```
## Special model behavior
### `default` model setting
The behavior of `default` depends on your account type.
For certain Max users, Claude Code will automatically fall back to Sonnet if you
hit a usage threshold with Opus.
### `opusplan` model setting
The `opusplan` model alias provides an automated hybrid approach:
* **In plan mode** - Uses `opus` for complex reasoning and architecture
decisions
* **In execution mode** - Automatically switches to `sonnet` for code generation
and implementation
This gives you the best of both worlds: Opus's superior reasoning for planning,
and Sonnet's efficiency for execution.
### Extended context with \[1m]
For Console/API users, the `[1m]` suffix can be added to full model names to
enable a
[1 million token context window](/en/docs/build-with-claude/context-windows#1m-token-context-window).
```bash theme={null}
# Example of using a full model name with the [1m] suffix
/model anthropic.claude-sonnet-4-5-20250929-v1:0[1m]
```
Note: Extended context models have
[different pricing](/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)
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.
| 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) |
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:
| Env var | Description |
| ------------------------------- | ---------------------------------------------------------------------------------------------- |
| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |
| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models only |
| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models only |
| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models only |
These environment variables give you fine-grained control over prompt caching behavior. The global `DISABLE_PROMPT_CACHING` setting takes precedence over the model-specific settings, allowing you to quickly disable all caching when needed. The per-model settings are useful for selective control, such as when debugging specific models or working with cloud providers that may have different caching implementations.

View File

@@ -0,0 +1,507 @@
# Monitoring
> Learn how to enable and configure OpenTelemetry for Claude Code.
Claude Code supports OpenTelemetry (OTel) metrics and events for monitoring and observability.
All metrics are time series data exported via OpenTelemetry's standard metrics protocol, and events are exported via OpenTelemetry's logs/events protocol. It is the user's responsibility to ensure their metrics and logs backends are properly configured and that the aggregation granularity meets their monitoring requirements.
<Note>
OpenTelemetry support is currently in beta and details are subject to change.
</Note>
## Quick Start
Configure OpenTelemetry using environment variables:
```bash theme={null}
# 1. Enable telemetry
export CLAUDE_CODE_ENABLE_TELEMETRY=1
# 2. Choose exporters (both are optional - configure only what you need)
export OTEL_METRICS_EXPORTER=otlp # Options: otlp, prometheus, console
export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console
# 3. Configure OTLP endpoint (for OTLP exporter)
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
# 4. Set authentication (if required)
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token"
# 5. For debugging: reduce export intervals
export OTEL_METRIC_EXPORT_INTERVAL=10000 # 10 seconds (default: 60000ms)
export OTEL_LOGS_EXPORT_INTERVAL=5000 # 5 seconds (default: 5000ms)
# 6. Run Claude Code
claude
```
<Note>
The default export intervals are 60 seconds for metrics and 5 seconds for logs. During setup, you may want to use shorter intervals for debugging purposes. Remember to reset these for production use.
</Note>
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.
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`
Example managed settings configuration:
```json theme={null}
{
"env": {
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
"OTEL_METRICS_EXPORTER": "otlp",
"OTEL_LOGS_EXPORTER": "otlp",
"OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.company.com:4317",
"OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer company-token"
}
}
```
<Note>
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.
</Note>
## Configuration Details
### Common Configuration Variables
| Environment Variable | Description | Example Values |
| ----------------------------------------------- | --------------------------------------------------------- | ------------------------------------ |
| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |
| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |
| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` |
| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics (overrides general) | `grpc`, `http/json`, `http/protobuf` |
| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint (overrides general) | `http://localhost:4318/v1/metrics` |
| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs (overrides general) | `grpc`, `http/json`, `http/protobuf` |
| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint (overrides general) | `http://localhost:4318/v1/logs` |
| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |
| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file |
| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file |
| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |
| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |
| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |
### Metrics Cardinality Control
The following environment variables control which attributes are included in metrics to manage cardinality:
| Environment Variable | Description | Default Value | Example to Disable |
| ----------------------------------- | ----------------------------------------------- | ------------- | ------------------ |
| `OTEL_METRICS_INCLUDE_SESSION_ID` | Include session.id attribute in metrics | `true` | `false` |
| `OTEL_METRICS_INCLUDE_VERSION` | Include app.version attribute in metrics | `false` | `true` |
| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Include user.account\_uuid attribute in metrics | `true` | `false` |
These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis.
### Dynamic Headers
For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:
#### Settings Configuration
Add to your `.claude/settings.json`:
```json theme={null}
{
"otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh"
}
```
#### Script Requirements
The script must output valid JSON with string key-value pairs representing HTTP headers:
```bash theme={null}
#!/bin/bash
# Example: Multiple headers
echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"
```
#### 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
Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable:
```bash theme={null}
# Add custom attributes for team identification
export OTEL_RESOURCE_ATTRIBUTES="department=engineering,team.id=platform,cost_center=eng-123"
```
These custom attributes will be included in all metrics and events, allowing you to:
* Filter metrics by team or department
* Track costs per cost center
* Create team-specific dashboards
* Set up alerts for specific teams
<Warning>
**Important formatting requirements for OTEL\_RESOURCE\_ATTRIBUTES:**
The `OTEL_RESOURCE_ATTRIBUTES` environment variable follows the [W3C Baggage specification](https://www.w3.org/TR/baggage/), which has strict formatting requirements:
* **No spaces allowed**: Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid
* **Format**: Must be comma-separated key=value pairs: `key1=value1,key2=value2`
* **Allowed characters**: Only US-ASCII characters excluding control characters, whitespace, double quotes, commas, semicolons, and backslashes
* **Special characters**: Characters outside the allowed range must be percent-encoded
**Examples:**
```bash theme={null}
# ❌ Invalid - contains spaces
export OTEL_RESOURCE_ATTRIBUTES="org.name=John's Organization"
# ✅ Valid - use underscores or camelCase instead
export OTEL_RESOURCE_ATTRIBUTES="org.name=Johns_Organization"
export OTEL_RESOURCE_ATTRIBUTES="org.name=JohnsOrganization"
# ✅ Valid - percent-encode special characters if needed
export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"
```
Note: 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.
</Warning>
### Example Configurations
```bash theme={null}
# Console debugging (1-second intervals)
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=console
export OTEL_METRIC_EXPORT_INTERVAL=1000
# OTLP/gRPC
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
# Prometheus
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=prometheus
# Multiple exporters
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=console,otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=http/json
# Different endpoints/backends for metrics and logs
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.company.com:4318
export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.company.com:4317
# Metrics only (no events/logs)
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
# Events/logs only (no metrics)
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
```
## Available Metrics and Events
### Standard Attributes
All metrics and events share these standard attributes:
| Attribute | Description | Controlled By |
| ------------------- | ------------------------------------------------------------- | --------------------------------------------------- |
| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |
| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |
| `organization.id` | Organization UUID (when authenticated) | Always included when available |
| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |
| `terminal.type` | Terminal type (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |
### Metrics
Claude Code exports the following metrics:
| Metric Name | Description | Unit |
| ------------------------------------- | ----------------------------------------------- | ------ |
| `claude_code.session.count` | Count of CLI sessions started | count |
| `claude_code.lines_of_code.count` | Count of lines of code modified | count |
| `claude_code.pull_request.count` | Number of pull requests created | count |
| `claude_code.commit.count` | Number of git commits created | count |
| `claude_code.cost.usage` | Cost of the Claude Code session | USD |
| `claude_code.token.usage` | Number of tokens used | tokens |
| `claude_code.code_edit_tool.decision` | Count of code editing tool permission decisions | count |
| `claude_code.active_time.total` | Total active time in seconds | s |
### Metric Details
#### Session Counter
Incremented at the start of each session.
**Attributes**:
* All [standard attributes](#standard-attributes)
#### Lines of Code Counter
Incremented when code is added or removed.
**Attributes**:
* All [standard attributes](#standard-attributes)
* `type`: (`"added"`, `"removed"`)
#### Pull Request Counter
Incremented when creating pull requests via Claude Code.
**Attributes**:
* All [standard attributes](#standard-attributes)
#### Commit Counter
Incremented when creating git commits via Claude Code.
**Attributes**:
* All [standard attributes](#standard-attributes)
#### Cost Counter
Incremented after each API request.
**Attributes**:
* All [standard attributes](#standard-attributes)
* `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022")
#### Token Counter
Incremented after each API request.
**Attributes**:
* All [standard attributes](#standard-attributes)
* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)
* `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022")
#### Code Edit Tool Decision Counter
Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.
**Attributes**:
* All [standard attributes](#standard-attributes)
* `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)
* `decision`: User decision (`"accept"`, `"reject"`)
* `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.
#### Active Time Counter
Tracks actual time spent actively using Claude Code (not idle time). This metric is incremented during user interactions such as typing prompts or receiving responses.
**Attributes**:
* All [standard attributes](#standard-attributes)
### Events
Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):
#### User Prompt Event
Logged when a user submits a prompt.
**Event Name**: `claude_code.user_prompt`
**Attributes**:
* All [standard attributes](#standard-attributes)
* `event.name`: `"user_prompt"`
* `event.timestamp`: ISO 8601 timestamp
* `prompt_length`: Length of the prompt
* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)
#### Tool Result Event
Logged when a tool completes execution.
**Event Name**: `claude_code.tool_result`
**Attributes**:
* All [standard attributes](#standard-attributes)
* `event.name`: `"tool_result"`
* `event.timestamp`: ISO 8601 timestamp
* `tool_name`: Name of the tool
* `success`: `"true"` or `"false"`
* `duration_ms`: Execution time in milliseconds
* `error`: Error message (if failed)
* `decision`: Either `"accept"` or `"reject"`
* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`
* `tool_parameters`: JSON string containing tool-specific parameters (when available)
* For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox`
#### API Request Event
Logged for each API request to Claude.
**Event Name**: `claude_code.api_request`
**Attributes**:
* All [standard attributes](#standard-attributes)
* `event.name`: `"api_request"`
* `event.timestamp`: ISO 8601 timestamp
* `model`: Model used (e.g., "claude-3-5-sonnet-20241022")
* `cost_usd`: Estimated cost in USD
* `duration_ms`: Request duration in milliseconds
* `input_tokens`: Number of input tokens
* `output_tokens`: Number of output tokens
* `cache_read_tokens`: Number of tokens read from cache
* `cache_creation_tokens`: Number of tokens used for cache creation
#### API Error Event
Logged when an API request to Claude fails.
**Event Name**: `claude_code.api_error`
**Attributes**:
* All [standard attributes](#standard-attributes)
* `event.name`: `"api_error"`
* `event.timestamp`: ISO 8601 timestamp
* `model`: Model used (e.g., "claude-3-5-sonnet-20241022")
* `error`: Error message
* `status_code`: HTTP status code (if applicable)
* `duration_ms`: Request duration in milliseconds
* `attempt`: Attempt number (for retried requests)
#### Tool Decision Event
Logged when a tool permission decision is made (accept/reject).
**Event Name**: `claude_code.tool_decision`
**Attributes**:
* All [standard attributes](#standard-attributes)
* `event.name`: `"tool_decision"`
* `event.timestamp`: ISO 8601 timestamp
* `tool_name`: Name of the tool (e.g., "Read", "Edit", "Write", "NotebookEdit", etc.)
* `decision`: Either `"accept"` or `"reject"`
* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`
## Interpreting Metrics and Events Data
The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create:
### Usage Monitoring
| Metric | Analysis Opportunity |
| ------------------------------------------------------------- | --------------------------------------------------------- |
| `claude_code.token.usage` | Break down by `type` (input/output), user, team, or model |
| `claude_code.session.count` | Track adoption and engagement over time |
| `claude_code.lines_of_code.count` | Measure productivity by tracking code additions/removals |
| `claude_code.commit.count` & `claude_code.pull_request.count` | Understand impact on development workflows |
### Cost Monitoring
The `claude_code.cost.usage` metric helps with:
* Tracking usage trends across teams or individuals
* Identifying high-usage sessions for optimization
<Note>
Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).
</Note>
### Alerting and Segmentation
Common alerts to consider:
* Cost spikes
* Unusual token consumption
* High session volume from specific users
All metrics can be segmented by `user.account_uuid`, `organization.id`, `session.id`, `model`, and `app.version`.
### Event Analysis
The event data provides detailed insights into Claude Code interactions:
**Tool Usage Patterns**: Analyze tool result events to identify:
* Most frequently used tools
* Tool success rates
* Average tool execution times
* Error patterns by tool type
**Performance Monitoring**: Track API request durations and tool execution times to identify performance bottlenecks.
## Backend Considerations
Your choice of metrics and logs backends will determine the types of analyses you can perform:
### 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
### 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
For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.
## Service Information
All metrics and events are exported with the following resource attributes:
* `service.name`: `claude-code`
* `service.version`: Current Claude Code version
* `os.type`: Operating system type (e.g., `linux`, `darwin`, `windows`)
* `os.version`: Operating system version string
* `host.arch`: Host architecture (e.g., `amd64`, `arm64`)
* `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux)
* Meter Name: `com.anthropic.claude_code`
## ROI Measurement Resources
For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](https://github.com/anthropics/claude-code-monitoring-guide). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear.
## Security/Privacy Considerations
* Telemetry is opt-in and requires explicit configuration
* Sensitive information like API keys or file contents are never included in metrics or events
* User prompt content is redacted by default - only prompt length is recorded. To enable user prompt logging, set `OTEL_LOG_USER_PROMPTS=1`
## Monitoring Claude Code on Amazon Bedrock
For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md).

View File

@@ -0,0 +1,90 @@
# Enterprise network configuration
> Configure Claude Code for enterprise environments with proxy servers, custom Certificate Authorities (CA), and mutual Transport Layer Security (mTLS) authentication.
Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security.
<Note>
All environment variables shown on this page can also be configured in [`settings.json`](/en/docs/claude-code/settings).
</Note>
## Proxy configuration
### Environment variables
Claude Code respects standard proxy environment variables:
```bash theme={null}
# HTTPS proxy (recommended)
export HTTPS_PROXY=https://proxy.example.com:8080
# HTTP proxy (if HTTPS not available)
export HTTP_PROXY=http://proxy.example.com:8080
# Bypass proxy for specific requests - space-separated format
export NO_PROXY="localhost 192.168.1.1 example.com .example.com"
# Bypass proxy for specific requests - comma-separated format
export NO_PROXY="localhost,192.168.1.1,example.com,.example.com"
# Bypass proxy for all requests
export NO_PROXY="*"
```
<Note>
Claude Code does not support SOCKS proxies.
</Note>
### Basic authentication
If your proxy requires basic authentication, include credentials in the proxy URL:
```bash theme={null}
export HTTPS_PROXY=http://username:password@proxy.example.com:8080
```
<Warning>
Avoid hardcoding passwords in scripts. Use environment variables or secure credential storage instead.
</Warning>
<Tip>
For proxies requiring advanced authentication (NTLM, Kerberos, etc.), consider using an LLM Gateway service that supports your authentication method.
</Tip>
## Custom CA certificates
If your enterprise environment uses custom CAs for HTTPS connections (whether through a proxy or direct API access), configure Claude Code to trust them:
```bash theme={null}
export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem
```
## mTLS authentication
For enterprise environments requiring client certificate authentication:
```bash theme={null}
# Client certificate for authentication
export CLAUDE_CODE_CLIENT_CERT=/path/to/client-cert.pem
# Client private key
export CLAUDE_CODE_CLIENT_KEY=/path/to/client-key.pem
# Optional: Passphrase for encrypted private key
export CLAUDE_CODE_CLIENT_KEY_PASSPHRASE="your-passphrase"
```
## Network access requirements
Claude Code requires access to the following URLs:
* `api.anthropic.com` - Claude API endpoints
* `claude.ai` - WebFetch safeguards
* `statsig.anthropic.com` - Telemetry and metrics
* `sentry.io` - Error reporting
Ensure these URLs are allowlisted in your proxy configuration and firewall rules. This is especially important when using Claude Code in containerized or restricted network environments.
## Additional resources
* [Claude Code settings](/en/docs/claude-code/settings)
* [Environment variables reference](/en/docs/claude-code/settings#environment-variables)
* [Troubleshooting guide](/en/docs/claude-code/troubleshooting)

View File

@@ -0,0 +1,99 @@
# Output styles
> Adapt Claude Code for uses beyond software engineering
Output styles allow you to use Claude Code as any type of agent while keeping
its core capabilities, such as running local scripts, reading/writing files, and
tracking TODOs.
## Built-in output styles
Claude Code's **Default** output style is the existing system prompt, designed
to help you complete software engineering tasks efficiently.
There are two additional built-in output styles focused on teaching you the
codebase and how Claude operates:
* **Explanatory**: Provides educational "Insights" in between helping you
complete software engineering tasks. Helps you understand implementation
choices and codebase patterns.
* **Learning**: Collaborative, learn-by-doing mode where Claude will not only
share "Insights" while coding, but also ask you to contribute small, strategic
pieces of code yourself. Claude Code will add `TODO(human)` markers in your
code for you to implement.
## How output styles work
Output styles directly modify Claude Code's system prompt.
* 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
system prompt.
## Change your output style
You can either:
* Run `/output-style` to access the 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`.
## 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:
```markdown theme={null}
---
name: My Custom Style
description:
A brief description of what this style does, to be displayed to the user
---
# Custom Style Instructions
You are an interactive CLI tool that helps users with software engineering
tasks. [Your custom instructions here...]
## Specific Behaviors
[Define how the assistant should behave in this style...]
```
You can 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`).
## Comparisons to related features
### Output Styles vs. CLAUDE.md vs. --append-system-prompt
Output styles completely “turn off” the parts of Claude Codes default system
prompt specific to software engineering. Neither CLAUDE.md nor
`--append-system-prompt` edit Claude Codes default system prompt. CLAUDE.md
adds the contents as a user message *following* Claude Codes 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 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)
You can think of output styles as “stored system prompts” and custom slash
commands as “stored prompts”.

View File

@@ -0,0 +1,92 @@
# Claude Code overview
> Learn about Claude Code, Anthropic's agentic coding tool that lives in your terminal and helps you turn ideas into code faster than ever before.
## Get started in 30 seconds
Prerequisites:
* [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
# Navigate to your project
cd your-awesome-project
# Start coding with Claude
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)
(Got specific setup needs or hit issues? See [advanced setup](/en/docs/claude-code/setup) or [troubleshooting](/en/docs/claude-code/troubleshooting).)
<Note>
**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.
</Note>
## 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.
* **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.
* **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.
## Next steps
<CardGroup>
<Card title="Quickstart" icon="rocket" href="/en/docs/claude-code/quickstart">
See Claude Code in action with practical examples
</Card>
<Card title="Common workflows" icon="graduation-cap" href="/en/docs/claude-code/common-workflows">
Step-by-step guides for common workflows
</Card>
<Card title="Troubleshooting" icon="wrench" href="/en/docs/claude-code/troubleshooting">
Solutions for common issues with Claude Code
</Card>
<Card title="IDE setup" icon="laptop" href="/en/docs/claude-code/ide-integrations">
Add Claude Code to your IDE
</Card>
</CardGroup>
## Additional resources
<CardGroup>
<Card title="Host on AWS or GCP" icon="cloud" href="/en/docs/claude-code/third-party-integrations">
Configure Claude Code with Amazon Bedrock or Google Vertex AI
</Card>
<Card title="Settings" icon="gear" href="/en/docs/claude-code/settings">
Customize Claude Code for your workflow
</Card>
<Card title="Commands" icon="terminal" href="/en/docs/claude-code/cli-reference">
Learn about CLI commands and controls
</Card>
<Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">
Clone our development container reference implementation
</Card>
<Card title="Security" icon="shield" href="/en/docs/claude-code/security">
Discover Claude Code's safeguards and best practices for safe usage
</Card>
<Card title="Privacy and data usage" icon="lock" href="/en/docs/claude-code/data-usage">
Understand how Claude Code handles your data
</Card>
</CardGroup>

View File

@@ -0,0 +1,433 @@
# Plugin marketplaces
> Create and manage 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.
## 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
## 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
```
### Add Git repositories
```shell Add any git repository theme={null}
/plugin marketplace add https://gitlab.com/company/plugins.git
```
### Add local marketplaces for development
```shell Add local directory containing .claude-plugin/marketplace.json theme={null}
/plugin marketplace add ./my-marketplace
```
```shell Add direct path to marketplace.json file theme={null}
/plugin marketplace add ./path/to/marketplace.json
```
```shell Add remote marketplace.json via URL theme={null}
/plugin marketplace add https://url.of/marketplace.json
```
### Install plugins from marketplaces
Once you've added marketplaces, install plugins directly:
```shell Install from any known marketplace theme={null}
/plugin install plugin-name@marketplace-name
```
```shell Browse available plugins interactively theme={null}
/plugin
```
### Verify marketplace installation
After adding a marketplace:
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
## Configure team marketplaces
Set up automatic marketplace installation for team projects by specifying required marketplaces in `.claude/settings.json`:
```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.
### Prerequisites for marketplace creation
* Git repository (GitHub, GitLab, or other git hosting)
* Understanding of JSON file format
* One or more plugins to distribute
### Create the marketplace file
Create `.claude-plugin/marketplace.json` in your repository root:
```json theme={null}
{
"name": "company-tools",
"owner": {
"name": "DevTools Team",
"email": "devtools@company.com"
},
"plugins": [
{
"name": "code-formatter",
"source": "./plugins/formatter",
"description": "Automatic code formatting on save",
"version": "2.1.0",
"author": {
"name": "DevTools Team"
}
},
{
"name": "deployment-tools",
"source": {
"source": "github",
"repo": "company/deploy-plugin"
},
"description": "Deployment automation tools"
}
]
}
```
### Marketplace schema
#### Required fields
| Field | Type | Description |
| :-------- | :----- | :--------------------------------------------- |
| `name` | string | Marketplace identifier (kebab-case, no spaces) |
| `owner` | object | Marketplace maintainer information |
| `plugins` | array | List of available plugins |
#### Optional metadata
| Field | Type | Description |
| :--------------------- | :----- | :------------------------------------ |
| `metadata.description` | string | Brief marketplace description |
| `metadata.version` | string | Marketplace version |
| `metadata.pluginRoot` | string | Base path for relative plugin sources |
### Plugin entries
<Note>
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.
</Note>
**Required fields:**
| Field | Type | Description |
| :------- | :------------- | :---------------------------------------- |
| `name` | string | Plugin identifier (kebab-case, no spaces) |
| `source` | string\|object | Where to fetch the plugin from |
#### 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 (e.g., 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) <sup>1</sup> |
**Component configuration fields:**
| Field | Type | Description |
| :----------- | :------------- | :----------------------------------------------- |
| `commands` | string\|array | Custom paths to command files or directories |
| `agents` | string\|array | Custom paths to agent files |
| `hooks` | string\|object | Custom hooks configuration or path to hooks file |
| `mcpServers` | string\|object | MCP server configurations or path to MCP config |
*<sup>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.</sup>*
### Plugin sources
#### Relative paths
For plugins in the same repository:
```json theme={null}
{
"name": "my-plugin",
"source": "./plugins/my-plugin"
}
```
#### GitHub repositories
```json theme={null}
{
"name": "github-plugin",
"source": {
"source": "github",
"repo": "owner/plugin-repo"
}
}
```
#### Git repositories
```json theme={null}
{
"name": "git-plugin",
"source": {
"source": "url",
"url": "https://gitlab.com/team/plugin.git"
}
}
```
#### 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)):
```json theme={null}
{
"name": "enterprise-tools",
"source": {
"source": "github",
"repo": "company/enterprise-plugin"
},
"description": "Enterprise workflow automation tools",
"version": "2.1.0",
"author": {
"name": "Enterprise Team",
"email": "enterprise@company.com"
},
"homepage": "https://docs.company.com/plugins/enterprise-tools",
"repository": "https://github.com/company/enterprise-plugin",
"license": "MIT",
"keywords": ["enterprise", "workflow", "automation"],
"category": "productivity",
"commands": [
"./commands/core/",
"./commands/enterprise/",
"./commands/experimental/preview.md"
],
"agents": [
"./agents/security-reviewer.md",
"./agents/compliance-checker.md"
],
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [{"type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"}]
}
]
},
"mcpServers": {
"enterprise-db": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"]
}
},
"strict": false
}
```
<Note>
**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.
</Note>
***
## 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`
**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:
```shell theme={null}
/plugin marketplace add https://gitlab.com/company/plugins.git
```
### Use local marketplaces for development
Test your marketplace locally before distribution:
```shell Add local marketplace for testing theme={null}
/plugin marketplace add ./my-local-marketplace
```
```shell Test plugin installation theme={null}
/plugin install test-plugin@my-local-marketplace
```
## Manage marketplace operations
### List known marketplaces
```shell List all configured marketplaces theme={null}
/plugin marketplace list
```
Shows all configured marketplaces with their sources and status.
### Update marketplace metadata
```shell Refresh marketplace metadata theme={null}
/plugin marketplace update marketplace-name
```
Refreshes plugin listings and metadata from the marketplace source.
### Remove a marketplace
```shell Remove a marketplace theme={null}
/plugin marketplace remove marketplace-name
```
Removes the marketplace from your configuration.
<Warning>
Removing a marketplace will uninstall any plugins you installed from it.
</Warning>
***
## Troubleshooting marketplaces
### Common marketplace issues
#### Marketplace not loading
**Symptoms**: Can't add marketplace or see plugins from it
**Solutions**:
* Verify the marketplace URL is accessible
* Check that `.claude-plugin/marketplace.json` exists at the specified path
* Ensure JSON syntax is valid using `claude plugin validate`
* For private repositories, confirm you have access permissions
#### Plugin installation failures
**Symptoms**: Marketplace appears but plugin installation fails
**Solutions**:
* Verify plugin source URLs are accessible
* Check that plugin directories contain required files
* For GitHub sources, ensure repositories are public or you have access
* Test plugin sources manually by cloning/downloading
### Validation and testing
Test your marketplace before sharing:
```bash Validate marketplace JSON syntax theme={null}
claude plugin validate .
```
```shell Add marketplace for testing theme={null}
/plugin marketplace add ./path/to/marketplace
```
```shell Install test plugin theme={null}
/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).
***
## Next steps
### For marketplace users
* **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
### For marketplace creators
* **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
### For organizations
* **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
## 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

View File

@@ -0,0 +1,376 @@
# Plugins reference
> Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications.
<Tip>
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).
</Tip>
This reference provides complete technical specifications for the Claude Code plugin system, including component schemas, CLI commands, and development tools.
## Plugin components reference
This section documents the five types of components that plugins can provide.
### Commands
Plugins add custom slash commands that integrate seamlessly with Claude Code's command system.
**Location**: `commands/` directory in plugin root
**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).
### Agents
Plugins can provide specialized subagents for specific tasks that Claude can invoke automatically when appropriate.
**Location**: `agents/` directory in plugin root
**File format**: Markdown files describing agent capabilities
**Agent structure**:
```markdown theme={null}
---
description: What this agent specializes in
capabilities: ["task1", "task2", "task3"]
---
# Agent Name
Detailed description of the agent's role, expertise, and when Claude should invoke it.
## Capabilities
- Specific task the agent excels at
- Another specialized capability
- When to use this agent vs others
## Context and examples
Provide examples of when this agent should be used and what kinds of problems it solves.
```
**Integration points**:
* Agents appear in the `/agents` interface
* Claude can invoke agents automatically based on task context
* Agents can be invoked manually by users
* Plugin agents work alongside built-in Claude agents
### Skills
Plugins can provide Agent Skills that extend Claude's capabilities. Skills are model-invoked—Claude autonomously decides when to use them based on the task context.
**Location**: `skills/` directory in plugin root
**File format**: Directories containing `SKILL.md` files with frontmatter
**Skill structure**:
```
skills/
├── pdf-processor/
│ ├── SKILL.md
│ ├── reference.md (optional)
│ └── scripts/ (optional)
└── code-reviewer/
└── SKILL.md
```
**Integration behavior**:
* Plugin Skills are automatically discovered when the plugin is installed
* Claude autonomously invokes Skills based on matching task context
* Skills can include supporting files alongside SKILL.md
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)
### Hooks
Plugins can provide event handlers that respond to Claude Code events automatically.
**Location**: `hooks/hooks.json` in plugin root, or inline in plugin.json
**Format**: JSON configuration with event matchers and actions
**Hook configuration**:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format-code.sh"
}
]
}
]
}
}
```
**Available events**:
* `PreToolUse`: Before Claude uses any tool
* `PostToolUse`: After Claude uses any tool
* `UserPromptSubmit`: When user submits a prompt
* `Notification`: When Claude Code sends notifications
* `Stop`: When Claude attempts to stop
* `SubagentStop`: When a subagent attempts to stop
* `SessionStart`: At the beginning of sessions
* `SessionEnd`: At the end of sessions
* `PreCompact`: Before conversation history is compacted
**Hook types**:
* `command`: Execute shell commands or scripts
* `validation`: Validate file contents or project state
* `notification`: Send alerts or status updates
### MCP servers
Plugins can bundle Model Context Protocol (MCP) servers to connect Claude Code with external tools and services.
**Location**: `.mcp.json` in plugin root, or inline in plugin.json
**Format**: Standard MCP server configuration
**MCP server configuration**:
```json theme={null}
{
"mcpServers": {
"plugin-database": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
"env": {
"DB_PATH": "${CLAUDE_PLUGIN_ROOT}/data"
}
},
"plugin-api-client": {
"command": "npx",
"args": ["@company/mcp-server", "--plugin-mode"],
"cwd": "${CLAUDE_PLUGIN_ROOT}"
}
}
}
```
**Integration behavior**:
* Plugin MCP servers start automatically when the plugin is enabled
* Servers appear as standard MCP tools in Claude's toolkit
* Server capabilities integrate seamlessly with Claude's existing tools
* Plugin servers can be configured independently of user MCP servers
***
## Plugin manifest schema
The `plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options.
### Complete schema
```json theme={null}
{
"name": "plugin-name",
"version": "1.2.0",
"description": "Brief plugin description",
"author": {
"name": "Author Name",
"email": "author@example.com",
"url": "https://github.com/author"
},
"homepage": "https://docs.example.com/plugin",
"repository": "https://github.com/author/plugin",
"license": "MIT",
"keywords": ["keyword1", "keyword2"],
"commands": ["./custom/commands/special.md"],
"agents": "./custom/agents/",
"hooks": "./config/hooks.json",
"mcpServers": "./mcp-config.json"
}
```
### Required fields
| Field | Type | Description | Example |
| :----- | :----- | :---------------------------------------- | :------------------- |
| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |
### Metadata fields
| Field | Type | Description | Example |
| :------------ | :----- | :---------------------------------- | :------------------------------------------------- |
| `version` | string | Semantic version | `"2.1.0"` |
| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |
| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |
| `homepage` | string | Documentation URL | `"https://docs.example.com"` |
| `repository` | string | Source code URL | `"https://github.com/user/plugin"` |
| `license` | string | License identifier | `"MIT"`, `"Apache-2.0"` |
| `keywords` | array | Discovery tags | `["deployment", "ci-cd"]` |
### Component path fields
| Field | Type | Description | Example |
| :----------- | :------------- | :----------------------------------- | :------------------------------------- |
| `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` |
| `agents` | string\|array | Additional agent files | `"./custom/agents/"` |
| `hooks` | string\|object | Hook config path or inline config | `"./hooks.json"` |
| `mcpServers` | string\|object | MCP config path or inline config | `"./mcp.json"` |
### Path behavior rules
**Important**: Custom paths supplement default directories - they don't replace them.
* If `commands/` exists, it's loaded in addition to custom command paths
* All paths must be relative to plugin root and start with `./`
* Commands from custom paths use the same naming and namespacing rules
* Multiple paths can be specified as arrays for flexibility
**Path examples**:
```json theme={null}
{
"commands": [
"./specialized/deploy.md",
"./utilities/batch-process.md"
],
"agents": [
"./custom-agents/reviewer.md",
"./custom-agents/tester.md"
]
}
```
### Environment variables
**`${CLAUDE_PLUGIN_ROOT}`**: Contains the absolute path to your plugin directory. Use this in hooks, MCP servers, and scripts to ensure correct paths regardless of installation location.
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/process.sh"
}
]
}
]
}
}
```
***
## Plugin directory structure
### Standard plugin layout
A complete plugin follows this structure:
```
enterprise-plugin/
├── .claude-plugin/ # Metadata directory
│ └── plugin.json # Required: plugin manifest
├── commands/ # Default command location
│ ├── status.md
│ └── logs.md
├── agents/ # Default agent location
│ ├── security-reviewer.md
│ ├── performance-tester.md
│ └── compliance-checker.md
├── skills/ # Agent Skills
│ ├── code-reviewer/
│ │ └── SKILL.md
│ └── pdf-processor/
│ ├── SKILL.md
│ └── scripts/
├── hooks/ # Hook configurations
│ ├── hooks.json # Main hook config
│ └── security-hooks.json # Additional hooks
├── .mcp.json # MCP server definitions
├── scripts/ # Hook and utility scripts
│ ├── security-scan.sh
│ ├── format-code.py
│ └── deploy.js
├── LICENSE # License file
└── CHANGELOG.md # Version history
```
<Warning>
The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.
</Warning>
### File locations reference
| Component | Default Location | Purpose |
| :-------------- | :--------------------------- | :------------------------------- |
| **Manifest** | `.claude-plugin/plugin.json` | Required metadata file |
| **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 |
***
## Debugging and development tools
### Debugging commands
Use `claude --debug` to see plugin loading details:
```bash theme={null}
claude --debug
```
This shows:
* Which plugins are being loaded
* Any errors in plugin manifests
* Command, agent, and hook registration
* MCP server initialization
### Common issues
| Issue | Cause | Solution |
| :--------------------- | :------------------------------ | :--------------------------------------------------- |
| Plugin not loading | Invalid `plugin.json` | Validate JSON syntax |
| 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 `./` |
***
## Distribution and versioning reference
### Version management
Follow semantic versioning for plugin releases:
```json theme={null}
## 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
```

View File

@@ -0,0 +1,391 @@
# Plugins
> Extend Claude Code with custom commands, agents, hooks, and MCP servers through the plugin system.
<Tip>
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).
</Tip>
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.
## 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.
### Prerequisites
* Claude Code installed on your machine
* Basic familiarity with command-line tools
### Create your first plugin
<Steps>
<Step title="Create the marketplace structure">
```bash theme={null}
mkdir test-marketplace
cd test-marketplace
```
</Step>
<Step title="Create the plugin directory">
```bash theme={null}
mkdir my-first-plugin
cd my-first-plugin
```
</Step>
<Step title="Create the plugin manifest">
```bash Create .claude-plugin/plugin.json theme={null}
mkdir .claude-plugin
cat > .claude-plugin/plugin.json << 'EOF'
{
"name": "my-first-plugin",
"description": "A simple greeting plugin to learn the basics",
"version": "1.0.0",
"author": {
"name": "Your Name"
}
}
EOF
```
</Step>
<Step title="Add a custom command">
```bash Create commands/hello.md theme={null}
mkdir commands
cat > commands/hello.md << 'EOF'
---
description: Greet the user with a personalized message
---
# Hello Command
Greet the user warmly and ask how you can help them today. Make the greeting personal and encouraging.
EOF
```
</Step>
<Step title="Create the marketplace manifest">
```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
```
</Step>
<Step title="Install and test your plugin">
```bash Start Claude Code from parent directory theme={null}
cd ..
claude
```
```shell Add the test marketplace theme={null}
/plugin marketplace add ./test-marketplace
```
```shell Install your plugin theme={null}
/plugin install my-first-plugin@test-marketplace
```
Select "Install now". You'll then need to restart Claude Code in order to use the new plugin.
```shell Try your new command theme={null}
/hello
```
You'll see Claude use your greeting command! Check `/help` to see your new command listed.
</Step>
</Steps>
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 structure overview
Your plugin follows this basic structure:
```
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
```
**Additional components you can add:**
* **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
<Note>
**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).
</Note>
***
## Install and manage plugins
Learn how to discover, install, and manage plugins to extend your Claude Code capabilities.
### Prerequisites
* Claude Code installed and running
* Basic familiarity with command-line interfaces
### Add marketplaces
Marketplaces are catalogs of available plugins. Add them to discover and install plugins:
```shell Add a marketplace theme={null}
/plugin marketplace add your-org/claude-plugins
```
```shell Browse available plugins theme={null}
/plugin
```
For detailed marketplace management including Git repositories, local development, and team distribution, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces).
### Install plugins
#### Via interactive menu (recommended for discovery)
```shell Open the plugin management interface theme={null}
/plugin
```
Select "Browse Plugins" to see available options with descriptions, features, and installation options.
#### Via direct commands (for quick installation)
```shell Install a specific plugin theme={null}
/plugin install formatter@your-org
```
```shell Enable a disabled plugin theme={null}
/plugin enable plugin-name@marketplace-name
```
```shell Disable without uninstalling theme={null}
/plugin disable plugin-name@marketplace-name
```
```shell Completely remove a plugin theme={null}
/plugin uninstall plugin-name@marketplace-name
```
### Verify installation
After installing a plugin:
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
## Set up team plugin workflows
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.
**To set up team plugins:**
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
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).
***
## Develop more complex plugins
Once you're comfortable with basic plugins, you can create more sophisticated extensions.
### Add Skills to your plugin
Plugins can include [Agent Skills](/en/docs/claude-code/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).
### 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).
### Test your plugins locally
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.
<Steps>
<Step title="Set up your development structure">
Organize your plugin and marketplace for testing:
```bash Create directory structure theme={null}
mkdir dev-marketplace
cd dev-marketplace
mkdir my-plugin
```
This creates:
```
dev-marketplace/
├── .claude-plugin/marketplace.json (you'll create this)
└── my-plugin/ (your plugin under development)
├── .claude-plugin/plugin.json
├── commands/
├── agents/
└── hooks/
```
</Step>
<Step title="Create the marketplace manifest">
```bash Create marketplace.json theme={null}
mkdir .claude-plugin
cat > .claude-plugin/marketplace.json << 'EOF'
{
"name": "dev-marketplace",
"owner": {
"name": "Developer"
},
"plugins": [
{
"name": "my-plugin",
"source": "./my-plugin",
"description": "Plugin under development"
}
]
}
EOF
```
</Step>
<Step title="Install and test">
```bash Start Claude Code from parent directory theme={null}
cd ..
claude
```
```shell Add your development marketplace theme={null}
/plugin marketplace add ./dev-marketplace
```
```shell Install your plugin theme={null}
/plugin install my-plugin@dev-marketplace
```
Test your plugin components:
* Try your commands with `/command-name`
* Check that agents appear in `/agents`
* Verify hooks work as expected
</Step>
<Step title="Iterate on your plugin">
After making changes to your plugin code:
```shell Uninstall the current version theme={null}
/plugin uninstall my-plugin@dev-marketplace
```
```shell Reinstall to test changes theme={null}
/plugin install my-plugin@dev-marketplace
```
Repeat this cycle as you develop and refine your plugin.
</Step>
</Steps>
<Note>
**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.
</Note>
### Debug plugin issues
If your plugin isn't working as expected:
1. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/`
2. **Test components individually**: Check each command, agent, and hook separately
3. **Use validation and debugging tools**: See [Debugging and development tools](/en/docs/claude-code/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques
### Share your plugins
When your plugin is ready to share:
1. **Add documentation**: Include a README.md with installation and usage instructions
2. **Version your plugin**: Use semantic versioning in your `plugin.json`
3. **Create or use a marketplace**: Distribute through plugin marketplaces for easy installation
4. **Test with others**: Have team members test the plugin before wider distribution
<Note>
For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/docs/claude-code/plugins-reference).
</Note>
***
## 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
### For plugin developers
* **Create your first marketplace**: [Plugin marketplaces guide](/en/docs/claude-code/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
* **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/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

View File

@@ -0,0 +1,324 @@
# Quickstart
> Welcome to Claude Code!
This quickstart guide will have you using AI-powered coding assistance in just a few minutes. By the end, you'll understand how to use Claude Code for common development tasks.
## Before you begin
Make sure you have:
* A terminal or command prompt open
* A code project to work with
* A [Claude.ai](https://claude.ai) (recommended) or [Claude Console](https://console.anthropic.com/) account
## Step 1: Install Claude Code
### NPM Install
If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/):
```sh theme={null}
npm install -g @anthropic-ai/claude-code
```
### Native Install
<Tip>
Alternatively, try our new native install, now in beta.
</Tip>
**Homebrew (macOS, Linux):**
```sh theme={null}
brew install --cask claude-code
```
**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
```
## Step 2: Log in to your account
Claude Code requires an account to use. When you start an interactive session with the `claude` command, you'll need to log in:
```bash theme={null}
claude
# You'll be prompted to log in on first use
```
```bash theme={null}
/login
# Follow the prompts to log in with your account
```
You can log in using either account type:
* [Claude.ai](https://claude.ai) (subscription plans - 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.
<Note>
When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization.
</Note>
<Note>
You can have both account types under the same email address. If you need to log in again or switch accounts, use the `/login` command within Claude Code.
</Note>
## Step 3: Start your first session
Open your terminal in any project directory and start Claude Code:
```bash theme={null}
cd /path/to/your/project
claude
```
You'll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands or `/resume` to continue a previous conversation.
<Tip>
After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/docs/claude-code/iam#credential-management).
</Tip>
## Step 4: Ask your first question
Let's start with understanding your codebase. Try one of these commands:
```
> what does this project do?
```
Claude will analyze your files and provide a summary. You can also ask more specific questions:
```
> what technologies does this project use?
```
```
> where is the main entry point?
```
```
> explain the folder structure
```
You can also ask Claude about its own capabilities:
```
> what can Claude Code do?
```
```
> how do I use slash commands in Claude Code?
```
```
> can Claude Code work with Docker?
```
<Note>
Claude Code reads your files as needed - you don't have to manually add context. Claude also has access to its own documentation and can answer questions about its features and capabilities.
</Note>
## Step 5: Make your first code change
Now let's make Claude Code do some actual coding. Try a simple task:
```
> add a hello world function to the main file
```
Claude Code will:
1. Find the appropriate file
2. Show you the proposed changes
3. Ask for your approval
4. Make the edit
<Note>
Claude Code always asks for permission before modifying files. You can approve individual changes or enable "Accept all" mode for a session.
</Note>
## Step 6: Use Git with Claude Code
Claude Code makes Git operations conversational:
```
> what files have I changed?
```
```
> commit my changes with a descriptive message
```
You can also prompt for more complex Git operations:
```
> create a new branch called feature/quickstart
```
```
> show me the last 5 commits
```
```
> help me resolve merge conflicts
```
## Step 7: Fix a bug or add a feature
Claude is proficient at debugging and feature implementation.
Describe what you want in natural language:
```
> add input validation to the user registration form
```
Or fix existing issues:
```
> there's a bug where users can submit empty forms - fix it
```
Claude Code will:
* Locate the relevant code
* Understand the context
* Implement a solution
* Run tests if available
## Step 8: Test out other common workflows
There are a number of ways to work with Claude:
**Refactor code**
```
> refactor the authentication module to use async/await instead of callbacks
```
**Write tests**
```
> write unit tests for the calculator functions
```
**Update documentation**
```
> update the README with installation instructions
```
**Code review**
```
> review my changes and suggest improvements
```
<Tip>
**Remember**: Claude Code is your AI pair programmer. Talk to it like you would a helpful colleague - describe what you want to achieve, and it will help you get there.
</Tip>
## Essential commands
Here are the most important commands for daily use:
| Command | What it does | Example |
| ------------------- | --------------------------------- | ----------------------------------- |
| `claude` | Start interactive mode | `claude` |
| `claude "task"` | Run a one-time task | `claude "fix the build error"` |
| `claude -p "query"` | Run one-off query, then exit | `claude -p "explain this function"` |
| `claude -c` | Continue most recent conversation | `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/docs/claude-code/cli-reference) for a complete list of commands.
## Pro tips for beginners
<AccordionGroup>
<Accordion title="Be specific with your requests">
Instead of: "fix the bug"
Try: "fix the login bug where users see a blank screen after entering wrong credentials"
</Accordion>
<Accordion title="Use step-by-step instructions">
Break complex tasks into steps:
```
> 1. create a new database table for user profiles
```
```
> 2. create an API endpoint to get and update user profiles
```
```
> 3. build a webpage that allows users to see and edit their information
```
</Accordion>
<Accordion title="Let Claude explore first">
Before making changes, let Claude understand your code:
```
> analyze the database schema
```
```
> build a dashboard showing products that are most frequently returned by our UK customers
```
</Accordion>
<Accordion title="Save time with shortcuts">
* Press `?` to see all available keyboard shortcuts
* Use Tab for command completion
* Press ↑ for command history
* Type `/` to see all slash commands
</Accordion>
</AccordionGroup>
## What's next?
Now that you've learned the basics, explore more advanced features:
<CardGroup cols={3}>
<Card title="Common workflows" icon="graduation-cap" href="/en/docs/claude-code/common-workflows">
Step-by-step guides for common tasks
</Card>
<Card title="CLI reference" icon="terminal" href="/en/docs/claude-code/cli-reference">
Master all commands and options
</Card>
<Card title="Configuration" icon="gear" href="/en/docs/claude-code/settings">
Customize Claude Code for your workflow
</Card>
</CardGroup>
## Getting help
* **In Claude Code**: Type `/help` or ask "how do I..."
* **Documentation**: You're here! Browse other guides
* **Community**: Join our [Discord](https://www.anthropic.com/discord) for tips and support

View File

@@ -0,0 +1,117 @@
# Security
> Learn about Claude Code's security safeguards and best practices for safe usage.
## How we approach security
### Security foundation
Your code's security is paramount. Claude Code is built with security at its core, developed according to Anthropic's comprehensive security program. Learn more and access resources (SOC 2 Type 2 report, ISO 27001 certificate, etc.) at [Anthropic Trust Center](https://trust.anthropic.com).
### Permission-based architecture
Claude Code uses strict read-only permissions by default. When additional actions are needed (editing files, running tests, executing commands), Claude Code requests explicit permission. Users control whether to approve actions once or allow them automatically.
We designed Claude Code to be transparent and secure. For example, we require approval for bash commands before executing them, giving you direct control. This approach enables users and organizations to configure permissions directly.
For detailed permission configuration, see [Identity and Access Management](/en/docs/claude-code/iam).
### Built-in protections
To mitigate risks in agentic systems:
* **Write access restriction**: Claude Code can only write to the folder where it was started and its subfolders—it cannot modify files in parent directories without explicit permission. While Claude Code can read files outside the working directory (useful for accessing system libraries and dependencies), write operations are strictly confined to the project scope, creating a clear security boundary
* **Prompt fatigue mitigation**: Support for allowlisting frequently used safe commands per-user, per-codebase, or per-organization
* **Accept Edits mode**: Batch accept multiple edits while maintaining permission prompts for commands with side effects
### User responsibility
Claude Code only has the permissions you grant it. You're responsible for reviewing proposed code and commands for safety before approval.
## Protect against prompt injection
Prompt injection is a technique where an attacker attempts to override or manipulate an AI assistant's instructions by inserting malicious text. Claude Code includes several safeguards against these attacks:
### Core protections
* **Permission system**: Sensitive operations require explicit approval
* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request
* **Input sanitization**: Prevents command injection by processing user inputs
* **Command blocklist**: Blocks risky commands that fetch arbitrary content from the web like `curl` and `wget` by default. When explicitly allowed, be aware of [permission pattern limitations](/en/docs/claude-code/iam#tool-specific-permission-rules)
### Privacy safeguards
We have implemented several safeguards to protect your data, including:
* Limited retention periods for sensitive information (see the [Privacy Center](https://privacy.anthropic.com/en/articles/10023548-how-long-do-you-store-my-data) to learn more)
* Restricted access to user session data
* User control over data training preferences. Consumer users can change their [privacy settings](https://claude.ai/settings/privacy) at any time.
For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy).
### Additional safeguards
* **Network request approval**: Tools that make network requests require user approval by default
* **Isolated context windows**: Web fetch uses a separate context window to avoid injecting potentially malicious prompts
* **Trust verification**: First-time codebase runs and new MCP servers require trust verification
* Note: Trust verification is disabled when running non-interactively with the `-p` flag
* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted
* **Fail-closed matching**: Unmatched commands default to requiring manual approval
* **Natural language descriptions**: Complex bash commands include explanations for user understanding
* **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/docs/claude-code/iam#credential-management)
**Best practices for working with untrusted content**:
1. Review suggested commands before approval
2. Avoid piping untrusted content directly to Claude
3. Verify proposed changes to critical files
4. Use virtual machines (VMs) to run scripts and make tool calls, especially when interacting with external web services
5. Report suspicious behavior with `/bug`
<Warning>
While these protections significantly reduce risk, no system is completely
immune to all attacks. Always maintain good security practices when working
with any AI tool.
</Warning>
## MCP security
Claude Code allows users to configure Model Context Protocol (MCP) servers. The list of allowed MCP servers is configured in your source code, as part of Claude Code settings engineers check into source control.
We encourage either writing your own MCP servers or using MCP servers from providers that you trust. You are able to configure Claude Code permissions for MCP servers. Anthropic does not manage or audit any MCP servers.
## IDE security
See [here](/en/docs/claude-code/ide-integrations#security) for more information on the security of running Claude Code in an IDE.
## Security best practices
### Working with sensitive code
* Review all suggested changes before approval
* Use project-specific permission settings for sensitive repositories
* Consider using [devcontainers](/en/docs/claude-code/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
* 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)
### Reporting security issues
If you discover a security vulnerability in Claude Code:
1. Do not disclose it publicly
2. Report it through our [HackerOne program](https://hackerone.com/anthropic-vdp/reports/new?type=team\&report_type=vulnerability)
3. Include detailed reproduction steps
4. Allow time for us to address the issue before public disclosure
## Related resources
* [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
* [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance

View File

@@ -0,0 +1,349 @@
# Claude Code settings
> Configure Claude Code with global and project-level settings, and environment variables.
Claude Code offers a variety of settings to configure its behavior to meet your needs. You can configure Claude Code by running the `/config` command when using the interactive REPL, which opens a tabbed Settings interface where you can view status information and modify configuration options.
## Settings files
The `settings.json` file is our official mechanism for configuring Claude
Code through hierarchical settings:
* **User settings** are defined in `~/.claude/settings.json` and apply to all
projects.
* **Project settings** are saved in your project directory:
* `.claude/settings.json` for settings that are checked into source control and shared with your team
* `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created.
* 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:\ProgramData\ClaudeCode\managed-settings.json`
* 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):
* macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`
* Linux and WSL: `/etc/claude-code/managed-mcp.json`
* Windows: `C:\ProgramData\ClaudeCode\managed-mcp.json`
```JSON Example settings.json theme={null}
{
"permissions": {
"allow": [
"Bash(npm run lint)",
"Bash(npm run test:*)",
"Read(~/.zshrc)"
],
"deny": [
"Bash(curl:*)",
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)"
]
},
"env": {
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
"OTEL_METRICS_EXPORTER": "otlp"
}
}
```
### Available settings
`settings.json` supports a number of options:
| Key | Description | Example |
| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |
| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |
| `cleanupPeriodDays` | 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` |
### 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"` |
### Settings precedence
Settings are applied in order of precedence (highest to lowest):
1. **Enterprise managed policies** (`managed-settings.json`)
* Deployed by IT/DevOps
* Cannot be overridden
2. **Command line arguments**
* Temporary overrides for a specific session
3. **Local project settings** (`.claude/settings.local.json`)
* Personal project-specific settings
4. **Shared project settings** (`.claude/settings.json`)
* Team-shared project settings in source control
5. **User settings** (`~/.claude/settings.json`)
* Personal global settings
This hierarchy ensures that enterprise security policies are always enforced while still allowing teams and individuals to customize their experience.
### Key points about the configuration system
* **Memory files (CLAUDE.md)**: Contain instructions and context that Claude loads at startup
* **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior
* **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
<Note>
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.
</Note>
### 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:
```json theme={null}
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)",
"Read(./config/credentials.json)",
"Read(./build)"
]
}
}
```
This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns will be completely invisible to Claude Code, preventing any accidental exposure of sensitive data.
## Subagent configuration
Claude Code supports custom AI subagents that can be configured at both user and project levels. These subagents are stored as Markdown files with YAML frontmatter:
* **User subagents**: `~/.claude/agents/` - Available across all your projects
* **Project subagents**: `.claude/agents/` - Specific to your project and can be shared with your team
Subagent files define specialized AI assistants with custom prompts and tool permissions. Learn more about creating and using subagents in the [subagents documentation](/en/docs/claude-code/sub-agents).
## Plugin configuration
Claude Code supports a plugin system that lets you extend functionality with custom commands, agents, hooks, and MCP servers. Plugins are distributed through marketplaces and can be configured at both user and repository levels.
### Plugin settings
Plugin-related settings in `settings.json`:
```json theme={null}
{
"enabledPlugins": {
"formatter@company-tools": true,
"deployer@company-tools": true,
"analyzer@security-plugins": false
},
"extraKnownMarketplaces": {
"company-tools": {
"source": "github",
"repo": "company/claude-plugins"
}
}
}
```
#### `enabledPlugins`
Controls which plugins are enabled. Format: `"plugin-name@marketplace-name": true/false`
**Scopes**:
* **User settings** (`~/.claude/settings.json`): Personal plugin preferences
* **Project settings** (`.claude/settings.json`): Project-specific plugins shared with team
* **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed)
**Example**:
```json theme={null}
{
"enabledPlugins": {
"code-formatter@team-tools": true,
"deployment-tools@team-tools": true,
"experimental-features@personal": false
}
}
```
#### `extraKnownMarketplaces`
Defines additional marketplaces that should be made available for the repository. Typically used in repository-level settings to ensure team members have access to required plugin sources.
**When a repository includes `extraKnownMarketplaces`**:
1. Team members are prompted to install the marketplace when they trust the folder
2. Team members are then prompted to install plugins from that marketplace
3. Users can skip unwanted marketplaces or plugins (stored in user settings)
4. Installation respects trust boundaries and requires explicit consent
**Example**:
```json theme={null}
{
"extraKnownMarketplaces": {
"company-tools": {
"source": {
"source": "github",
"repo": "company-org/claude-plugins"
}
},
"security-plugins": {
"source": {
"source": "git",
"url": "https://git.company.com/security/plugins.git"
}
}
}
}
```
**Marketplace source types**:
* `github`: GitHub repository (uses `repo`)
* `git`: Any git URL (uses `url`)
* `directory`: Local filesystem path (uses `path`, for development only)
### Managing plugins
Use the `/plugin` command to manage plugins interactively:
* Browse available plugins from marketplaces
* Install/uninstall plugins
* Enable/disable plugins
* View plugin details (commands, agents, hooks provided)
* Add/remove marketplaces
Learn more about the plugin system in the [plugins documentation](/en/docs/claude-code/plugins).
## Environment variables
Claude Code supports the following environment variables to control its behavior:
<Note>
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.
</Note>
| 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 |
## 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).
### 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).
For example, you could automatically run a Python formatter after Claude
modifies Python files, or prevent modifications to production configuration
files by blocking Write operations to certain paths.
## See also
* [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

View File

@@ -0,0 +1,182 @@
# Set up Claude Code
> Install, authenticate, and start using Claude Code on your development machine.
## 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)
* **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).
## Standard installation
To install Claude Code, run the following command:
```sh theme={null}
npm install -g @anthropic-ai/claude-code
```
<Warning>
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.
</Warning>
<Note>
Some users may be automatically migrated to an improved installation method.
Run `claude doctor` after installation to check your installation type.
</Note>
After the installation process completes, navigate to your project and start Claude Code:
```bash theme={null}
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 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.
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.
<Note>
Claude Code securely stores your credentials. See [Credential Management](/en/docs/claude-code/iam#credential-management) for details.
</Note>
## 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/docs/claude-code/troubleshooting#linux-permission-issues).
<Tip>
Run `claude doctor` after installation to check your installation type and version.
</Tip>
### Global npm installation
Traditional method shown in the [install steps above](#standard-installation)
### Native binary installation (Beta)
If you have an existing installation of Claude Code, use `claude install` to start the native binary installation.
For a fresh install, run one of the following commands:
**Homebrew (macOS, Linux):**
```sh theme={null}
brew install --cask claude-code
```
<Note>
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).
</Note>
**macOS, Linux, WSL:**
```bash theme={null}
# Install stable version (default)
curl -fsSL https://claude.ai/install.sh | bash
# Install latest version
curl -fsSL https://claude.ai/install.sh | bash -s latest
# Install specific version number
curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58
```
<Note>
**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`.
</Note>
**Windows PowerShell:**
```powershell theme={null}
# Install stable version (default)
irm https://claude.ai/install.ps1 | iex
# Install latest version
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest
# Install specific version number
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58
```
**Windows CMD:**
```batch theme={null}
REM Install stable version (default)
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
REM Install latest version
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd latest && del install.cmd
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.
<Tip>
Make sure that you remove any outdated aliases or symlinks.
Once your installation is complete, run `claude doctor` to verify the installation.
</Tip>
### Local installation
* 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
## 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).
## Update Claude Code
### Auto updates
Claude Code automatically keeps itself up to date to ensure you have the latest features and security fixes.
* **Update checks**: Performed on startup and periodically while running
* **Update process**: Downloads and installs automatically in the background
* **Notifications**: You'll see a notification when updates are installed
* **Applying updates**: Updates take effect the next time you start Claude Code
**Disable auto-updates:**
Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/docs/claude-code/settings):
```bash theme={null}
export DISABLE_AUTOUPDATER=1
```
### Update manually
```bash theme={null}
claude update
```

View File

@@ -0,0 +1,598 @@
# Agent Skills
> 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.
## Prerequisites
* Claude Code version 1.0 or later
* Basic familiarity with [Claude Code](/en/docs/claude-code/quickstart)
## What are Agent Skills?
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.
**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).
**Benefits**:
* Extend Claude's capabilities for your specific workflows
* Share expertise across your team via git
* Reduce repetitive prompting
* Compose multiple Skills for complex tasks
Learn more in the [Agent Skills overview](/en/docs/agents-and-tools/agent-skills/overview).
<Note>
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).
</Note>
## Create a Skill
Skills are stored as directories containing a `SKILL.md` file.
### Personal Skills
Personal Skills are available across all your projects. Store them in `~/.claude/skills/`:
```bash theme={null}
mkdir -p ~/.claude/skills/my-skill-name
```
**Use personal Skills for**:
* Your individual workflows and preferences
* Experimental Skills you're developing
* Personal productivity tools
### Project Skills
Project Skills are shared with your team. Store them in `.claude/skills/` within your project:
```bash theme={null}
mkdir -p .claude/skills/my-skill-name
```
**Use project Skills for**:
* Team workflows and conventions
* Project-specific expertise
* Shared utilities and scripts
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.
## Write SKILL.md
Create a `SKILL.md` file with YAML frontmatter and Markdown content:
```yaml theme={null}
---
name: Your Skill Name
description: Brief description of what this Skill does and when to use it
---
# Your Skill Name
## Instructions
Provide clear, step-by-step guidance for Claude.
## Examples
Show concrete examples of using this Skill.
```
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.
## Add supporting files
Create additional files alongside SKILL.md:
```
my-skill/
├── SKILL.md (required)
├── reference.md (optional documentation)
├── examples.md (optional examples)
├── scripts/
│ └── helper.py (optional utility)
└── templates/
└── template.txt (optional template)
```
Reference these files from SKILL.md:
````markdown theme={null}
For advanced usage, see [reference.md](reference.md).
Run the helper script:
```bash
python scripts/helper.py input.txt
```
````
Claude reads these files only when needed, using progressive disclosure to manage context efficiently.
## Restrict tool access with allowed-tools
Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active:
```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
---
# Safe File Reader
This Skill provides read-only file access.
## 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 (e.g., 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.
<Note>
`allowed-tools` is only supported for Skills in Claude Code.
</Note>
## 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/
# View a specific Skill's content
cat ~/.claude/skills/my-skill/SKILL.md
```
## Test a Skill
After creating a Skill, test it by asking questions that match your description.
**Example**: If your description mentions "PDF files":
```
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
If Claude doesn't use your Skill, check these common issues:
### Make description specific
**Too vague**:
```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:
```bash theme={null}
# Personal
ls ~/.claude/skills/my-skill/SKILL.md
# Project
ls .claude/skills/my-skill/SKILL.md
```
### 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
```
## Share Skills with your team
**Recommended approach**: Distribute Skills through [plugins](/en/docs/claude-code/plugins).
To share Skills via plugin:
1. Create a plugin with Skills in the `skills/` directory
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).
You can also share Skills directly through project repositories:
### Step 1: Add Skill to your project
Create a project Skill:
```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
```
### Step 3: Team members get Skills automatically
When team members pull the latest changes, Skills are immediately available:
```bash theme={null}
git pull
claude # Skills are now available
```
## Update a Skill
Edit SKILL.md directly:
```bash theme={null}
# Personal Skill
code ~/.claude/skills/my-skill/SKILL.md
# Project Skill
code .claude/skills/my-skill/SKILL.md
```
Changes take effect the next time you start Claude Code. If Claude Code is already running, restart it to load the updates.
## Remove a Skill
Delete the Skill directory:
```bash theme={null}
# Personal
rm -rf ~/.claude/skills/my-skill
# Project
rm -rf .claude/skills/my-skill
git commit -m "Remove unused Skill"
```
## Best practices
### Keep Skills focused
One Skill should address one capability:
**Focused**:
* "PDF form filling"
* "Excel data analysis"
* "Git commit messages"
**Too broad**:
* "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**:
```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.
```
**Vague**:
```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
```
This helps team members understand what changed between versions.
## Troubleshooting
### Claude doesn't use my Skill
**Symptom**: You ask a relevant question but Claude doesn't use your Skill.
**Check**: Is the description specific enough?
Vague descriptions make discovery difficult. Include both what the Skill does and when to use it, with key terms users would mention.
**Too generic**:
```yaml theme={null}
description: Helps with data
```
**Specific**:
```yaml theme={null}
description: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files.
```
**Check**: Is the YAML valid?
Run validation to check for syntax errors:
```bash theme={null}
# View frontmatter
cat .claude/skills/my-skill/SKILL.md | head -n 15
# Check for common issues
# - Missing opening or closing ---
# - Tabs instead of spaces
# - Unquoted strings with special characters
```
**Check**: Is the Skill in the correct location?
```bash theme={null}
# Personal Skills
ls ~/.claude/skills/*/SKILL.md
# Project Skills
ls .claude/skills/*/SKILL.md
```
### Skill has errors
**Symptom**: The Skill loads but doesn't work correctly.
**Check**: Are dependencies available?
Claude will automatically install required dependencies (or ask for permission to install them) when it needs them.
**Check**: Do scripts have execute permissions?
```bash theme={null}
chmod +x .claude/skills/my-skill/scripts/*.py
```
**Check**: Are file paths correct?
Use forward slashes (Unix style) in all paths:
**Correct**: `scripts/helper.py`
**Wrong**: `scripts\helper.py` (Windows style)
### Multiple Skills conflict
**Symptom**: Claude uses the wrong Skill or seems confused between similar Skills.
**Be specific in descriptions**: Help Claude choose the right Skill by using distinct trigger terms in your descriptions.
Instead of:
```yaml theme={null}
# Skill 1
description: For data analysis
# Skill 2
description: For analyzing data
```
Use:
```yaml theme={null}
# Skill 1
description: Analyze sales data in Excel files and CRM exports. Use for sales reports, pipeline analysis, and revenue tracking.
# Skill 2
description: Analyze log files and system metrics data. Use for performance monitoring, debugging, and system diagnostics.
```
## Examples
### Simple Skill (single file)
```
commit-helper/
└── SKILL.md
```
```yaml theme={null}
---
name: Generating Commit Messages
description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes.
---
# Generating Commit Messages
## Instructions
1. Run `git diff --staged` to see changes
2. I'll suggest a commit message with:
- Summary under 50 characters
- Detailed description
- Affected components
## Best practices
- Use present tense
- Explain what and why, not how
```
### Skill with tool permissions
```
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
```
pdf-processing/
├── SKILL.md
├── FORMS.md
├── REFERENCE.md
└── scripts/
├── fill_form.py
└── validate.py
```
**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.
---
# PDF Processing
## Quick start
Extract text:
```python
import pdfplumber
with pdfplumber.open("doc.pdf") as pdf:
text = pdf.pages[0].extract_text()
```
For form filling, see [FORMS.md](FORMS.md).
For detailed API reference, see [REFERENCE.md](REFERENCE.md).
## Requirements
Packages must be installed in your environment:
```bash
pip install pypdf pdfplumber
```
````
<Note>
List required packages in the description. Packages must be installed in your environment before Claude can use them.
</Note>
Claude loads additional files only when needed.
## Next steps
<CardGroup cols={2}>
<Card title="Authoring best practices" icon="lightbulb" href="/en/docs/agents-and-tools/agent-skills/best-practices">
Write Skills that Claude can use effectively
</Card>
<Card title="Agent Skills overview" icon="book" href="/en/docs/agents-and-tools/agent-skills/overview">
Learn how Skills work across Claude products
</Card>
<Card title="Get started with Agent Skills" icon="rocket" href="/en/docs/agents-and-tools/agent-skills/quickstart">
Create your first Skill
</Card>
</CardGroup>

View File

@@ -0,0 +1,489 @@
# Slash commands
> Control Claude's behavior during an interactive session with slash commands.
## Built-in slash commands
| Command | Purpose |
| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------- |
| `/add-dir` | Add additional working directories |
| `/agents` | Manage custom AI subagents for specialized tasks |
| `/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 |
## Custom slash commands
Custom slash commands allow you to define frequently-used prompts as Markdown files that Claude Code can execute. Commands are organized by scope (project-specific or personal) and support namespacing through directory structures.
### Syntax
```
/<command-name> [arguments]
```
#### Parameters
| Parameter | Description |
| :--------------- | :---------------------------------------------------------------- |
| `<command-name>` | Name derived from the Markdown filename (without `.md` extension) |
| `[arguments]` | Optional arguments passed to the command |
### Command types
#### Project commands
Commands stored in your repository and shared with your team. When listed in `/help`, these commands show "(project)" after their description.
**Location**: `.claude/commands/`
In the following example, we create the `/optimize` command:
```bash theme={null}
# Create a project command
mkdir -p .claude/commands
echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md
```
#### Personal commands
Commands available across all your projects. When listed in `/help`, these commands show "(user)" after their description.
**Location**: `~/.claude/commands/`
In the following example, we create the `/security-review` command:
```bash theme={null}
# Create a personal command
mkdir -p ~/.claude/commands
echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md
```
### Features
#### Namespacing
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.
Conflicts between user and project level commands are not supported. Otherwise, multiple commands with the same base file name can coexist.
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)".
#### Arguments
Pass dynamic values to commands using argument placeholders:
##### All arguments with `$ARGUMENTS`
The `$ARGUMENTS` placeholder captures all arguments passed to the command:
```bash theme={null}
# Command definition
echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md
# Usage
> /fix-issue 123 high-priority
# $ARGUMENTS becomes: "123 high-priority"
```
##### Individual arguments with `$1`, `$2`, etc.
Access specific arguments individually using positional parameters (similar to shell scripts):
```bash theme={null}
# Command definition
echo 'Review PR #$1 with priority $2 and assign to $3' > .claude/commands/review-pr.md
# Usage
> /review-pr 456 high alice
# $1 becomes "456", $2 becomes "high", $3 becomes "alice"
```
Use positional arguments when you need to:
* Access arguments individually in different parts of your command
* Provide defaults for missing arguments
* Build more structured commands with specific parameter roles
#### Bash command execution
Execute bash commands before the slash command runs using the `!` prefix. The output is included in the command context. You *must* include `allowed-tools` with the `Bash` tool, but you can choose the specific bash commands to allow.
For example:
```markdown theme={null}
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
description: Create a git commit
---
## Context
- Current git status: !`git status`
- Current git diff (staged and unstaged changes): !`git diff HEAD`
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -10`
## Your task
Based on the above changes, create a single git commit.
```
#### File references
Include file contents in commands using the `@` prefix to [reference files](/en/docs/claude-code/common-workflows#reference-files-and-directories).
For example:
```markdown theme={null}
# Reference a specific file
Review the implementation in @src/utils/helpers.js
# Reference multiple files
Compare @src/old-version.js with @src/new-version.js
```
#### Thinking mode
Slash commands can trigger extended thinking by including [extended thinking keywords](/en/docs/claude-code/common-workflows#use-extended-thinking).
### Frontmatter
Command files support frontmatter, useful for specifying metadata about the command:
| Frontmatter | Purpose | Default |
| :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------- |
| `allowed-tools` | List of tools the command can use | Inherits from the conversation |
| `argument-hint` | The arguments expected for the slash command. Example: `argument-hint: add [tagId] \| remove [tagId] \| list`. This hint is shown to the user when auto-completing the slash command. | None |
| `description` | Brief description of the command | Uses the first line from the prompt |
| `model` | Specific model string (see [Models overview](/en/docs/about-claude/models/overview)) | Inherits from the conversation |
| `disable-model-invocation` | Whether to prevent `SlashCommand` tool from calling this command | false |
For example:
```markdown theme={null}
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
argument-hint: [message]
description: Create a git commit
model: claude-3-5-haiku-20241022
---
Create a git commit with message: $ARGUMENTS
```
Example using positional arguments:
```markdown theme={null}
---
argument-hint: [pr-number] [priority] [assignee]
description: Review pull request
---
Review PR #$1 with priority $2 and assign to $3.
Focus on security, performance, and code style.
```
## Plugin commands
[Plugins](/en/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).
### How plugin commands work
Plugin commands are:
* **Namespaced**: Commands can use the format `/plugin-name:command-name` to avoid conflicts (plugin prefix is optional unless there are name collisions)
* **Automatically available**: Once a plugin is installed and enabled, its commands appear in `/help`
* **Fully integrated**: Support all command features (arguments, frontmatter, bash execution, file references)
### Plugin command structure
**Location**: `commands/` directory in plugin root
**File format**: Markdown files with frontmatter
**Basic command structure**:
```markdown theme={null}
---
description: Brief description of what the command does
---
# Command Name
Detailed instructions for Claude on how to execute this command.
Include specific guidance on parameters, expected outcomes, and any special considerations.
```
**Advanced command features**:
* **Arguments**: Use placeholders like `{arg1}` in command descriptions
* **Subdirectories**: Organize commands in subdirectories for namespacing
* **Bash integration**: Commands can execute shell scripts and programs
* **File references**: Commands can reference and modify project files
### Invocation patterns
```shell Direct command (when no conflicts) theme={null}
/command-name
```
```shell Plugin-prefixed (when needed for disambiguation) theme={null}
/plugin-name:command-name
```
```shell With arguments (if command supports them) theme={null}
/command-name arg1 arg2
```
## MCP slash commands
MCP servers can expose prompts as slash commands that become available in Claude Code. These commands are dynamically discovered from connected MCP servers.
### Command format
MCP commands follow the pattern:
```
/mcp__<server-name>__<prompt-name> [arguments]
```
### Features
#### Dynamic discovery
MCP commands are automatically available when:
* An MCP server is connected and active
* The server exposes prompts through the MCP protocol
* The prompts are successfully retrieved during connection
#### Arguments
MCP prompts can accept arguments defined by the server:
```
# Without arguments
> /mcp__github__list_prs
# With arguments
> /mcp__github__pr_review 456
> /mcp__jira__create_issue "Bug title" high
```
#### Naming conventions
* Server and prompt names are normalized
* Spaces and special characters become underscores
* Names are lowercased for consistency
### Managing MCP connections
Use the `/mcp` command to:
* View all configured MCP servers
* Check connection status
* Authenticate with OAuth-enabled servers
* Clear authentication tokens
* View available tools and prompts from each server
### MCP permissions and wildcards
When configuring [permissions for MCP tools](/en/docs/claude-code/iam#tool-specific-permission-rules), note that **wildcards are not supported**:
* ✅ **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 all tools from an MCP server, use just the server name: `mcp__servername`. To approve specific tools only, list each tool individually.
## `SlashCommand` tool
The `SlashCommand` tool allows Claude to execute [custom slash commands](/en/docs/claude-code/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:
```
> Run /write-unit-test when you are about to start writing tests.
```
This tool puts each available custom slash command's metadata into context up to the
character budget limit. You can use `/context` to monitor token usage and follow
the operations below to manage context.
### `SlashCommand` tool supported commands
`SlashCommand` tool only supports custom slash commands that:
* Are user-defined. Built-in commands like `/compact` and `/init` are *not* supported.
* Have the `description` frontmatter field populated. We use the `description` in the context.
For Claude Code versions >= 1.0.124, you can see which custom slash commands
`SlashCommand` tool can invoke by running `claude --debug` and triggering a query.
### Disable `SlashCommand` tool
To prevent Claude from executing any slash commands via the tool:
```bash theme={null}
/permissions
# Add to deny rules: SlashCommand
```
This will also remove SlashCommand tool (and the slash 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.
### `SlashCommand` permission rules
The permission rules support:
* **Exact match**: `SlashCommand:/commit` (allows only `/commit` with no arguments)
* **Prefix match**: `SlashCommand:/review-pr:*` (allows `/review-pr` with any arguments)
### Character budget limit
The `SlashCommand` tool includes a character budget to limit the size of command
descriptions shown to Claude. This prevents token overflow when many commands
are available.
The budget includes each custom slash command's name, args, 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".
## Skills vs slash commands
**Slash commands** and **Agent Skills** serve different purposes in Claude Code:
### Use slash commands for
**Quick, frequently-used prompts**:
* Simple prompt snippets you use often
* Quick reminders or templates
* Frequently-used instructions that fit in one file
**Examples**:
* `/review` → "Review this code for bugs and suggest improvements"
* `/explain` → "Explain this code in simple terms"
* `/optimize` → "Analyze this code for performance issues"
### Use Skills for
**Comprehensive capabilities with structure**:
* Complex workflows with multiple steps
* Capabilities requiring scripts or utilities
* Knowledge organized across multiple files
* Team workflows you want to standardize
**Examples**:
* PDF processing Skill with form-filling scripts and validation
* Data analysis Skill with reference docs for different data types
* Documentation Skill with style guides and templates
### Key differences
| Aspect | Slash Commands | Agent Skills |
| -------------- | -------------------------------- | ----------------------------------- |
| **Complexity** | Simple prompts | Complex capabilities |
| **Structure** | Single .md file | Directory with SKILL.md + resources |
| **Discovery** | Explicit invocation (`/command`) | Automatic (based on context) |
| **Files** | One file only | Multiple files, scripts, templates |
| **Scope** | Project or personal | Project or personal |
| **Sharing** | Via git | Via git |
### Example comparison
**As a slash command**:
```markdown theme={null}
# .claude/commands/review.md
Review this code for:
- Security vulnerabilities
- Performance issues
- Code style violations
```
Usage: `/review` (manual invocation)
**As a Skill**:
```
.claude/skills/code-review/
├── SKILL.md (overview and workflows)
├── SECURITY.md (security checklist)
├── PERFORMANCE.md (performance patterns)
├── STYLE.md (style guide reference)
└── scripts/
└── run-linters.sh
```
Usage: "Can you review this code?" (automatic discovery)
The Skill provides richer context, validation scripts, and organized reference material.
### When to use each
**Use slash commands**:
* You invoke the same prompt repeatedly
* The prompt fits in a single file
* You want explicit control over when it runs
**Use Skills**:
* Claude should discover the capability automatically
* Multiple files or scripts are needed
* Complex workflows with validation steps
* Team needs standardized, detailed guidance
Both slash commands and Skills can coexist. Use the approach that fits your needs.
Learn more about [Agent Skills](/en/docs/claude-code/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

View File

@@ -0,0 +1,202 @@
# Status line configuration
> Create a custom status line for Claude Code to display contextual information
Make Claude Code your own with a custom status line that displays at the bottom of the Claude Code interface, similar to how terminal prompts (PS1) work in shells like Oh-my-zsh.
## Create a custom status line
You can either:
* Run `/statusline` to ask Claude Code to help you set up a custom status line. By default, it will try to reproduce your terminal's prompt, but you can provide additional instructions about the behavior you want to Claude Code, such as `/statusline show the model name in orange`
* Directly add a `statusLine` command to your `.claude/settings.json`:
```json theme={null}
{
"statusLine": {
"type": "command",
"command": "~/.claude/statusline.sh",
"padding": 0 // Optional: set to 0 to let status line go to edge
}
}
```
## How it Works
* The status line is updated when the conversation messages update
* Updates run at most every 300ms
* The first line of stdout from your command becomes the status line text
* ANSI color codes are supported for styling your status line
* Claude Code passes contextual information about the current session (model, directories, etc.) as JSON to your script via stdin
## JSON Input Structure
Your status line command receives structured data via stdin in JSON format:
```json theme={null}
{
"hook_event_name": "Status",
"session_id": "abc123...",
"transcript_path": "/path/to/transcript.json",
"cwd": "/current/working/directory",
"model": {
"id": "claude-opus-4-1",
"display_name": "Opus"
},
"workspace": {
"current_dir": "/current/working/directory",
"project_dir": "/original/project/directory"
},
"version": "1.0.80",
"output_style": {
"name": "default"
},
"cost": {
"total_cost_usd": 0.01234,
"total_duration_ms": 45000,
"total_api_duration_ms": 2300,
"total_lines_added": 156,
"total_lines_removed": 23
}
}
```
## Example Scripts
### Simple Status Line
```bash theme={null}
#!/bin/bash
# Read JSON input from stdin
input=$(cat)
# Extract values using jq
MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')
CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')
echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}"
```
### Git-Aware Status Line
```bash theme={null}
#!/bin/bash
# Read JSON input from stdin
input=$(cat)
# Extract values using jq
MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')
CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')
# Show git branch if in a git repo
GIT_BRANCH=""
if git rev-parse --git-dir > /dev/null 2>&1; then
BRANCH=$(git branch --show-current 2>/dev/null)
if [ -n "$BRANCH" ]; then
GIT_BRANCH=" | 🌿 $BRANCH"
fi
fi
echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}$GIT_BRANCH"
```
### Python Example
```python theme={null}
#!/usr/bin/env python3
import json
import sys
import os
# Read JSON from stdin
data = json.load(sys.stdin)
# Extract values
model = data['model']['display_name']
current_dir = os.path.basename(data['workspace']['current_dir'])
# Check for git branch
git_branch = ""
if os.path.exists('.git'):
try:
with open('.git/HEAD', 'r') as f:
ref = f.read().strip()
if ref.startswith('ref: refs/heads/'):
git_branch = f" | 🌿 {ref.replace('ref: refs/heads/', '')}"
except:
pass
print(f"[{model}] 📁 {current_dir}{git_branch}")
```
### Node.js Example
```javascript theme={null}
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
// Read JSON from stdin
let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
const data = JSON.parse(input);
// Extract values
const model = data.model.display_name;
const currentDir = path.basename(data.workspace.current_dir);
// Check for git branch
let gitBranch = '';
try {
const headContent = fs.readFileSync('.git/HEAD', 'utf8').trim();
if (headContent.startsWith('ref: refs/heads/')) {
gitBranch = ` | 🌿 ${headContent.replace('ref: refs/heads/', '')}`;
}
} catch (e) {
// Not a git repo or can't read HEAD
}
console.log(`[${model}] 📁 ${currentDir}${gitBranch}`);
});
```
### Helper Function Approach
For more complex bash scripts, you can create helper functions:
```bash theme={null}
#!/bin/bash
# Read JSON input once
input=$(cat)
# Helper functions for common extractions
get_model_name() { echo "$input" | jq -r '.model.display_name'; }
get_current_dir() { echo "$input" | jq -r '.workspace.current_dir'; }
get_project_dir() { echo "$input" | jq -r '.workspace.project_dir'; }
get_version() { echo "$input" | jq -r '.version'; }
get_cost() { echo "$input" | jq -r '.cost.total_cost_usd'; }
get_duration() { echo "$input" | jq -r '.cost.total_duration_ms'; }
get_lines_added() { echo "$input" | jq -r '.cost.total_lines_added'; }
get_lines_removed() { echo "$input" | jq -r '.cost.total_lines_removed'; }
# Use the helpers
MODEL=$(get_model_name)
DIR=$(get_current_dir)
echo "[$MODEL] 📁 ${DIR##*/}"
```
## Tips
* Keep your status line concise - it should fit on one line
* Use emojis (if your terminal supports them) and colors to make information scannable
* Use `jq` for JSON parsing in Bash (see examples above)
* Test your script by running it manually with mock JSON input: `echo '{"model":{"display_name":"Test"},"workspace":{"current_dir":"/test"}}' | ./statusline.sh`
* Consider caching expensive operations (like git status) if needed
## Troubleshooting
* If your status line doesn't appear, check that your script is executable (`chmod +x`)
* Ensure your script outputs to stdout (not stderr)

View File

@@ -0,0 +1,387 @@
# 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.
## What are subagents?
Subagents are pre-configured AI personalities that Claude Code can delegate tasks to. Each subagent:
* 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
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.
## Key benefits
<CardGroup cols={2}>
<Card title="Context preservation" icon="layer-group">
Each subagent operates in its own context, preventing pollution of the main conversation and keeping it focused on high-level objectives.
</Card>
<Card title="Specialized expertise" icon="brain">
Subagents can be fine-tuned with detailed instructions for specific domains, leading to higher success rates on designated tasks.
</Card>
<Card title="Reusability" icon="rotate">
Once created, subagents can be used across different projects and shared with your team for consistent workflows.
</Card>
<Card title="Flexible permissions" icon="shield-check">
Each subagent can have different tool access levels, allowing you to limit powerful tools to specific subagent types.
</Card>
</CardGroup>
## Quick start
To create your first subagent:
<Steps>
<Step title="Open the subagents interface">
Run the following command:
```
/agents
```
</Step>
<Step title="Select 'Create New Agent'">
Choose whether to create a project-level or user-level subagent
</Step>
<Step title="Define the 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
* If you're generating with Claude, you can also edit the system prompt in your own editor by pressing `e`
</Step>
<Step title="Save and use">
Your subagent is now available! Claude will use it automatically when appropriate, or you can invoke it explicitly:
```
> Use the code-reviewer subagent to check my recent changes
```
</Step>
</Steps>
## Subagent configuration
### File locations
Subagents are stored as Markdown files with YAML frontmatter in two possible locations:
| Type | Location | Scope | Priority |
| :-------------------- | :------------------ | :---------------------------- | :------- |
| **Project subagents** | `.claude/agents/` | Available in current project | Highest |
| **User subagents** | `~/.claude/agents/` | Available across all projects | Lower |
When subagent names conflict, project-level subagents take precedence over user-level subagents.
### 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.
**Plugin agent locations**: Plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest).
**Using plugin agents**:
* 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
See the [plugin components reference](/en/docs/claude-code/plugins-reference#agents) for details on creating plugin agents.
### CLI-based configuration
You can also define subagents dynamically using the `--agents` CLI flag, which accepts a JSON object:
```bash theme={null}
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
```
**Priority**: CLI-defined subagents have lower priority than project-level subagents but higher priority than user-level subagents.
**Use case**: This approach is useful for:
* 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
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).
### File format
Each subagent is defined in a Markdown file with this structure:
```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'
---
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.
```
#### 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) |
### Model selection
The `model` field allows you to control which [AI model](/en/docs/claude-code/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)
* **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`)
<Note>
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.
</Note>
### 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.
<Tip>
**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.
</Tip>
You have two options for configuring tools:
* **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`)
**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.
## Managing subagents
### Using the /agents command (Recommended)
The `/agents` command provides a comprehensive interface for subagent management:
```
/agents
```
This opens an interactive menu where you can:
* 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
* **Easily manage tool permissions** with a complete list of available tools
### Direct file management
You can also manage subagents by working directly with their files:
```bash theme={null}
# Create a project subagent
mkdir -p .claude/agents
echo '---
name: test-runner
description: Use proactively to run tests and fix failures
---
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
# Create a user subagent
mkdir -p ~/.claude/agents
# ... create subagent file
```
## Using subagents effectively
### Automatic delegation
Claude Code proactively delegates tasks based on:
* The task description in your request
* The `description` field in subagent configurations
* Current context and available tools
<Tip>
To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field.
</Tip>
### Explicit invocation
Request a specific subagent by mentioning it in your command:
```
> 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
```
## Example subagents
### Code reviewer
```markdown theme={null}
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code is simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.
```
### Debugger
```markdown theme={null}
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not just symptoms.
```
### Data scientist
```markdown theme={null}
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
model: sonnet
---
You are a data scientist specializing in SQL and BigQuery analysis.
When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly
Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations
For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data
Always ensure queries are efficient and cost-effective.
```
## 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.
* **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the subagent will perform.
* **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
### Chaining subagents
For complex workflows, you can chain multiple subagents:
```
> 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.
## Performance considerations
* **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.
## 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

View File

@@ -0,0 +1,69 @@
# Optimize your terminal setup
> Claude Code works best when your terminal is properly configured. Follow these guidelines to optimize your experience.
### Themes and appearance
Claude cannot control the theme of your terminal. That's handled by your terminal application. You can match Claude Code's theme to your terminal any time via the `/config` command.
For additional customization of the Claude Code interface itself, you can configure a [custom status line](/en/docs/claude-code/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:
* **Quick escape**: Type `\` followed by Enter to create a newline
* **Keyboard shortcut**: Set up a keybinding to insert a newline
#### Set up Shift+Enter (VS Code or iTerm2):
Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter.
#### Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app):
**For Mac Terminal.app:**
1. Open Settings → Profiles → Keyboard
2. Check "Use Option as Meta Key"
**For iTerm2 and VS Code terminal:**
1. Open Settings → Profiles → Keys
2. Under General, set Left/Right Option key to "Esc+"
### Notification setup
Never miss when Claude completes a task with proper notification configuration:
#### iTerm 2 system notifications
For iTerm 2 alerts when tasks complete:
1. Open iTerm 2 Preferences
2. Navigate to Profiles → Terminal
3. Enable "Silence bell" and Filter Alerts → "Send escape sequence-generated alerts"
4. Set your preferred notification delay
Note that these notifications are specific to iTerm 2 and not available in the default macOS Terminal.
#### Custom notification hooks
For advanced notification handling, you can create [notification hooks](/en/docs/claude-code/hooks#notification) to run your own logic.
### Handling large inputs
When working with extensive code or long instructions:
* **Avoid direct pasting**: Claude Code may struggle with very long pasted content
* **Use file-based workflows**: Write content to a file and ask Claude to read it
* **Be aware of VS Code limitations**: The VS Code terminal is particularly prone to truncating long pastes
### Vim Mode
Claude Code supports a subset of Vim keybindings that can be enabled with `/vim` or configured via `/config`.
The supported subset includes:
* Mode switching: `Esc` (to NORMAL), `i`/`I`, `a`/`A`, `o`/`O` (to INSERT)
* Navigation: `h`/`j`/`k`/`l`, `w`/`e`/`b`, `0`/`$`/`^`, `gg`/`G`
* Editing: `x`, `dw`/`de`/`db`/`dd`/`D`, `cw`/`ce`/`cb`/`cc`/`C`, `.` (repeat)

View File

@@ -0,0 +1,222 @@
# Enterprise deployment overview
> 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.
## Provider comparison
<table>
<thead>
<tr>
<th>Feature</th>
<th>Anthropic</th>
<th>Amazon Bedrock</th>
<th>Google Vertex AI</th>
</tr>
</thead>
<tbody>
<tr>
<td>Regions</td>
<td>Supported [countries](https://www.anthropic.com/supported-countries)</td>
<td>Multiple AWS [regions](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)</td>
<td>Multiple GCP [regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations)</td>
</tr>
<tr>
<td>Prompt caching</td>
<td>Enabled by default</td>
<td>Enabled by default</td>
<td>Enabled by default</td>
</tr>
<tr>
<td>Authentication</td>
<td>API key</td>
<td>AWS credentials (IAM)</td>
<td>GCP credentials (OAuth/Service Account)</td>
</tr>
<tr>
<td>Cost tracking</td>
<td>Dashboard</td>
<td>AWS Cost Explorer</td>
<td>GCP Billing</td>
</tr>
<tr>
<td>Enterprise features</td>
<td>Teams, usage monitoring</td>
<td>IAM policies, CloudTrail</td>
<td>IAM roles, Cloud Audit Logs</td>
</tr>
</tbody>
</table>
## Cloud providers
<CardGroup cols={2}>
<Card title="Amazon Bedrock" icon="aws" href="/en/docs/claude-code/amazon-bedrock">
Use Claude models through AWS infrastructure with IAM-based authentication and AWS-native monitoring
</Card>
<Card title="Google Vertex AI" icon="google" href="/en/docs/claude-code/google-vertex-ai">
Access Claude models via Google Cloud Platform with enterprise-grade security and compliance
</Card>
</CardGroup>
## Corporate infrastructure
<CardGroup cols={2}>
<Card title="Enterprise Network" icon="shield" href="/en/docs/claude-code/network-config">
Configure Claude Code to work with your organization's proxy servers and SSL/TLS requirements
</Card>
<Card title="LLM Gateway" icon="server" href="/en/docs/claude-code/llm-gateway">
Deploy centralized model access with usage tracking, budgeting, and audit logging
</Card>
</CardGroup>
## Configuration overview
Claude Code supports flexible configuration options that allow you to combine different providers and infrastructure:
<Note>
Understand the difference between:
* **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`)
Both configurations can be used in tandem.
</Note>
### Using Bedrock with corporate proxy
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
# Configure corporate proxy
export HTTPS_PROXY='https://proxy.example.com:8080'
```
### Using Bedrock with LLM Gateway
Use a gateway service that provides Bedrock-compatible endpoints:
```bash theme={null}
# Enable Bedrock
export CLAUDE_CODE_USE_BEDROCK=1
# Configure LLM gateway
export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock'
export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # If gateway handles AWS auth
```
### Using Vertex AI with corporate proxy
Route Vertex AI traffic through a corporate HTTP/HTTPS proxy:
```bash theme={null}
# Enable Vertex
export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION=us-east5
export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id
# Configure corporate proxy
export HTTPS_PROXY='https://proxy.example.com:8080'
```
### 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/docs/claude-code/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
### 1. 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/docs/claude-code/memory).
### 2. 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
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
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).
### 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).
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

View File

@@ -0,0 +1,336 @@
# Troubleshooting
> Discover solutions to common issues with Claude Code installation and usage.
## Common installation issues
### Windows installation issues: errors in WSL
You might encounter the following issues in WSL:
**OS/platform detection issues**: If you receive an error during installation, WSL may be using Windows `npm`. Try:
* Run `npm config set os linux` before installation
* Install with `npm install -g @anthropic-ai/claude-code --force --no-os-check` (Do NOT use `sudo`)
**Node not found errors**: If you see `exec: node: not found` when running `claude`, your WSL environment may be using a Windows installation of Node.js. You can confirm this with `which npm` and `which node`, which should point to Linux paths starting with `/usr/` rather than `/mnt/c/`. To fix this, try installing Node via your Linux distribution's package manager or via [`nvm`](https://github.com/nvm-sh/nvm).
**nvm version conflicts**: If you have nvm installed in both WSL and Windows, you may experience version conflicts when switching Node versions in WSL. This happens because WSL imports the Windows PATH by default, causing Windows nvm/npm to take priority over the WSL installation.
You can identify this issue by:
* Running `which npm` and `which node` - if they point to Windows paths (starting with `/mnt/c/`), Windows versions are being used
* Experiencing broken functionality after switching Node versions with nvm in WSL
To resolve this issue, fix your Linux PATH to ensure the Linux node/npm versions take priority:
**Primary solution: Ensure nvm is properly loaded in your shell**
The most common cause is that nvm isn't loaded in non-interactive shells. Add the following to your shell configuration file (`~/.bashrc`, `~/.zshrc`, etc.):
```bash theme={null}
# Load nvm if it exists
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
```
Or run directly in your current session:
```bash theme={null}
source ~/.nvm/nvm.sh
```
**Alternative: Adjust PATH order**
If nvm is properly loaded but Windows paths still take priority, you can explicitly prepend your Linux paths to PATH in your shell configuration:
```bash theme={null}
export PATH="$HOME/.nvm/versions/node/$(node -v)/bin:$PATH"
```
<Warning>
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.
</Warning>
### 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`).
#### Recommended solution: Native Claude Code installation
Claude Code has a native installation that doesn't depend on npm or Node.js.
<Note>
The native Claude Code installer is currently in beta.
</Note>
Use the following command to run the native installer.
**macOS, Linux, WSL:**
```bash theme={null}
# Install stable version (default)
curl -fsSL https://claude.ai/install.sh | bash
# Install latest version
curl -fsSL https://claude.ai/install.sh | bash -s latest
# Install specific version number
curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58
```
**Windows PowerShell:**
```powershell theme={null}
# Install stable version (default)
irm https://claude.ai/install.ps1 | iex
# Install latest version
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest
# Install specific version number
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58
```
This command installs the appropriate build of Claude Code for your operating system and architecture and adds a symlink to the installation at `~/.local/bin/claude`.
<Tip>
Make sure that you have the installation directory in your system PATH.
</Tip>
#### 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}
claude doctor # Check installation health
```
## Permissions and authentication
### Repeated permission prompts
If you find yourself repeatedly approving the same commands, you can allow specific tools
to run without approval using the `/permissions` command. See [Permissions docs](/en/docs/claude-code/iam#configuring-permissions).
### Authentication issues
If you're experiencing authentication problems:
1. Run `/logout` to sign out completely
2. Close Claude Code
3. Restart with `claude` and complete the authentication process again
If problems persist, try:
```bash theme={null}
rm -rf ~/.config/claude-code/auth.json
claude
```
This removes your stored authentication information and forces a clean login.
## Performance and stability
### High CPU or memory usage
Claude Code is designed to work with most development environments, but may consume significant resources when processing large codebases. If you're experiencing performance issues:
1. Use `/compact` regularly to reduce context size
2. Close and restart Claude Code between major tasks
3. Consider adding large build directories to your `.gitignore` file
### Command hangs or freezes
If Claude Code seems unresponsive:
1. Press Ctrl+C to attempt to cancel the current operation
2. If unresponsive, you may need to close the terminal and restart
### Search and discovery issues
If Search tool, `@file` mentions, custom agents, and custom slash commands aren't working, install system `ripgrep`:
```bash theme={null}
# macOS (Homebrew)
brew install ripgrep
# Windows (winget)
winget install BurntSushi.ripgrep.MSVC
# Ubuntu/Debian
sudo apt install ripgrep
# Alpine Linux
apk add ripgrep
# Arch Linux
pacman -S ripgrep
```
Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/docs/claude-code/settings#environment-variables).
### Slow or incomplete search results on WSL
Disk read performance penalties when [working across file systems on WSL](https://learn.microsoft.com/en-us/windows/wsl/filesystems) may result in fewer-than-expected matches (but not a complete lack of search functionality) when using Claude Code on WSL.
<Note>
`/doctor` will show Search as OK in this case.
</Note>
**Solutions:**
1. **Submit more specific searches**: Reduce the number of files searched by specifying directories or file types: "Search for JWT validation logic in the auth-service package" or "Find use of md5 hash in JS files".
2. **Move project to Linux filesystem**: If possible, ensure your project is located on the Linux filesystem (`/home/`) rather than the Windows filesystem (`/mnt/c/`).
3. **Use native Windows instead**: Consider running Claude Code natively on Windows instead of through WSL, for better file system performance.
## IDE integration issues
### JetBrains IDE not detected on WSL2
If you're using Claude Code on WSL2 with JetBrains IDEs and getting "No available IDEs detected" errors, this is likely due to WSL2's networking configuration or Windows Firewall blocking the connection.
#### WSL2 networking modes
WSL2 uses NAT networking by default, which can prevent IDE detection. You have two options:
**Option 1: Configure Windows Firewall** (recommended)
1. Find your WSL2 IP address:
```bash theme={null}
wsl hostname -I
# Example output: 172.21.123.456
```
2. Open PowerShell as Administrator and create a firewall rule:
```powershell theme={null}
New-NetFirewallRule -DisplayName "Allow WSL2 Internal Traffic" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16 -LocalAddress 172.21.0.0/16
```
(Adjust the IP range based on your WSL2 subnet from step 1)
3. Restart both your IDE and Claude Code
**Option 2: Switch to mirrored networking**
Add to `.wslconfig` in your Windows user directory:
```ini theme={null}
[wsl2]
networkingMode=mirrored
```
Then restart WSL with `wsl --shutdown` from PowerShell.
<Note>
These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations.
</Note>
For additional JetBrains configuration tips, see our [IDE integration guide](/en/docs/claude-code/ide-integrations#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)
### ESC key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals
If you're using Claude Code in JetBrains terminals and the ESC key doesn't interrupt the agent as expected, this is likely due to a keybinding clash with JetBrains' default shortcuts.
To fix this issue:
1. Go to Settings → Tools → Terminal
2. Either:
* Uncheck "Move focus to the editor with Escape", or
* Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut
3. Apply the changes
This allows the ESC key to properly interrupt Claude Code operations.
## Markdown formatting issues
Claude Code sometimes generates markdown files with missing language tags on code fences, which can affect syntax highlighting and readability in GitHub, editors, and documentation tools.
### Missing language tags in code blocks
If you notice code blocks like this in generated markdown:
````markdown theme={null}
```
function example() {
return "hello";
}
```
````
Instead of properly tagged blocks like:
````markdown theme={null}
```javascript
function example() {
return "hello";
}
```
````
**Solutions:**
1. **Ask Claude to add language tags**: Simply request "Please 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.
3. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed.
### Inconsistent spacing and formatting
If generated markdown has excessive blank lines or inconsistent spacing:
**Solutions:**
1. **Request formatting corrections**: Ask Claude to "Fix spacing and formatting issues in this markdown file."
2. **Use formatting tools**: Set up hooks to run markdown formatters like `prettier` or custom formatting scripts on generated markdown files.
3. **Specify formatting preferences**: Include formatting requirements in your prompts or project [memory](/en/docs/claude-code/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)
* **Set up validation hooks**: Use post-processing hooks to automatically verify and fix common formatting issues
## Getting more help
If you're experiencing issues not covered here:
1. Use the `/bug` command within Claude Code to report problems directly to Anthropic
2. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues
3. Run `/doctor` to 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

View File

@@ -0,0 +1,130 @@
# Visual Studio Code
> Use Claude Code with Visual Studio Code through our native extension or CLI integration
<img src="https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=600835067c8b03557a0529978e3f0261" alt="Claude Code VS Code Extension Interface" data-og-width="2500" width="2500" data-og-height="1155" height="1155" data-path="images/vs-code-extension-interface.jpg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=280&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=c11a25932f84ca58124a368156b476d2 280w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=560&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=3642697ed4d8a6c02396c403bf7aae44 560w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=840&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=fb3cb16e752060fbeb0f5e8ba775798b 840w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=1100&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=1c6073edc8fcfcbc8e237cbf5f25cdc6 1100w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=1650&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=152628678fe3301018b79e932706c430 1650w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=2500&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=7ac83b2db00366c9a745380571a748ab 2500w" />
## VS Code Extension (Beta)
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.
### Features
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
* **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
* **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
### Requirements
* VS Code 1.98.0 or higher
### Installation
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
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 on them to expand for full details
### Using Third-Party Providers (Vertex and Bedrock)
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:
1. Open VS Code settings
2. Search for "Claude Code: Environment Variables"
3. Add the required environment variables
#### Environment Variables
| 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"` |
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)
### Not Yet Implemented
The following features are not 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
* **Checkpoints**: Save and restore conversation state at specific points
* **Advanced shortcuts**:
* `#` shortcut to add to memory
* `!` shortcut to run bash commands directly
* **Tab completion**: File path completion with tab key
We are working on adding these features in future updates.
## 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.
When running in VS Code, consider:
* 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
## 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 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.
Both the extension and CLI integration work with Visual Studio Code, Cursor, Windsurf, and VSCodium.
## Troubleshooting
### 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
### 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:
* 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)
For additional help, see our [troubleshooting guide](/en/docs/claude-code/troubleshooting).

View File

@@ -0,0 +1,119 @@
#!/usr/bin/env node
/**
* update_docs.js
*
* Fetches the latest Claude Code documentation from docs.claude.com
* and saves it to the references/ directory.
*
* Usage: node scripts/update_docs.js
*/
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 REFERENCES_DIR = path.join(__dirname, '..', 'references');
/**
* Fetch content from a URL using https module
*/
function fetchUrl(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(data);
} else {
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
}
});
}).on('error', reject);
});
}
/**
* Extract Claude Code doc URLs from 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();
}
/**
* Fetch and save a single documentation page
*/
async function fetchAndSaveDoc(url) {
const filename = path.basename(url);
const filepath = path.join(REFERENCES_DIR, filename);
try {
console.log(` Fetching ${filename}...`);
const content = await fetchUrl(url);
fs.writeFileSync(filepath, content, 'utf8');
return { url, filename, success: true };
} catch (error) {
console.error(` ❌ Failed to fetch ${filename}: ${error.message}`);
return { url, filename, success: false, error: error.message };
}
}
/**
* Main execution
*/
async function main() {
console.log('🚀 Claude Code Documentation Updater\n');
// Ensure references directory exists
if (!fs.existsSync(REFERENCES_DIR)) {
fs.mkdirSync(REFERENCES_DIR, { recursive: true });
}
// Get all Claude Code documentation URLs
const urls = await getClaudeCodeUrls();
console.log(`✅ Found ${urls.length} Claude Code documentation pages\n`);
// Fetch all documentation pages
console.log('📥 Downloading documentation...');
const results = [];
for (const url of urls) {
const result = await fetchAndSaveDoc(url);
results.push(result);
// Small delay to be nice to the server
await new Promise(resolve => setTimeout(resolve, 100));
}
// Summary
const successful = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;
console.log(`\n✅ Documentation update complete!`);
console.log(` ${successful} files downloaded successfully`);
if (failed > 0) {
console.log(` ${failed} files failed to download`);
}
console.log(`\n📁 Documentation saved to: ${REFERENCES_DIR}`);
}
// Run if called directly
if (require.main === module) {
main().catch(error => {
console.error('❌ Error:', error.message);
process.exit(1);
});
}
module.exports = { getClaudeCodeUrls, fetchAndSaveDoc };